繁体   English   中英

如何在 tensorflow 2.0 中重用变量?

[英]How to reuse variables in tensorflow 2.0?

在使用 tensorflow 2.0 时,我发现 tf.Variable 有点奇怪? 下面有两种情况。

第一个

x1 = tf.Variable(12., name='x')
x2 = tf.Variable(12., name='x')
print(x1 is x2)
x1.assign(1.)
print(x1)
print(x2)

output 是

False
<tf.Variable 'x:0' shape=() dtype=float32, numpy=1.0>
<tf.Variable 'x:0' shape=() dtype=float32, numpy=12.0>

这意味着具有相同名称的变量不共享相同的 memory。

第二个

x = tf.Variable(12., name='x')
print(x)
y = x.assign(5.)
print(y)
print(x is y)

x.assign(3.)
print(x)
print(y)

output 是

<tf.Variable 'x:0' shape=() dtype=float32, numpy=12.0>
<tf.Variable 'UnreadVariable' shape=() dtype=float32, numpy=5.0>
False
<tf.Variable 'x:0' shape=() dtype=float32, numpy=3.0>
<tf.Variable 'UnreadVariable' shape=() dtype=float32, numpy=3.0>

结果出乎意料,不同名字的变量xy共享同一个 memory,但是id(x)不等于id(y)

因此,变量的名称无法区分变量是否相同(共享相同的内存)。 以及如何重用 tensorflow 2.0 中的变量,例如 tensorflow 1.0 中with tf.variable_scope("scope", reuse=True) tf.get_variable(...)

引用您的问题:

结果出乎意料,不同名字的变量x和y共享同一个memory,但是id(x)不等于id(y)。

不,这是不正确的。 来自tf.Variable.assign的文档,其中read_value默认为True

read_value:如果为真,将返回计算结果为变量新值的内容 如果 False 将返回分配操作。

这里的“某事”应该是一个新的操作,它不是x ,而是被评估为x的值。

要重用x ,只需访问x

y = x
print(y is x) # True

最后,关于:

这意味着具有相同名称的变量不共享相同的 memory。

因此,变量的名称无法区分是否 [...]

关于您的第一个示例,您必须自己创建不同的(因此可区分的) name 您可能想看看这个已接受答案https://stackoverflow.com/a/73024334/5290519的评论

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM