tf.variable_scope()用法详解

https://www.tensorflow.org/api_docs/python/tf/variable_scope?hl=en
tf.variable_scope()用法详解
本质是一个上下文管理器。

创建新变量

import tensorflow as tf
with tf.variable_scope("foo"):
    with tf.variable_scope("bar"):
        v = tf.get_variable("v", [1])
        assert v.name == "foo/bar/v:0"

通过tf.AUTO_REUSE分享变量

def foo():
  with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
    v = tf.get_variable("v", [1])
  return v

v1 = foo()  # Creates v.
v2 = foo()  # Gets the same, existing v.
assert v1 == v2

通过reuse=True分享变量

with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1])
with tf.variable_scope("foo", reuse=True):
    v1 = tf.get_variable("v", [1])
assert v1 == v