0

So basically, my question is the same as Concatenating empty array in Numpy but for Tensorflow.

Mainly, the motivation is to handle the initial array in a prettier way that using a if statement. My current pseudo-code is:

E = None
for a in A:
    if E is None:
        E = a
    else:
        E = tf.concat([E, a], axis=0)

This technique works but I would like to make it a prettier way and maybe using only tf.Tensor. This is a code of a custom layer so I am interested in a code that works inside a model.

I would like a solution closer to the accepted response initializing E as: E = np.array([], dtype=np.int64).reshape(0,5).

This question gets close enough but when I init E as:

E = tf.zeros([a.shape[0], a.shape[1], 0])
...

I get an empty tensor as a result with only the correct shape but not filled.

1 Answer 1

3

In TF2, you can simply port the numpy solution with TensorFlow functions:

>>> xs = tf.constant([[1,2,3,4,5],[10,20,30,40,50]])
>>> ys = tf.reshape(tf.constant([], dtype=tf.int32),(0,5))
>>> ys
<tf.Tensor: shape=(0, 5), dtype=int32, numpy=array([], shape=(0, 5), dtype=int32)>
>>> tf.concat([ys,xs], axis=0)
<tf.Tensor: shape=(2, 5), dtype=int32, numpy=
array([[ 1,  2,  3,  4,  5],
       [10, 20, 30, 40, 50]], dtype=int32)>
Sign up to request clarification or add additional context in comments.

3 Comments

I tried to do that and I get: *** tensorflow.python.framework.errors_impl.InvalidArgumentError: ConcatOp : Dimensions of inputs should match: shape[0] = [0,1,2,3] vs. shape[1] = [1,1,2,3] [Op:ConcatV2] name: concat. My E is <tf.Tensor: shape=(0, 1, 2, 3), dtype=complex64, numpy=array([], shape=(0, 1, 2, 3), dtype=complex64)> and a is <tf.Tensor: shape=(1, 1, 2, 3), dtype=complex64, numpy= array([[[[0.+0.j, 1.+1.j, 2.+2.j], [6.+6.j, 7.+7.j, 8.+8.j]]]], dtype=complex64)>
I can't reproduce. Are you sure you are concatenating along the correct axis?
Ups, you were right! I was using another axis! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.