Transposing a 3D Tensor
Here, we created a 3D tensor named tensor. We use the tf.constant() function to create a constant tensor with the specified values. The tensor x has a shape of (2, 2, 3), meaning it contains two 2×3 matrices.
Then, we use the tf.transpose() function to transpose the tensor and we use the permutation [0, 2, 1], which means we’re swapping the second and third dimensions of the tensor. As a result, the rows and columns within each 2×3 matrix are transposed.
Finally, it prints both the original tensor and its transposed version.
Python3
import numpy as np # Define the dimensions of the 3D tensor depth = 2 rows = 2 cols = 3 # Define the range of integers min_value = 0 max_value = 50 # Adjust as needed # Generate a 3D tensor of random integers tensor = np.random.randint(min_value, max_value + 1 , size = (depth, rows, cols)) # Print the generated 3D tensor print ( "Tensor:" ) print (tensor) # Transpose the tensor transposed_x = tf.transpose(tensor, perm = [ 0 , 2 , 1 ]) print ( "Transpose of tensor:" ) print (transposed_x.numpy()) |
Output:
Tensor:
[[[19 39 29]
[25 14 34]]
[[ 8 16 31]
[11 41 6]]]
Transpose of tensor:
[[[19 25]
[39 14]
[29 34]]
[[ 8 11]
[16 41]
[31 6]]]
Tensor Transpose in Tensorflow With Example
Tensor transpose is a fundamental operation in TensorFlow that rearranges the dimensions of a tensor according to a specified permutation. This operation is crucial in various machine learning algorithms and data manipulation tasks.
Tensor is useful when dealing with multidimensional data, such as images, time series, and sequences. Transposing a tensor changes the order of its dimensions, providing flexibility in data manipulation and computation.
In this article, we will learn Tensor Transpose in TensorFlow with Example.
Syntax of tf.transpose()
tf.transpose(
a, perm=None, conjugate=False, name=’transpose’
)
Parameters
- a: Input tensor.
- perm: Permutation of dimensions. If not provided, the default permutation is set to (n-1…0), where n is the rank of the input tensor.
- conjugate: Optional parameter for complex tensors. The values are conjugated and transposed if set to True and the tensor dtype is either complex64 or complex128.
- name: Optional parameter for operation name.
Contact Us