在尝试通过创建一个简单的示例来可视化所有内容之前,我在理解variable_scope和name_scope (它们看起来几乎相同)之间的区别时遇到了问题:
import tensorflow as tf
def scoping(fn, scope1, scope2, vals):
with fn(scope1):
a = tf.Variable(vals[0], name='a')
b = tf.get_variable('b', initializer=vals[1])
c = tf.constant(vals[2], name='c')
with fn(scope2):
d = tf.add(a * b, c, name='res')
print '\n '.join([scope1, a.name, b.name, c.name, d.name]), '\n'
return d
d1 = scoping(tf.variable_scope, 'scope_vars', 'res', [1, 2, 3])
d2 = scoping(tf.name_scope, 'scope_name', 'res', [1, 2, 3])
with tf.Session() as sess:
writer = tf.summary.FileWriter('logs', sess.graph)
sess.run(tf.global_variables_initializer())
print sess.run([d1, d2])
writer.close()
在这里,我创建了一个函数,该函数创建一些变量和常量,并在范围内对它们进行分组(取决于我提供的类型)。在此函数中,我还将打印所有变量的名称。之后,我执行图形以获取结果值的值,并保存事件文件以在张量板上对其进行调查。如果运行此命令,则会得到以下信息:
scope_vars
scope_vars/a:0
scope_vars/b:0
scope_vars/c:0
scope_vars/res/res:0
scope_name
scope_name/a:0
b:0
scope_name/c:0
scope_name/res/res:0
如果打开TB,您会看到类似的图案(因为您看到b
在scope_name
矩形的外部):
这给你答案 :
现在,您看到tf.variable_scope()
在所有变量(无论如何创建它们),ops,常量的名称之前添加了一个前缀。另一方面, tf.name_scope()
忽略使用tf.get_variable()
创建的变量,因为它假定您知道要使用哪个变量以及在哪个范围内。
关于共享变量的良好文档告诉您
tf.variable_scope()
:管理传递给tf.get_variable()
名称的名称空间。
同一文档提供了更多详细信息,“可变作用域”如何工作以及何时有用。
0
variable_scope
和name_scope
什么name_scope
? 变量范围教程讨论了variable_scope
隐式打开name_scope
。我还注意到,在name_scope
中创建变量name_scope
自动将其名称扩展为作用域名称。那么区别是什么呢?