How to insert a value at given index or indices ( mutiple index ) into a Tensor?

1.2k Views Asked by At

I am having a matrix of size 12 x 10 and a list of document_length = [4,3,5] . The first 4 rows belongs to sentences of one document, next 3 to other doc and last 5 to other doc. I need to get a new matrix or Tensor of size 15 x 10 in the following manner.

I need to insert a row of zeros, in such a way that, here max doc length is 5. So, 1 row of zero has to be inserted in 5th index ( because first doc length is 4 ) . Then 2 row of zeros at index 9 and 10 ( second doc length is 3 ) and so on . If the question is confusing please let me know .

I have feed 12 x 10 to GRU or LSTM , but it has to be in a 3d . To get a proper 3D, I need to convert 12 X 10 to 15 x 10 . Any help ?

1

There are 1 best solutions below

6
On BEST ANSWER

Here is a way to do it. You first break down your 12x10 Tensor into a list of size 12. This is done using the tf.unstack() function.

# Assume `words` is my 12x10 tensor
tensors = tf.unstack(words, 12, axis=0) 

After that, you can insert tf.zeros() tensors into the list at your indices. Here for simplicity, I will just insert a tensor in index 4.

b = tf.zeros((10))
tensors.insert(4, b)

Finally, tf.stack() your list to re-construct it.

words = tf.stack(tensors, axis=0)