1

I want to overwrite the values of a certain column of a 3-dimensional tensor(batch size, sequence length, number of classes) with a 2-dimensional tensor (batch size, sequence length). I have tried the following value assignment on numpy while debugging and worked perfectly fine but not sure how to do the same on tensor.

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

I know that item assignment is not supported on tensors but was wondering if there is a way without losing the data of ref tensor.

srdeep
  • 67
  • 4
  • Does [this question](https://stackoverflow.com/questions/44657388/how-to-replace-certain-values-in-tensorflow-tensor-with-the-values-of-the-other) help you? – Ben.T Nov 26 '18 at 14:34

1 Answers1

2

I think the easiest thing in this case would be:

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

Output:

[[[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]]]

I proposed a more flexible replacement operation for contiguous slices in TensorFlow issue #18383, but this is probably simpler and faster in this case.

jdehesa
  • 58,456
  • 7
  • 77
  • 121