Tensor Transpose in Tensorflow With Example
Last Updated :
23 Jul, 2025
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.
Transposing a 2D Tensor
Here, we have created a random tensor using NumPy module. We have defined the dimensions of the tensor is 2x3. 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 2x3 matrix of random integers, and the transpose operation switches the rows and columns, resulting in a 3x2 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)
Transposing a Complex Tensor with Conjugation
Here, we generate a tensor of complex numbers using NumPy and TensorFlow. It defines the dimensions of the tensor, the range of values for the real and imaginary parts, and then creates the complex tensor. After converting it into a TensorFlow constant, the code transposes the tensor while conjugating its elements using TensorFlow's tf.transpose()
function with conjugate=True
. Finally, it prints both the original tensor and the transposed tensor with conjugation.
Python3
import numpy as np
# Define the dimensions of the complex matrix
num_rows = 3
num_cols = 3
#range
min_val = 0
max_val = 50
# Generate a tensor of complex numbers
complex_tensor = np.random.randint(min_val, max_val +1, size=(num_rows, num_cols))+ 1j * np.random.randint(min_val, max_val,size=(num_rows, num_cols))
tensor = tf.constant(complex_tensor)
print("tensor of complex numbers: ")
print(tensor)
# Transpose the tensor with conjugation
transposed_conj_x = tf.transpose(tensor, conjugate=True)
print("Transposed Conjugate tensor:")
print(transposed_conj_x)
Output:
tensor of complex numbers:
tf.Tensor(
[[15. +9.j 12.+27.j 19.+46.j]
[45.+48.j 16.+21.j 49.+27.j]
[12. +5.j 1.+45.j 32.+46.j]], shape=(3, 3), dtype=complex128)
Transposed Conjugate tensor:
tf.Tensor(
[[15. -9.j 45.-48.j 12. -5.j]
[12.-27.j 16.-21.j 1.-45.j]
[19.-46.j 49.-27.j 32.-46.j]], shape=(3, 3), dtype=complex128)
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 2x3 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 2x3 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]]]
Transposing Tensors with Batch Dimension
Here, we create a tensor with a batch dimension. The tensor contains three 2x2 matrices, representing a batch of data samples. Each 2x2 matrix corresponds to a single data sample.
Then, we use the tf.transpose() function to transpose the tensor and we use the permutation [1, 0, 2], which means we're swapping the first and second dimensions of the tensor. As a result, the batch and feature dimensions are swapped.
Python3
import tensorflow as tf
# Define a tensor with a batch dimension
depth = 3
rows = 2
cols = 2
#range
min_value = 0
max_value = 50 # Adjust as needed
# Generate a 3D tensor of random integers
tensor = tf.constant(np.random.randint(min_value, max_value + 1, size=(depth, rows, cols)))
print("tensor:")
print(tensor)
# Transpose the tensor to swap the batch and feature dimensions
transposed_x = tf.transpose(tensor, perm=[1, 0, 2])
print("transpose of tensor:")
print(transposed_x.numpy())
Output:
tensor:
tf.Tensor(
[[[23 8]
[37 13]]
[[41 20]
[37 20]]
[[48 13]
[11 37]]], shape=(3, 2, 2), dtype=int64)
transpose of tensor:
[[[23 8]
[41 20]
[48 13]]
[[37 13]
[37 20]
[11 37]]]
Transposing a High-dimensional Tensor
Here, we create a 4D tensor named x. The tensor contains two sets of 2x2 matrices, arranged in a 2x2x2x2 structure. This means we have two sets of 2x2 matrices, where each set is arranged along two dimensions.
Then, we use the tf.transpose() function to transpose the tensor and we use the permutation [0, 2, 1, 3], which means we're rearranging the dimensions of the tensor. The first and third dimensions are swapped, and the second dimension remains unchanged.
Python3
import tensorflow as tf
# Define a 4D tensor
x = tf.constant([[[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]],
[[[9, 10],
[11, 12]],
[[13, 14],
[15, 16]]]])
# Transpose the tensor to change the order of dimensions
transposed_x = tf.transpose(x, perm=[0, 2, 1, 3])
print("Transposed 4D Tensor:")
print(transposed_x.numpy())
Output:
Transposed 4D Tensor:
[[[[ 1 2]
[ 5 6]]
[[ 3 4]
[ 7 8]]]
[[[ 9 10]
[13 14]]
[[11 12]
[15 16]]]]
Conclusion
In conclusion, Tensor transpose is a fundamental operation in TensorFlow used for rearranging tensor dimensions. In this article, we learned transposing 2D, complex, 3D, and high-dimensional tensors.
Similar Reads
Deep Learning Tutorial Deep Learning is a subset of Artificial Intelligence (AI) that helps machines to learn from large datasets using multi-layered neural networks. It automatically finds patterns and makes predictions and eliminates the need for manual feature extraction. Deep Learning tutorial covers the basics to adv
5 min read
Deep Learning Basics
Introduction to Deep LearningDeep Learning is transforming the way machines understand, learn and interact with complex data. Deep learning mimics neural networks of the human brain, it enables computers to autonomously uncover patterns and make informed decisions from vast amounts of unstructured data. How Deep Learning Works?
7 min read
Artificial intelligence vs Machine Learning vs Deep LearningNowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are
4 min read
Deep Learning Examples: Practical Applications in Real LifeDeep learning is a branch of artificial intelligence (AI) that uses algorithms inspired by how the human brain works. It helps computers learn from large amounts of data and make smart decisions. Deep learning is behind many technologies we use every day like voice assistants and medical tools.This
3 min read
Challenges in Deep LearningDeep learning, a branch of artificial intelligence, uses neural networks to analyze and learn from large datasets. It powers advancements in image recognition, natural language processing, and autonomous systems. Despite its impressive capabilities, deep learning is not without its challenges. It in
7 min read
Why Deep Learning is ImportantDeep learning has emerged as one of the most transformative technologies of our time, revolutionizing numerous fields from computer vision to natural language processing. Its significance extends far beyond just improving predictive accuracy; it has reshaped entire industries and opened up new possi
5 min read
Neural Networks Basics
What is a Neural Network?Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamental
12 min read
Types of Neural NetworksNeural networks are computational models that mimic the way biological neural networks in the human brain process information. They consist of layers of neurons that transform the input data into meaningful outputs through a series of mathematical operations. In this article, we are going to explore
7 min read
Layers in Artificial Neural Networks (ANN)In Artificial Neural Networks (ANNs), data flows from the input layer to the output layer through one or more hidden layers. Each layer consists of neurons that receive input, process it, and pass the output to the next layer. The layers work together to extract features, transform data, and make pr
4 min read
Activation functions in Neural NetworksWhile building a neural network, one key decision is selecting the Activation Function for both the hidden layer and the output layer. It is a mathematical function applied to the output of a neuron. It introduces non-linearity into the model, allowing the network to learn and represent complex patt
8 min read
Feedforward Neural NetworkFeedforward Neural Network (FNN) is a type of artificial neural network in which information flows in a single direction i.e from the input layer through hidden layers to the output layer without loops or feedback. It is mainly used for pattern recognition tasks like image and speech classification.
6 min read
Backpropagation in Neural NetworkBack Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Deep Learning Models
Deep Learning Frameworks
TensorFlow TutorialTensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
2 min read
Keras TutorialKeras high-level neural networks APIs that provide easy and efficient design and training of deep learning models. It is built on top of powerful frameworks like TensorFlow, making it both highly flexible and accessible. Keras has a simple and user-friendly interface, making it ideal for both beginn
3 min read
PyTorch TutorialPyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the networkâs behavior in real-time, making it an excellent choice for both beginners an
7 min read
Caffe : Deep Learning FrameworkCaffe (Convolutional Architecture for Fast Feature Embedding) is an open-source deep learning framework developed by the Berkeley Vision and Learning Center (BVLC) to assist developers in creating, training, testing, and deploying deep neural networks. It provides a valuable medium for enhancing com
8 min read
Apache MXNet: The Scalable and Flexible Deep Learning FrameworkIn the ever-evolving landscape of artificial intelligence and deep learning, selecting the right framework for building and deploying models is crucial for performance, scalability, and ease of development. Apache MXNet, an open-source deep learning framework, stands out by offering flexibility, sca
6 min read
Theano in PythonTheano is a Python library that allows us to evaluate mathematical operations including multi-dimensional arrays efficiently. It is mostly used in building Deep Learning Projects. Theano works way faster on the Graphics Processing Unit (GPU) rather than on the CPU. This article will help you to unde
4 min read
Model Evaluation
Deep Learning Projects