#######################variable_scope###########################with tf.variable_scope("foo",reuse = True):
v = tf.get_variable("v", [1])
v1 = tf.get_variable("v", [1])
assert v == v1
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
v2 = tf.get_variable("v", [1])
assert v == v2
#输出ValueError
with tf.variable_scope("foo") as foo_scope:
assert foo_scope.name == "foo"with tf.variable_scope("bar"):
with tf.variable_scope("cat") as other_scope:
assert other_scope.name == "bar/cat"#如果在开启的一个变量作用域之前使用预先定义的作用域,#则会跳过当前变量的作用域,保持预先存在的作用域不变with tf.variable_scope(foo_scope) as foo_scope2:
assert foo_scope2.name == "foo"
with tf.variable_scope("foo"):
x = 1.0 + tf.get_variable("v123",[1])
with tf.variable_scope("foo"):
#reuse = True是为了解决下面y的名称冲突,若y的名称与x相同,则产生新的foo#并在原来基础上foo n命名为foo n+1,但后续会报错。#若名字不同则在foo n+1 基础上产生foo n+2/addy = 1.0 +tf.get_variable("v122",[1])
print(x.op.name,y.op.name)
foo_7/add foo_8/add
#name_scope会影响op_name,通过Variable()创建的变量#不会影响get_variable()创建的变量
with tf.variable_scope("foo123"):
with tf.name_scope("bar22"):
v = tf.get_variable("v22", [1])
b = tf.Variable(tf.zeros([1]), name = 'b')
x = 1.0+v
assert v.name == "foo123/v22:0"
assert b.name == "foo123/bar22/b:0"
assert x.op.name == "foo123/bar22/add"