tensorflow学习笔记--tf.get_variable、tf.Variable

    tf.get_variable创建变量的时候必须提供name属性。如果再次运行该代码,报错:

ValueError: Variable gv already exists, disallowed. Did you mean to set reuse=True in VarScope?

    可见,tf.get_variable用来实现变量共享。tf.get_variable创建的变量存在命名冲突的问题。而tf.Variable不存在命名冲突的问题,如果tf.Variable创建的变量name相同,就会创建一个新的变量,在name属性(或者name_scope)后加上后缀_1等。例如:

import tensorflow as tf
with tf.variable_scope('v_scope') as scope1:
    Weights1 = tf.get_variable('Weights', shape=[2,3])
    bias1 = tf.Variable([0.52], name='bias')

# 下面来共享上面已经定义好的变量
# note: 在下面的 scope 中的get_variable()变量必须已经定义过了,才能设置 reuse=True,否则会报错
with tf.variable_scope('v_scope', reuse=True) as scope2:
    Weights2 = tf.get_variable('Weights')
    bias2 = tf.Variable([0.52], name='bias')
    bias3= tf.Variable([0.52], name='bias')

print(Weights1.name)
print(Weights2.name)
print(bias1.name)
print(bias2.name)
print(bias3.name)

输出:

v_scope/Weights:0
v_scope/Weights:0
v_scope/bias:0
v_scope_1/bias:0
v_scope_1/bias_1:0

    tf.variable_scope包含tf.name_scope的作用,而且可以用来实现变量共享.

with tf.variable_scope('vs1', reuse=True) as vs:

    tf.variable_scope中设置了reuse=True,则其中tf.get_variable()的变量必须是已经在vs1中通过tf.get_variable()方法声明的变量,否则报错:

ValueError: Variable vs1/var3 does not exist, or was not created with tf.get_variable().

而tf.Variable()方法不受reuse=True的影响。

tf.name_scope()对tf.get_variable()方法没有作用,起不到命名空间的作用。例如:

import tensorflow as tf
with tf.name_scope('nc1') as vs:
    a = tf.get_variable('var1', shape=[2,4], dtype=tf.float32)
print(a.name)

输出:var1:0

具体实验参考博客  TensorFlow入门(七) 充分理解 name / variable_scope

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值