The torch.rot90() method rotates an n-D tensor by 90 degrees in the plane specified by two dimensions. By rotating the tensor, it reorients the data in a specified plane.

Syntax
torch.rot90(input, k=1, dims=(0, 1))
Parameters
Argument | Description |
input (Tensor) | It represents an input tensor to be rotated. |
k (int, optional) | It represents the number of times to rotate the tensor by 90 degrees.
|
dims (tuple of two ints, optional) |
It is the two dimensions that define the plane of rotation. The default is (0, 1). |
2D Tensor Rotation

Let’s create a 2D tensor using torch.tensor() method and rotate it by 90 degrees counterclockwise.
import torch tensor = torch.tensor([[11, 2, 31], [4, 51, 6]]) print(tensor) # Output: # tensor([[11, 2, 31], # [ 4, 51, 6]]) # Rotate 90 degrees counterclockwise rotated = torch.rot90(tensor, k=1) print(rotated) # Output: # tensor([[31, 6], # [ 2, 51], # [11, 4]])
In the above code, the output tensor is 90 degrees counter-clockwise.
Multiple rotations

To rotate multiple times, we can use the “k” argument. That means, if we want to rotate 180 degrees, we can use the rot90() method and pass k = 2, which means 90 x 2 = 180 degrees.
import torch tensor = torch.tensor([[11, 2, 31], [4, 51, 6]]) print(tensor) # Output: # tensor([[11, 2, 31], # [ 4, 51, 6]]) # Rotate 180 degrees counterclockwise rotated_180 = torch.rot90(tensor, k=2) print(rotated_180) # Output: # tensor([[ 6, 51, 4], # [31, 2, 11]])
Clockwise rotation
Until now, we have performed counterclockwise rotation; now we will perform clockwise rotation.
A negative k value rotates clockwise.
import torch tensor = torch.tensor([[1, 121, 31], [14, 511, 61]]) print(tensor) # Output: # tensor([[ 1, 121, 31], # [ 14, 511, 61]]) # Rotate 90 degrees clockwise rotated_clockwise = torch.rot90(tensor, k=-1) print(rotated_clockwise) # Output: # tensor([[ 14, 1], # [511, 121], # [ 61, 31]])
You can see that we passed k = -1, which means it rotated clockwise instead of counterclockwise.
You can see that the last row became the first column.
Rotating a higher-dimensional tensor
Let’s define a 3D tensor and rotate it counterclockwise in a specific plane.
import torch tensor_3d = torch.arange(24).reshape(2, 3, 4) print(tensor_3d) # Output: # tensor([[[ 0, 1, 2, 3], # [ 4, 5, 6, 7], # [ 8, 9, 10, 11]], # [[12, 13, 14, 15], # [16, 17, 18, 19], # [20, 21, 22, 23]]]) # Rotate 90 degrees anticlockwise rotated_3d_tensor = torch.rot90(tensor_3d, k=1, dims=(1, 2)) print(rotated_3d_tensor) # Output: # tensor([[[ 3, 7, 11], # [ 2, 6, 10], # [ 1, 5, 9], # [ 0, 4, 8]], # [[15, 19, 23], # [14, 18, 22], # [13, 17, 21], # [12, 16, 20]]])
In the above code, the rotation occurs in the plane defined by dims=(1, 2), affecting the last two dimensions (3×4) for each slice of the first dimension. The shape changes from (2, 3, 4) to (2, 4, 3).
That’s all!