我一直在看TensorFlow上的教程
with tf.name_scope('read_inputs') as scope:
# something
这个例子
a = tf.constant(5)
和
with tf.name_scope('s1') as scope:
a = tf.constant(5)
似乎有相同的效果。那么,为什么我们要使用
name_scope
呢?
最佳答案
我没有看到重用常量的用例,但是这里是有关范围和变量共享的一些相关信息。
范围
name_scope
将范围添加为所有操作的前缀variable_scope
将范围添加为所有变量和操作的前缀实例化变量
tf.Variable()
构造函数在变量名前添加当前name_scope
和variable_scope
tf.get_variable()
构造函数忽略name_scope
,仅在当前variable_scope
的名称前面加上前缀例如:
with tf.variable_scope("variable_scope"):
with tf.name_scope("name_scope"):
var1 = tf.get_variable("var1", [1])
with tf.variable_scope("variable_scope"):
with tf.name_scope("name_scope"):
var2 = tf.Variable([1], name="var2")
产生
var1 = <tf.Variable 'variable_scope/var1:0' shape=(1,) dtype=float32_ref>
var2 = <tf.Variable 'variable_scope/name_scope/var2:0' shape=(1,) dtype=string_ref>
重用变量
tf.variable_scope
定义共享变量reuse_variables()
,如下所示with tf.variable_scope("scope"):
var1 = tf.get_variable("variable1",[1])
tf.get_variable_scope().reuse_variables()
var2=tf.get_variable("variable1",[1])
assert var1 == var2
tf.Variable()
总是创建一个新变量,当使用已经使用的名称构造变量时,它只会在其后附加_1
,_2
等-可能会引起冲突:( 关于tensorflow - 我们为什么使用tf.name_scope(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42708989/