Tensorflow tf concat

less than 1 minute read

tf.concat

tf.tile

tf.concat(
    values,
    axis,
    name='concat'
)
  • For example:
import tensorflow as tf
tf.InteractiveSession()

t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
tf.concat([t1, t2], 0)  # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
tf.concat([t1, t2], 1)  # [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]

# tensor t3 with shape [2, 3]
# tensor t4 with shape [2, 3]
tf.shape(tf.concat([t3, t4], 0))  # [4, 3]
tf.shape(tf.concat([t3, t4], 1))  # [2, 6]

As in Python, the axis could also be negative numbers. Negative axis are interpreted as counting from the end of the rank, i.e., axis + rank(values)-th dimension.

  • For example:
t1 = [[[1, 2], [2, 3]], [[4, 4], [5, 3]]]
t2 = [[[7, 4], [8, 4]], [[2, 10], [15, 11]]]
tf.concat([t1, t2], -1)

#would produce:

[[[ 1,  2,  7,  4],
  [ 2,  3,  8,  4]],

 [[ 4,  4,  2, 10],
  [ 5,  3, 15, 11]]]

t1 = [[[1, 2, 3], [4, 5, 6]]]
t2 = [[[7, 8, 9], [10, 11, 12]]]
out = tf.concat([t1, t2], 2)  

print(out.eval())

[[[ 1  2  3  7  8  9]
  [ 4  5  6 10 11 12]]]