Handling Negative axis

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.

Then, we use the tf.concat() function to concatenate t1 and t2 along the last dimension using a negative axis value (-1). Negative axis values count from the end of the tensor’s shape. In this case, -1 refers to the last dimension.

Python3




import tensorflow as tf
 
# Example tensors
t1 = tf.constant([[[1, 2], [2, 3]], [[4, 4], [5, 3]]])
t2 = tf.constant([[[7, 4], [8, 4]], [[2, 10], [15, 11]]])
 
print('Tensor 1:\n', t1)
print('\nTensor 2:\n', t2)
 
# Concatenate along the last dimension using negative axis
result = tf.concat([t1, t2], axis=-1)
 
print("\nConcatenated along last dimension:\n", result)


Output:

Tensor 1:
tf.Tensor(
[[[1 2]
[2 3]]
[[4 4]
[5 3]]], shape=(2, 2, 2), dtype=int32)
Tensor 2:
tf.Tensor(
[[[ 7 4]
[ 8 4]]
[[ 2 10]
[15 11]]], shape=(2, 2, 2), dtype=int32)
Concatenated along last dimension:
tf.Tensor(
[[[ 1 2 7 4]
[ 2 3 8 4]]
[[ 4 4 2 10]
[ 5 3 15 11]]], shape=(2, 2, 4), 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