Transposing a 2D Tensor
Here, we have created a random tensor using NumPy module. We have defined the dimensions of the tensor is 2×3. We use the tf.constant() function to create a constant tensor with the specified values. Then we transposed the 2D tensor using tf.tensor() function. Finally, the original matrix and its transpose are printed. The original matrix represents a 2×3 matrix of random integers, and the transpose operation switches the rows and columns, resulting in a 3×2 matrix.
Python3
import numpy as np import tensorflow as tf # Define the dimensions of the random matrix num_rows = 2 num_cols = 3 # Define the range of integers min_value = 0 max_value = 50 # Adjust as needed # Generate a tensor tensor = np.random.randint(min_value, max_value + 1 , size = ( num_rows, num_cols)) tensor = tf.constant(matrix) #Transpose the tensor transposed_tensor = tf.transpose(tensor) #print the original matrix and transpose of the matrix print ( "Tensor:" ) print (tensor) print ( "Transpose of Tensor" ) print (transposed_tensor) |
Output:
Tensor:
tf.Tensor(
[[[40 41]
[13 1]]
[[22 13]
[ 4 1]]
[[25 21]
[35 24]]], shape=(3, 2, 2), dtype=int64)
Transpose of Tensor
tf.Tensor(
[[[40 22 25]
[13 4 35]]
[[41 13 21]
[ 1 1 24]]], shape=(2, 2, 3), dtype=int64)
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