Class variable_scope
定义于tensorflow/python/ops/variable_scope.py。
variable_scope是一个上下文管理器,在创建变量(variables)时使用。
这个上下文管理器有三个功能:
- 表明values来自于同一个graph
- 确保graph是默认graph
- 推出一个名称空间和变量空间
If name_or_scope
is not None, it is used as is. If scope
is None, the default_name
is used. 不懂
如果在同一个变量范围(scope)中,有相同的变量名,则tensorflow会自动在变量名上加后缀_N
。
在你不小心创建或共享变量的时候,变量范围(variable scope)可以提供保护性检查。下面是一个创建新变量的例子:
with tf.variable_scope("foo"):
with tf.varible_scope("bar"):
v = tf.get_variable("v", [1])
assert v.name == "foo/bar/v:0"
下面是一个使用AUTO_REUSE
共享变量的例子:
def foo():
with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
v = tf.get_variable("v", [1])
return v
v1 = foo() # Create v.
v2 = foo() # Gets the same, exiting 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
另一种共享变量的例子,直接对scope进行操作:
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
为了避免共享变量时发生意外,我们可以设置异常机制。当在none-reusing scope中创建同名变量时,抛出异常。例子:
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
v1 = tf.get_variable("v", [1])
# Raises ValueError("... v already exists ...")
相应的,在reuse mode中,如果我们创建的变量不存在,也抛出异常。例子:
with tf.variable_scope("foo", reuse=True):
v = tf.get_variable("v", [1])
# Raises ValueError("... v does not exists ...")
PS: reuse
状态是自动继承的:如果我们创建一个reusing scope,那么它所有的sub-scope都是resue的。
总结
variable_scope是一个名称空间,名称空间在编译时,作为变量名的前缀可以自动保证变量名的唯一性。同时variable_scope提供了reuse机制,使我们可以重用定义过的变量。