代码之家  ›  专栏  ›  技术社区  ›  user1245262

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

  •  0
  • user1245262  · 技术社区  · 3 年前

    我想把一层神经网络的权值改成一组新的已知值。当前的一组值是:

    >>> 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 ’我如何防止这种情况发生?我该如何改变 只有 与张量有关的值?

    2 回复  |  直到 3 年前
        1
  •  0
  •   AndrewJaeyoung    3 年前

    为了一个tf。变量实例。assign方法有一个 read_value 论点那是 True 默认情况下。如果 x 是一个武断的tf。变量,然后是numpy数组 silly (尺寸与 十、 ),你可以做:

    x.assign(silly, read_value=False)
    

    这不会返回任何内容,但会改变tf。变量实例, 十、 在正确的位置

    对于一个我从原始帖子改编的玩具示例,请执行以下操作:

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

    显然,与原始帖子中涉及的张量不同,但预期行为与预期一致。

        2
  •  0
  •   xdurch0    3 年前

    这个名字实际上没有改变:

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

    印刷品 test:0 .然后呢

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

    还有指纹 测试:0 .