Skip to content
Advertisement

How to append rank 1 tensors using only tensorflow operations?

Say I have two rank 1 tensors of different (important) length:

import tensorflow as tf
x = tf.constant([1, 2, 3])
y = tf.constant([4, 5])

Now I want to append y to the end of x to give me the tensor:

<tf.Tensor: shape=(5,), dtype=int32, numpy=array([1, 2, 3, 4, 5], dtype=int32)>

But I can’t seem to figure out how.

I will be doing this inside a function that I will decorate with tf.function, and it is my understanding that everything needs to be tensorflow operations for the tf.function decorator to work. That is, converting x and y to numpy arrays and back to a tensor will cause problems.

Thanks!

EDIT:

The solution is to use tf.concat() as pointed out by @Andrey:

tf.concat([x, y], axis=0)

It turns out that the problem originated when trying to append a single number to the end of a rank 1 tensor as follows:

x = tf.constant([1, 2, 3])
y = tf.constant(5)

tf.concat([x, y], axis=0)

which fails since here y is a rank 0 tensor of shape (). This can be solved by writing:

x = tf.constant([1, 2, 3])
y = tf.constant([5])

tf.concat([x, y], axis=0)

since y will then be a rank 1 tensor of shape (1,).

Advertisement

Answer

Use tf.concat():

import tensorflow as tf
t1 = tf.constant([1, 2, 3])
t2 = tf.constant([4, 5])
output = tf.concat([t1, t2], 0)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement