tf.variable_scope

tf.variable_scope

这个是创建变量的域的函数。

主要用来声明变量的作用域,实现共享变量。

解析链接: https://blog.csdn.net/weixin_39875161/article/details/92435753

https://www.cnblogs.com/MY0213/p/9208503.html

示例1-如何创建一个新变量:

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

示例2-共享变量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

示例3-使用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

示例4-通过捕获范围并设置重用来共享变量:

with tf.variable_scope("foo") as scope:
    v = tf.get_variable("v", [1])
    scope.reuse_variables()
    v1 = tf.get_variable("v", [1])
assert v1 == v

为了防止意外共享变量,我们在获取非重用范围中的现有变量时引发异常。

with tf.variable_scope("foo"):
    v = tf.get_variable("v", [1])
    v1 = tf.get_variable("v", [1])
    #  Raises ValueError("... v already exists ...")

同样,我们在尝试获取重用模式中不存在的变量时引发异常。

with tf.variable_scope("foo", reuse=True):
    v = tf.get_variable("v", [1])
    #  Raises ValueError("... v does not exists ...")
文章目录