3. tf.Variable和tf.get_variable区别和联系

3.1 联系

两个函数都可以用于创建变量
tf.Variable: initial_value必须指定, name可选

tf.Variable(
    initial_value=None, trainable=None, validate_shape=True, caching_device=None,
    name=None, variable_def=None, dtype=None, import_scope=None, constraint=None,
    synchronization=tf.VariableSynchronization.AUTO,
    aggregation=tf.compat.v1.VariableAggregation.NONE, shape=None
)

tf.get_variable: name, shape, initializer必须指定

tf.compat.v1.get_variable(
    name, shape=None, dtype=None, initializer=None, regularizer=None,
    trainable=None, collections=None, caching_device=None, partitioner=None,
    validate_shape=True, use_resource=None, custom_getter=None, constraint=None,
    synchronization=tf.VariableSynchronization.AUTO,
    aggregation=tf.compat.v1.VariableAggregation.NONE
)

使用tf.Variable和tf.get_variable创建初始化为1, shape为[2,3]的变量。

a = tf.Variable(tf.constant(1, shape=[2, 3]))
b = tf.get_variable("b", shape=[2, 3], initializer=tf.constant_initializer(1))

3.2 区别

tf.get_variable可以通过变量名,进行创建或获取变量name不可选。而tf.Variable只能进行创建变量,name可选。

如果需要通过tf.get_variable获取已经创建的变量,需要通过tf.variable_scope函数生成上下文管理器。

with tf.variable_scope("liang"):
    v = tf.get_variable("sun", shape=(), initializer=tf.constant_initializer(1.0))

'''
with tf.variable_scope("liang"):
    v = tf.get_variable("sun") # Error liang/sun:0 exists.
'''

with tf.variable_scope("liang", reuse=True):
    v1 = tf.get_variable("sun")
    print(v == v1) # True
    
'''
with tf.variable_scope("b", reuse=True):  
    v2 = tf.get_variable("s") # Error, b/s doesn't exist.
'''

注意

  • 当创建变量时,不需要加reuse=True, 如果已经创建,则会报错。
  • 当获取变量时,需要加reuse=True,如果没有创建,则会报错。

3.3 tf.variable_scope

tf.variable_scope可以创建命名空间,命名空间会加到变量名前。

### tf.variable_scope, create namespace.
vs = tf.get_variable("v", [1])
print(vs.name)  # v:0

with tf.variable_scope("foo"):
    vs2 = tf.get_variable("v", [1])
    print(vs2.name) # foo/v:0

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

with tf.variable_scope("", reuse=True):
    vs4 = tf.get_variable("foo/v")
    print(vs4 == vs2)  # True

    vs5 = tf.get_variable("foo/bar/v")
    print(vs5 == vs3)  # True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值