TensorFlow学习笔记(1):variable与get_variable, name_scope()和variable_scope()

Variable

tensorflow中有两个关于variable的op,tf.Variable()与tf.get_variable()下面介绍这两个的区别
使用tf.Variable时,如果检测到命名冲突,系统会自己处理。使用tf.get_variable()时,系统不会处理冲突,而会报错

import tensorflow as tf
w_1 = tf.Variable(3,name="w_1")
w_2 = tf.Variable(1,name="w_1")
print w_1.name
print w_2.name
#输出
#w_1:0
#w_1_1:0

import tensorflow as tf

w_1 = tf.get_variable(name="w_1",initializer=1)
w_2 = tf.get_variable(name="w_1",initializer=2)
#错误信息
#ValueError: Variable w_1 already exists, disallowed. Did
#you mean to set reuse=True in VarScope?

基于这两个函数的特性,当我们需要共享变量的时候,需要使用tf.get_variable()。在其他情况下,这两个的用法是一样的

  • tf.get_variable() 以及 tf.Variable() 是 TensorFlow 中创建变量的两种主要方式;
  • 如果在 tf.name_scope() 环境下分别使用 tf.get_variable() 和 tf.Variable(),两者的主要区别在于
    • tf.get_variable() 创建的变量名不受 name_scope 的影响;
    • tf.get_variable() 创建的变量,name 属性值不可以相同;tf.Variable() 创建变量时,name 属性值允许重复(底层实现时,会自动引入别名机制

import tensorflow as tf

with tf.variable_scope("scope1"):
    w1 = tf.get_variable("w1", shape=[])
    w2 = tf.Variable(0.0, name="w2")
with tf.variable_scope("scope1", reuse=True):
    w1_p = tf.get_variable("w1", shape=[])
    w2_p = tf.Variable(1.0, name="w2")

assert w1 == w1_p
assert w2 != w2_p
get_variable() 函数的行为依赖于 reuse 的状态:

  • case1:reuse 设置为 False,创建并返回新变量:

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

  • case2: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')
    assert v1 == v

看到这,就可以明白官网上说的参数复用的真面目了。由于 tf.Variable() 每次都在创建新对象,所有 reuse=True 和它并没有什么关系。对于 get_variable(),来说,如果已经创建的变量对象,就把那个对象返回,如果没有创建变量对象的话,就创建一个新的。


variable_scope()

一个双层嵌套名称空间:

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.name_scope('foo'):
    with tf.variable_scope('bar'):
        v = tf.get_variable('v', [1])
assert v.name == 'bar/v:0'


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值