改变张量某列的值

Changing the Values of a Certain Column of a Tensor

我想用二维张量(批量大小,序列长度)覆盖3维张量(批量大小,序列长度,类的数量)的特定列的值。我在调试时在 numpy 上尝试了以下赋值并且工作得很好但不确定如何在张量上做同样的事情。

Numpy Solution:

    Tensor A shape [50,4,4]
    Tensor B shape [50,4]

  * A[:,:,0]=b[:,:] 
    Tensor A shape is [50,4,4]

Example: 
    A[1]: 
        [[0.2,0.6,0.1,0.02],
        [0.3,0.4,0.5,0.12],
        [0.2,0.46,0.31,0.02],
        [0.2,0.1,0.2,0.03]]
    B[1]:
        [0,1,1,0]
    A*[1]:
        [[0,0.6,0.1,0.02],
        [1,0.4,0.5,0.12],
        [1,0.46,0.31,0.02],
        [0,0.1,0.2,0.03]]

我知道张量不支持项目分配,但想知道是否有办法不丢失 ref 张量的数据。

我认为在这种情况下最简单的事情是:

import tensorflow as tf

a = tf.placeholder(tf.float32, [None, None, None])
b = tf.placeholder(tf.float32, [None, None])
a_star = tf.concat([b[:, :, tf.newaxis], a[:, :, 1:]], axis=-1)
# Test
with tf.Session() as sess:
    print(sess.run(a_star, feed_dict={
        a: [[[0.2 , 0.6 , 0.1 , 0.02],
             [0.3 , 0.4 , 0.5 , 0.12],
             [0.2 , 0.46, 0.31, 0.02],
             [0.2 , 0.1 , 0.2 , 0.03]]],
        b: [[0, 1, 1, 0]]
    }))

输出:

[[[0.   0.6  0.1  0.02]
  [1.   0.4  0.5  0.12]
  [1.   0.46 0.31 0.02]
  [0.   0.1  0.2  0.03]]]

我在TensorFlow issue #18383中提出了一种更灵活的连续切片替换操作,但在这种情况下这可能更简单、更快速。