Home > Mobile >  tf.concat tensors with different length
tf.concat tensors with different length

Time:12-06

I have 2 tensors like:

a = tf.constant([[1, 2, 3], [1, 2, 3]])
b = tf.constant([1, 2, 3, 4, 5])

My desired output would be:

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

But when I try tf.concat([a, b], axis=0) I get this error:

InvalidArgumentError: ConcatOp : Dimensions of inputs should match: shape[0] = [2,3] vs. shape[1] = [1,5] [Op:ConcatV2] name: concat

CodePudding user response:

Try this:

a = tf.constant([[1, 2, 3], [1, 2, 3]])
b = tf.constant([1, 2, 3, 4, 5])

c = tf.concat([tf.pad(a, tf.constant([[0,0], [0,2]])), tf.expand_dims(b, axis=0)], axis=0)
tf.print(c)

[[1 2 3 0 0]
 [1 2 3 0 0]
 [1 2 3 4 5]]
  • Related