代码之家  ›  专栏  ›  技术社区  ›  Falco Winkler

在列表中指定的索引处给张量赋值零

  •  2
  • Falco Winkler  · 技术社区  · 7 年前

    例如,我必须使用张量

    A = tf.Tensor(
           [[1.0986123 0.6931472 0.        0.6931472 0.       ]
            [0.        0.        0.        0.        0.       ]
            [3.7376697 3.7612002 3.7841897 3.8066626 3.8286414]], shape=(3, 5), dtype=float32)
    
    B = tf.Tensor(
       [[2 1]
        [2 2]], shape=(2, 2), dtype=int64)
    

    张量 B 在张量中保持指数 A . 我想更新张量中的每一个值 A. 到索引列表中列出的零 .

    tf.Tensor(
           [[1.0986123 0.6931472 0.        0.6931472 0.       ]
            [0.        0.        0.        0.        0.       ]
            [3.7376697 0 0 3.8066626 3.8286414]], shape=(3, 5), dtype=float32)
    

    因此索引[2,1]和[2,2]处的条目被设置为0。

    我看着 tf.assign tf.Variable 的。 tf.boolean_mask

    我查看了可以找到的张量流函数和相关的S/O答案,但找不到满意的解决方案。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Vladimir Bystricky    7 年前

    你可以用 tf.scatter_nd_update 为了这个。例如:

    A = tf.Variable(
        [[1.0986123, 0.6931472, 0.       , 0.6931472, 0.       ],
         [0.       , 0.       , 0.       , 0.       , 0.       ],
         [3.7376697, 3.7612002, 3.7841897, 3.8066626, 3.8286414]], dtype=tf.float32)
    
    B = tf.Variable(
        [[2, 1],
         [2, 2]], dtype=tf.int64)
    
    C = tf.scatter_nd_update(A, B, tf.zeros(shape=tf.shape(B)[0]))
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        print(sess.run(C))
    

    A = tf.constant(
        [[1.0986123, 0.6931472, 0.       , 0.6931472, 0.       ],
         [0.       , 0.       , 0.       , 0.       , 0.       ],
         [3.7376697, 3.7612002, 3.7841897, 3.8066626, 3.8286414]], dtype=tf.float32)
    
    B = tf.constant(
        [[2, 1],
         [2, 2]], dtype=tf.int64)
    
    AV = tf.Variable(A)
    
    C = tf.scatter_nd_update(AV, B, tf.zeros(shape=tf.shape(B)[0]))
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        print(sess.run(C))
    
    推荐文章