如何在不更改张量的任何其他属性的情况下更改存储在 TensorFlow 变量中的 numpy 数组的值?

How can I change the values of a numpy array stored in a TensorFlow Variable Without Changing ANY other properties of the Tensor?

我想将神经网络一层的权重更改为一组新的已知值。当前的一组值是:

>>> 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传递值时,与Tensor关联的图节点的名称也发生了变化:

>>> 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'。我如何防止这种情况发生?如何更改 与张​​量关联的值?

对于 tf.Variable 实例,.assign 方法有一个 read_value 参数,默认情况下为 True。如果 x 是任意的 tf.Variable,那么对于一个 numpy 数组 silly(与 x 具有相同的维度),你可以这样做:

x.assign(silly, read_value=False)

这不会 return 任何东西,但它会改变 tf.Variable 实例,x 到位。

对于我改编自原始 post 的玩具示例,执行以下操作:

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)>

显然与原始 post 中涉及的张量完全不同,但预期行为符合预期。

名字实际上并没有改变:

a = tf.Variable(np.zeros((3, 4)), name='test')
a.name

打印 test:0。然后

a.assign(np.zeros((3, 4)))
a.name

仍然打印 test:0.