tf.variable_scope官方文档

Class variable_scope

定义于tensorflow/python/ops/variable_scope.py
variable_scope是一个上下文管理器,在创建变量(variables)时使用。

这个上下文管理器有三个功能:

  1. 表明values来自于同一个graph
  2. 确保graph是默认graph
  3. 推出一个名称空间和变量空间

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机制,使我们可以重用定义过的变量。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值