假设我们想要获取 tensorflow 变量的值,我们可以在 session 下运行它。
假设a = tf.Variable(...)
然后可以使用sess.run(a)
获取它的值
但是如果有两个名称相同但名称范围不同的变量,如何获取各个变量的值?
with tf.name_scope("x"):
a = tf.Variable(...)
with tf.name_scope("y"):
a = tf.Variable(...)
那么如何分别获取x
下的a
和y
下的a
的值呢?
如果我执行 sess.run(a)
,我将在 name_scope y
(最近的一个)下获得值
最佳答案
您可以查看变量的名称并通过范围/名称获取它们:
with tf.variable_scope("x"):
a = tf.get_variable('a', initializer=1)
with tf.variable_scope("y"):
a = tf.get_variable('a', initializer=2)
with tf.Session() as s:
s.run(tf.global_variables_initializer())
[print(var.op.name) for var in tf.global_variables()]
res = s.run(['x/a:0', 'y/a:0'])
print(res)
返回:
x/a
y/a
[1, 2]
关于python - 如何获取特定名称范围下的 tensorflow 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48119449/