Home > Blockchain >  How do I add only certain columns to a tensor in tensorflow?
How do I add only certain columns to a tensor in tensorflow?

Time:12-01

Consider the code below:

import tensorflow as tf

test=tf.constant([[[100., 2., -30.],[-4,5,6]], [[4., 5., 6.],[-7,8,9]]]) # matrix

print(test)

test1=tf.constant([[[100.]],[[  8.]]])

print(test1)

When adding test1 to the first two columns of test we would get the following output:

print(test[:,:,0:2] test1)

I do not want to add test1 variable to the last column of the test variable, but at the same time I would like to include the last column of the test variable in the output unchanged:

[[[200. 102., -30.]
  [ 96. 105., 6.]]

 [[ 12.  13., 6]
  [  1.  16., 9]]]

How would I code this quickly?

CodePudding user response:

The simplest option would be to just use tf.concat:

import tensorflow as tf

test = tf.constant([[[100., 2., -30.],[-4,5,6]], [[4., 5., 6.],[-7,8,9]]]) # matrix
test1 = tf.constant([[[100.]],[[  8.]]])

print(tf.concat([test[:,:,0:2]   test1, test[:,:,2:]], axis=-1))
tf.Tensor(
[[[200. 102. -30.]
  [ 96. 105.   6.]]

 [[ 12.  13.   6.]
  [  1.  16.   9.]]], shape=(2, 2, 3), dtype=float32)
  • Related