经常看到这个函数,所以特地查了一下源码单独记一下。
参考资料:
- $PYTHONHOME/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py
- https://github.com/tensorflow/docs/blob/r1.3/site/en/api_docs/api_docs/python/tf/variable_scope.md
- https://blog.csdn.net/hyxing520/article/details/80889496
def variable_scope(name_or_scope,
default_name=None,
values=None,
initializer=None,
regularizer=None,
caching_device=None,
partitioner=None,
custom_getter=None,
reuse=None,
dtype=None,
use_resource=None)
作用:这个函数返回上下文管理器,用于定义创建变量(或层)的操作。
此上下文管理器验证(可选)values
是否来自同一个图,确保该图是默认图,并推送名称作用域和变量作用域。
如果name_or_scope
不是None,则按原样使用。如果scope
为None,则使用default_name
。在这种情况下,如果先前在同一作用域内使用了相同的名称,那么它将被追加_N
以保证唯一性。
变量作用域允许创建新变量并共享已创建的变量,同时提供检查以避免意外创建或共享。有关详细信息,请参阅@ {$ variables $ Variable Scope How To}
创建新变量的简单示例:
with tf.variable_scope("foo"):
with tf.variable_scope("bar"):
v = tf.get_variable("v", [1])
assert v.name == "foo/bar/v:0"
共享变量的简单示例
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
通过捕获作用域及设置reuse来共享一个变量:
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])
# 抛出的异常为 ValueError("... v already exists ...").
同样的,我们在可复用的情况下尝试获取一个不存在的变量的时候会引发一个异常:
with tf.variable_scope("foo", reuse=True):
v = tf.get_variable("v", [1])
# 抛出的异常为 ValueError("... v does not exists ...").
请注意,
reuse
标志具有继承能力:如果我们打开一个重用域,那么它的所有子域也会重用。
关于名称作用域的说明:设置reuse
不会影响其他操作(如mult)的命名。相关讨论参见github#6189
注意,直到并包括版本1.0,允许(尽管明确不鼓励)将False传递给reuse参数,从而产生与None略有不同的未记录行为。从1.1.0开始传递None和False,因为重用具有完全相同的效果。
Args:
参数名 解释 name_or_scope string
orVariableScope
: 待打开的作用域.default_name 如果 name_or_scope
参数为None
,则使用默认名称,此名称将是不加参数的。如果提供了name_or_scope
,则不会使用它,因此它不是必需的,可以是None
。values 传递给op函数的 Tensor
参数列表。initializer 此作用域内变量的默认初始值。 regularizer 用于此作用域内变量的默认正则化器。 caching_device 用于此作用域内变量的默认缓存设备。 partitioner 用于此作用域内变量的默认分区工具。 custom_getter 用于此作用域内变量的默认自定义getter reuse True
或None
; 如果为True
,我们将进入此作用域以及所有子作用域的重用模式;如果None
,我们只继承父作用域重用。dtype 在此作用域中创建的变量类型(默认为传递进来的作用域中的类型,或从父作用域继承而得)。 use_resource 如果为 False
,则所有变量都将是常规变量。如果为True
,则将使用具有明确定义的语义的经验性ResourceVariables。默认为False
(更新的版本将更改为True
)。Returns:
可以捕获和重用的作用域。Raises:
ValueError: when trying to reuse within a create scope, or create within a reuse scope.
TypeError: when the types of some arguments are not appropriate.