tf.Variable()、tf.get_variable()

- tf.Variable()

W = tf.Variable(<initial-value>, name=<optional-name>)

用于生成一个初始值为initial-value的变量。必须指定初始化值

-tf.get_variable()

W = tf.get_variable(name, shape=None, dtype=tf.float32, initializer=None,
       regularizer=None, trainable=True, collections=None)

获取已存在的变量(要求不仅名字,而且初始化方法等各个参数都一样),如果不存在,就新建一个。
initializer可以用各种初始化方法,不用明确指定值。

- 区别

[1]. tf.get_variable()可以实现共享变量,而tf.Variable()只能新建变量。
[2]. get_variable新建变量如果遇见重复的name则会因为重复而报错(在没有启动reuse=True的情况下)。
[3]. variable新建的变量如果遇见重复的name则会自动修改前缀,以避免重复出现。


- 代码演示

  • 实现共享
with tf.variable_scope("one"):
    a = tf.get_variable("v", [1]) #a.name == "one/v:0"
with tf.variable_scope("one"):
    b = tf.get_variable("v", [1]) #创建两个名字一样的变量会报错 ValueError: Variable one/v already exists 
with tf.variable_scope("one", reuse = True): #注意reuse的作用。
    c = tf.get_variable("v", [1]) #c.name == "one/v:0" 成功共享,因为设置了reuse

assert a==c #Assertion is true, they refer to the same object.

# 注意,如果开启了reuse = True
# 那么就必须复用变量,如果指定的变量名不存在,则会报错
with tf.variable_scope("one", reuse = True): #注意reuse的作用。
    d = tf.get_variable("p", [1]) #c.name == "one/v:0" 报错,因为之前没有name为p的变量
  • Variable()
import tensorflow as tf

with tf.name_scope('nameScope'):
    n1 = tf.Variable(1,name= "1")

with tf.name_scope("nameScope"):
    n2 = tf.Variable(3,name="1")

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(n1)# <tf.Variable 'nameScope/1:0' shape=() dtype=int32_ref>
    print(n2)# <tf.Variable 'nameScope_1/1:0' shape=() dtype=int32_ref>
    # tf.Variable会自动检修改前缀以避免重复出现

参考

https://blog.csdn.net/timothytt/article/details/79789274
https://blog.csdn.net/NNNNNNNNNNNNY/article/details/70177509

记录时间

2018/9/13 13:15 第一次
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值