这些函数之间有什么区别?
<小时/>
tf.variable_op_scope(values, name, default_name, initializer=None)
Returns a context manager for defining an op that creates variables. This context manager validates that the given values are from the same graph, ensures that that graph is the default graph, and pushes a name scope and a variable scope.
<小时/>
tf.op_scope(values, name, default_name=None)
Returns a context manager for use when defining a Python op. This context manager validates that the given values are from the same graph, ensures that that graph is the default graph, and pushes a name scope.
<小时/>
tf.name_scope(name)
Wrapper for
Graph.name_scope()
using the default graph. SeeGraph.name_scope()
for more details.
tf.variable_scope(name_or_scope, reuse=None, initializer=None)
Returns a context for variable scope. Variable scope allows to create new variables and to share already created ones while providing checks to not create or share by accident. For details, see the Variable Scope How To, here we present only a few basic examples.
最佳答案
让我们首先简单介绍一下变量共享。它是 TensorFlow 中的一种机制,允许共享在代码的不同部分访问的变量,而无需传递对变量的引用。
方法tf.get_variable
可以与变量名称作为参数一起使用,以创建具有该名称的新变量或检索之前创建的变量。这与使用 tf.Variable
不同。构造函数,每次调用时都会创建一个新变量(如果已经存在具有此类名称的变量,则可能会在变量名称中添加后缀)。
正是为了变量共享机制,引入了单独类型的作用域(变量作用域)。
因此,我们最终有两种不同类型的范围:
- 名称范围,使用
tf.name_scope
创建 - 变量范围,使用
tf.variable_scope
创建
两个作用域对所有操作以及使用 tf.Variable 创建的变量具有相同的效果,即作用域将作为前缀添加到操作或变量名称中。
但是,tf.get_variable
会忽略名称范围。我们可以在下面的示例中看到这一点:
with tf.name_scope("my_scope"):
v1 = tf.get_variable("var1", [1], dtype=tf.float32)
v2 = tf.Variable(1, name="var2", dtype=tf.float32)
a = tf.add(v1, v2)
print(v1.name) # var1:0
print(v2.name) # my_scope/var2:0
print(a.name) # my_scope/Add:0
将使用 tf.get_variable
访问的变量放置在作用域中的唯一方法是使用变量作用域,如下例所示:
with tf.variable_scope("my_scope"):
v1 = tf.get_variable("var1", [1], dtype=tf.float32)
v2 = tf.Variable(1, name="var2", dtype=tf.float32)
a = tf.add(v1, v2)
print(v1.name) # my_scope/var1:0
print(v2.name) # my_scope/var2:0
print(a.name) # my_scope/Add:0
这使我们能够轻松地在程序的不同部分之间共享变量,甚至在不同的名称范围内:
with tf.name_scope("foo"):
with tf.variable_scope("var_scope"):
v = tf.get_variable("var", [1])
with tf.name_scope("bar"):
with tf.variable_scope("var_scope", reuse=True):
v1 = tf.get_variable("var", [1])
assert v1 == v
print(v.name) # var_scope/var:0
print(v1.name) # var_scope/var:0
<小时/>
更新
从版本 r0.11 开始,op_scope
和 variable_op_scope
均为 deprecated并替换为 name_scope
和 variable_scope
。
关于tensorflow - tensorflow 中的名称范围和变量范围有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35919020/