简体   繁体   English

如何在 tensorflow 2.0 中重用变量?

[英]How to reuse variables in tensorflow 2.0?

When using tensorflow 2.0, I find something weird about tf.Variable?在使用 tensorflow 2.0 时,我发现 tf.Variable 有点奇怪? There are two cases bellow.下面有两种情况。

The first one第一个

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

The output is output 是

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

which means variables with the same name don't share the same memory.这意味着具有相同名称的变量不共享相同的 memory。

The second one第二个

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)

The output is 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>

The result is unexpected, variables x and y with different names share the same memory, but id(x) is not equal to id(y) .结果出乎意料,不同名字的变量xy共享同一个 memory,但是id(x)不等于id(y)

Therefore, the name of variable can't distinguish whether variables are identical(share the same memory).因此,变量的名称无法区分变量是否相同(共享相同的内存)。 And how can I reuse variables in tensorflow 2.0, like with tf.variable_scope("scope", reuse=True) tf.get_variable(...) in tensorflow 1.0?以及如何重用 tensorflow 2.0 中的变量,例如 tensorflow 1.0 中with tf.variable_scope("scope", reuse=True) tf.get_variable(...)

Quoted from your question:引用您的问题:

The result is unexpected, variables x and y with different names share the same memory, but id(x) is not equal to id(y).结果出乎意料,不同名字的变量x和y共享同一个memory,但是id(x)不等于id(y)。

No, this is incorrect.不,这是不正确的。 From the docs of tf.Variable.assign , where read_value is default to True :来自tf.Variable.assign的文档,其中read_value默认为True

read_value: if True, will return something which evaluates to the new value of the variable; read_value:如果为真,将返回计算结果为变量新值的内容 if False will return the assign op.如果 False 将返回分配操作。

Here "something" should be a new operation, which isn't x , but is evaluated to the value of x .这里的“某事”应该是一个新的操作,它不是x ,而是被评估为x的值。

To reuse x , just access x :要重用x ,只需访问x

y = x
print(y is x) # True

Finally, regarding:最后,关于:

which means variables with the same name don't share the same memory.这意味着具有相同名称的变量不共享相同的 memory。

Therefore, the name of variable can't distinguish whether [...]因此,变量的名称无法区分是否 [...]

You have to create different(thus distinguishable) name s yourself, regarding your first example.关于您的第一个示例,您必须自己创建不同的(因此可区分的) name You might want to take a look at the comments of this accepted answer https://stackoverflow.com/a/73024334/5290519您可能想看看这个已接受答案https://stackoverflow.com/a/73024334/5290519的评论

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

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