variable_scope和 name_scope有什么不同?可变作用域教程谈到 variable_scope隐式地打开 name_scope。我还注意到,在 name_scope中创建一个变量也会自动使用范围名来扩展它的名称。那有什么区别呢?
variable_scope
name_scope
当您使用 tf.get_variable而不是 tf.Variable创建变量时,Tensorflow 将开始检查使用相同方法创建的变量的名称,以查看它们是否发生冲突。如果他们这样做,将引发一个异常。如果您使用 tf.get_variable创建了一个变量,并尝试使用 tf.name_scope上下文管理器更改变量名的前缀,这不会阻止 Tensorflow 引发异常。在这种情况下,只有 tf.variable_scope上下文管理器才能有效地更改 var 的名称。或者,如果您想重用变量,那么在第二次创建 var 之前,应该调用 scope.use _ variable ()。
tf.get_variable
tf.Variable
tf.name_scope
tf.variable_scope
总而言之,tf.name_scope只需向在该作用域中创建的所有张量添加一个前缀(用 tf.get_variable创建的变量除外) ,而 tf.variable_scope则向用 tf.get_variable创建的变量添加一个前缀。
在我试图通过创建一个简单的示例来可视化所有内容之前,我在理解 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矩形外面) :
b
scope_name
这给了你答案 :
现在您可以看到,tf.variable_scope()为所有变量(不管您如何创建它们)、操作系统和常量的名称添加了一个前缀。另一方面,tf.name_scope()忽略使用 tf.get_variable()创建的变量,因为它假设您知道要在哪个作用域中使用哪个变量。
tf.variable_scope()
tf.name_scope()
tf.get_variable()
关于 共享变量的一个很好的文档告诉您
管理传递给 tf.get_variable()的名称的命名空间。
同样的文档提供了关于变量作用域如何工作以及何时有用的更多细节。
tf.variable_scope是 tf.name_scope的演变,用于处理 Variable重用。正如您所注意到的,它比 tf.name_scope做的更多,所以没有真正的理由使用 tf.name_scope: 毫不奇怪,TF 开发人员建议只使用 tf.variable_scope。
Variable
我对于仍然存在 tf.name_scope的理解是,这两者的行为存在细微的不兼容性,这使得作为 tf.name_scope替代品的 tf.variable_scope无效。