[英]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>
結果出乎意料,不同名字的變量x
和y
共享同一個 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.