Press "Enter" to skip to content

， 如有侵权请联系删除，仅限于学术交流，请勿商用。如有谬误，请联系指出。

```a = tf.constant(1)
print(a.name)  # prints "Const:0"
b = tf.Variable(1)
print(b.name)  # prints "Variable:0"```

```a = tf.constant(1, name="a")
print(a.name)  # prints "a:0"
b = tf.Variable(1, name="b")
print(b.name)  # prints "b:0"```

TensorFlow引入了两个不同的上下文管理器来改变张量和变量的名称。第一个是 `tf.name_scope`

```with tf.name_scope("scope"):
a = tf.constant(1, name="a")
print(a.name)  # prints "scope/a:0"
b = tf.Variable(1, name="b")
print(b.name)  # prints "scope/b:0"
c = tf.get_variable(name="c", shape=[])
print(c.name)  # prints "c:0"```

`tf.name_scope`

`tf.name_scope`

```with tf.variable_scope("scope"):
a = tf.constant(1, name="a")
print(a.name)  # prints "scope/a:0"
b = tf.Variable(1, name="b")
print(b.name)  # prints "scope/b:0"
c = tf.get_variable(name="c", shape=[])
print(c.name)  # prints "scope/c:0"
with tf.variable_scope("scope"):
a1 = tf.get_variable(name="a", shape=[])
a2 = tf.get_variable(name="a", shape=[])  # Disallowed```

```with tf.variable_scope("scope"):
a1 = tf.get_variable(name="a", shape=[])
with tf.variable_scope("scope", reuse=True):
a2 = tf.get_variable(name="a", shape=[])  # OK```

```with tf.variable_scope('my_scope'):
features1 = tf.layers.conv2d(image1, filters=32, kernel_size=3)
# Use the same convolution weights to process the second image:
with tf.variable_scope('my_scope', reuse=True):
features2 = tf.layers.conv2d(image2, filters=32, kernel_size=3)```

，这种操作告诉TensorFlow如果不存在具有相同名称的变量，就创建新变量，否则就复用：

```with tf.variable_scope("scope", reuse=tf.AUTO_REUSE):
features1 = tf.layers.conv2d(image1, filters=32, kernel_size=3)
with tf.variable_scope("scope", reuse=tf.AUTO_REUSE):
features2 = tf.layers.conv2d(image2, filters=32, kernel_size=3)```

```conv3x32 = tf.make_template("conv3x32", lambda x: tf.layers.conv2d(x, 32, 3))
features1 = conv3x32(image1)
features2 = conv3x32(image2)  # Will reuse the convolution weights.```