tf.Variable()和tf.get_variable()的区别

tf.Variable()和tf.get_variable()在创建变量的过程基本上是一样的。

tf.Variable()和tf.get_variable()最大的区别在于指定变量名称的参数。对于tf.Variable(),变量名称name是一个可选的参数。但是对于tf.get_variable(),变量名称是一个必填的参数。

 

对于tf.Variable()如果name冲突,系统会自动处理

import tensorflow as tf

a=tf.constant([1,2])
b=tf.constant([3,4],name='b')
c=tf.constant([3,4],name='b')
print(a)
print(b)
print(c)

'''
Tensor("Const:0", shape=(2,), dtype=int32)
Tensor("b:0", shape=(2,), dtype=int32)
Tensor("b_1:0", shape=(2,), dtype=int32)
'''

但是对于tf.get_variable()系统会报错。

import tensorflow as tf

v1=tf.get_variable(name='v',shape=[1])
v2=tf.get_variable(name='v',shape=[1])
print(v)
'''
 Variable v already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:
'''

 tf.get_variable() 结合  tf.variable_scope()的参数reuse(reuse默认为False)可以实现对同一变量的创建或获取。

当tf.variable_scope()使用resuse=True生成上下文管理器时,这个上下文管理器内所有的tf.get_variable()会直接获取已经创建的变量,如果变量不存在会报错。 相反,当tf.variable_scope()使用reuse=None或reuse=False创建上下文管理器时,tf.get_variable()会创建新的变量,如果同名的变量存在则会报错。

import tensorflow as tf

with tf.variable_scope('foo'):
    v1=tf.get_variable('v',[1])
    print(v1)
#命名空间foo已经存在v的变量,所以会报错
# with tf.variable_scope('foo'):
#     v1 = tf.get_variable('v', [1])

with tf.variable_scope('foo',reuse=True):
    v1 = tf.get_variable('v', [1])
#命名空间foo没有创建v2,所以会报错
with tf.variable_scope('foo',reuse=True):
    v1 = tf.get_variable('v2', [1])

所以可以根据传进来的reuse来判断是创建新变量还是使用已经创建好的变量。

但是tf.Variable()结合tf.variable_scope没有这样的效果,因为当变量的name冲突时,他会改变名称空间来解决冲突。

import tensorflow as tf

with tf.variable_scope('foo'):
    v1=tf.Variable([1],'v')
    print(v1)
with tf.variable_scope('foo'):
    v1=tf.Variable([1],'v')
    print(v1)
'''
<tf.Variable 'foo/Variable:0' shape=(1,) dtype=int32_ref>
<tf.Variable 'foo_1/Variable:0' shape=(1,) dtype=int32_ref>
'''

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值