PyTorch torch.rot90 Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.rot90It is a function in PyTorch used to rotate tensors by 90 degrees.

Function Definition

torch.rot90(input, k=1, dims=[0, 1])

Parameter Description:

  • input- Input tensor
  • k- Number of rotations, positive means counterclockwise, negative means clockwise (default 1)
  • dims- Plane dimensions for rotation (default [0, 1])

Usage Examples

Example

import torch

# 2D tensor rotation
x = torch.arange(12).reshape(3, 4)
print("Original tensor:")
print(x)

result = torch.rot90(x, 1)
print("Counterclockwise rotation by 90 degrees:")
print(result)

result = torch.rot90(x, -1)
print("nClockwise rotation by 90 degrees:")
print(result)

result = torch.rot90(x, 2)
print("nRotation by 180 degrees:")
print(result)

# Rotate along a specified plane (3D tensor)
y = torch.arange(24).reshape(2, 3, 4)
print("n3D tensor shape:", y.shape)

result = torch.rot90(y, 1, dims=[1, 2])
print("Shape after rotating 90 degrees along the [1, 2] plane:", result.shape)

The output result is:

原始张量:
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
逆时针旋转 90 度:
tensor([[ 3,  7, 11],
        [ 2,  6, 10],
        [ 1,  5,  9],
        [ 0,  4,  8]])

顺时针旋转 90 度:
tensor([[ 8,  4,  0],
        [ 9,  5,  1],
        [10,  6,  2],
        [11,  7,  3]])

旋转 180 度:
tensor([[11, 10,  9,  8],
        [ 7,  6,  5,  4],
        [ 3,  2,  1,  0]])

三维张量形状: torch.Size([2, 3, 4])
沿 [1, 2] 平面旋转 90 度后形状: torch.Size([2, 4, 3])

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions