python中tensor与variable_TensorF中变量与get_变量的区别

我可以发现两者之间的两个主要区别:首先,tf.Variable将始终创建一个新变量,而tf.get_variable从图中获取一个具有指定参数的现有的变量,如果它不存在,则创建一个新变量。

tf.Variable要求指定初始值。

必须澄清的是,函数tf.get_variable在名称前面加上当前变量作用域以执行重用检查。例如: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):

c = tf.get_variable("v", [1]) #c.name == "one/v:0"

with tf.variable_scope("two"):

d = tf.get_variable("v", [1]) #d.name == "two/v:0"

e = tf.Variable(1, name = "v", expected_shape = [1]) #e.name == "two/v_1:0"

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

assert(a is d) #AssertionError: they are different objects

assert(d is e) #AssertionError: they are different objects

最后一个断言错误很有意思:在同一范围内同名的两个变量应该是同一个变量。但是如果你测试变量名d和e,你会发现Tensorflow改变了变量名e:d.name #d.name == "two/v:0"

e.name #e.name == "two/v_1:0"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值