我想將神經網路的一層的權重更改為一組新的已知值。當前的值集是:
>>> import tensorflow as tf
...
>>> curr_layer.weights
<tf.Variable 'conv2d/kernel:0' shape=(4, 4, 1, 64) dtype=float32, numpy=
array([[[[ 0.02059445, -0.01320859, -0.00185177, ..., 0.02550568,
-0.02180868, 0.00089696]],
...
[[-0.03411875, -0.00027762, -0.00894349, ..., 0.04085622,
0.02792494, -0.02052956]]]], dtype=float32)>
為了這個例子,我創建了一個形狀相同的零陣列:
>>> silly = np.zeros([4,4,1,64])
但是,當我assign用來傳輸值時,與張量關聯的圖形節點的名稱也會發生變化:
>>> curr_layer.weights[0].assign(silly)
curr_layer.weights[0].assign(silly)
<tf.Variable 'UnreadVariable' shape=(4, 4, 1, 64) dtype=float32, numpy=
array([[[[0., 0., 0., ..., 0., 0., 0.]],
....
[[0., 0., 0., ..., 0., 0., 0.]]]], dtype=float32)>
現在哪里'conv2d/kernel:0'變成了'Unread Variable'。我該如何防止這種情況發生?如何僅更改與張量相關的值?
uj5u.com熱心網友回復:
對于 tf.Variable 實體, .assign 方法默認有一個read_value引數True。如果x是一個任意的 tf.Variable,那么對于一個 numpy 陣列silly(與 的維度相同x),您可以執行以下操作:
x.assign(silly, read_value=False)
這不會回傳任何內容,但會更改 tf.Variable 實體x。
對于我改編自原始帖子的玩具示例,執行以下操作:
silly = np.zeros([2,2])
x = tf.Variable([[1,0],[0,1]], dtype=tf.float32, name='test')
x.assign(silly, read_value=False)
x
導致:
<tf.Variable 'test:0' shape=(2, 2) dtype=float32, numpy=
array([[0., 0.],
[0., 0.]], dtype=float32)>
顯然與原始帖子中涉及的張量不同,但預期的行為是預期的。
uj5u.com熱心網友回復:
名稱實際上并沒有改變:
a = tf.Variable(np.zeros((3, 4)), name='test')
a.name
列印test:0。然后
a.assign(np.zeros((3, 4)))
a.name
仍然列印test:0。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442729.html
