Concatenating tensors along a specific dimension

Here, we are creating Two example tensors t1 and t2 using TensorFlow’s tf.constant function. These tensors are 2-dimensional, with each containing two rows and three columns.

Along Axis0:

Here, we use the tf.concat() function to concatenate t1 and t2 along axis 0, i.e., along rows. This means the rows of t2 will be appended after the rows of t1.

Python3




import tensorflow as tf
 
# Example tensors
t1 = tf.constant([[1, 2, 3], [4, 5, 6]])
t2 = tf.constant([[7, 8, 9], [10, 11, 12]])
print('Tensor 1:\n', t1)
print('\nTensor 2:\n', t2)
 
# Concatenate along axis 0 (rows)
result_0 = tf.concat([t1, t2], axis=0)
 
print("\nConcatenated along axis 0:\n", result_0)


Output:

Tensor 1:
tf.Tensor(
[[1 2 3]
[4 5 6]], shape=(2, 3), dtype=int32)
Tensor 2:
tf.Tensor(
[[ 7 8 9]
[10 11 12]], shape=(2, 3), dtype=int32)
Concatenated along axis 0:
tf.Tensor(
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]], shape=(4, 3), dtype=int32)

Along Axis1:

We use the tf.concat() function to concatenate t1 and t2 along axis 1, i.e., along columns. This means the columns of t2 will be appended after the columns of t1.

Python3




import tensorflow as tf
 
# Example tensors
t1 = tf.constant([[1, 2, 3], [4, 5, 6]])
t2 = tf.constant([[7, 8, 9], [10, 11, 12]])
 
print('Tensor 1:\n', t1)
print('\nTensor 2:\n', t2)
# Concatenate along axis 1 (columns)
result_1 = tf.concat([t1, t2], axis=1)
 
print("\nConcatenated along axis 0:\n", result_1)


Output:

Tensor 1:
tf.Tensor(
[[1 2 3]
[4 5 6]], shape=(2, 3), dtype=int32)
Tensor 2:
tf.Tensor(
[[ 7 8 9]
[10 11 12]], shape=(2, 3), dtype=int32)
Concatenated along axis 0:
tf.Tensor(
[[ 1 2 3 7 8 9]
[ 4 5 6 10 11 12]], shape=(2, 6), dtype=int32)

Tensor Concatenations in Tensorflow With Example

Tensor concatenation is a fundamental operation in TensorFlow, essential for combining tensors along specified dimensions. In this article, we will learn about concatenation in TensorFlow and demonstrate the concatenations in python.

Similar Reads

tf.concat

In TensorFlow, the tf.concat function combines tensors along a specified axis....

Concatenating tensors along a specific dimension

Here, we are creating Two example tensors t1 and t2 using TensorFlow’s tf.constant function. These tensors are 2-dimensional, with each containing two rows and three columns....

Handling Negative axis

...

Handling mismatched dimensions

...

Conclusion:

Here, we create Two example tensors t1 and t2 using TensorFlow’s tf.constant function. These tensors are 3-dimensional, with each containing two matrices of size 2×2....

Contact Us