tf.variable_scope()

tf.variable_scope(): 可以让变量有相同的命名,包括tf.get_variable得到的变量,还有tf.Variable变量

它返回的是一个用于定义创建variable(层)的op的上下文管理器。

可变范围允许创建新的variable并分享已创建的variable,同时提供检查,不会意外创建或共享。

如何创建新variable的简单示例:

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

共享variable的基本示例:

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

通过捕获范围并设置重用来共享variable:

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

为了防止意外共享variable,当在非重用范围内获取现有variable时,我们引发异常。

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

同样,当尝试获取在重用模式下不存在的variable时,我们引发异常。

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

请注意,重用标志是继承的:如果我们打开一个重用的范围,那么它的所有子范围也会变得重用。

ARGS:

name_or_scope:string或VariableScope:要打开的范围。
default_name:如果name_or_scope参数为None,则将使用默认名称,此名称将被唯一。 如果提供了name_or_scope,它将不会被使用,因此它不是必需的,可以是None。
值:传递给op函数的Tensor参数列表。
初始化器:此范围内的变量的默认初始化程序。
regularizer:此范围内的变量的默认正则符。
caching_device:此范围内的变量的默认缓存设备。
partitioner:此范围内变量的默认分区。
custom_getter:此范围内变量的默认定制getter。
重用:True或None 如果是,我们进入该范围以及所有子范围的重用模式; 如果没有,我们只是继承父范围重用。
dtype:在此范围中创建的变量类型(默认为传递范围中的类型,或从父范围继承)

返回:

可以捕获和重复使用的范围。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值