with tf.compat.v1.variable_scope("foo"): with tf.compat.v1.variable_scope("bar"): v = tf.compat.v1.get_variable("v", [1]) assert v.name == "foo/bar/v:0"
安全进入一个已经创建好的variable scope:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
with tf.compat.v1.variable_scope("foo") as vs: pass
# 重新进入变量作用域 with tf.compat.v1.variable_scope(vs, auxiliary_name_scope=False) as vs1: # 重建原始的名称作用域 with tf.name_scope(vs1.original_name_scope): v = tf.compat.v1.get_variable("v", [1]) assert v.name == "foo/v:0" c = tf.constant([1], name="c") assert c.name == "foo/c:0" >>> print(v) <tf.Variable 'foo/v:0' shape=(1,) dtype=float32_ref> >>> print(type(v)) <class'tensorflow.python.ops.variables.RefVariable'> >>> print(c) Tensor("foo/c:0", shape=(1,), dtype=int32) >>> print(type(c)) <class'tensorflow.python.framework.ops.Tensor'>
通过 AUTO_REUSE共享变量:
1 2 3 4 5 6 7 8 9 10 11
deffoo(): with tf.compat.v1.variable_scope("foo", reuse=tf.compat.v1.AUTO_REUSE): v = tf.compat.v1.get_variable("v", [1]) return v
with tf.compat.v1.variable_scope("foo"): v = tf.compat.v1.get_variable("v", [1]) with tf.compat.v1.variable_scope("foo", reuse=True): v1 = tf.compat.v1.get_variable("v", [1]) assert v1 == v assertid(v1) == id(v)
在当前scope内设置reuse:
1 2 3 4 5 6
# 注意:必须要把scope.reuse_variables()放在已创建的变量之后以及重用之前。 with tf.compat.v1.variable_scope("foo") as scope: v = tf.compat.v1.get_variable("v", [1]) scope.reuse_variables() v1 = tf.compat.v1.get_variable("v", [1]) assert v1 == v