如何在 PyTorch 中找到张量的转置?

要转置张量,我们需要转置两个维度。如果张量是 0-D 或 1-D 张量,则张量的转置与原样相同。对于二维张量,使用两个维度 0 和 1 作为transpose(input, 0, 1)计算转置

语法

要找到标量、向量或矩阵的转置,我们可以应用下面定义的第一个语法。

对于任何维度张量,我们都可以应用第二种语法。

  • 对于 <= 2D 张量,

Tensor.t()
torch.t(input)

  • 对于任何维张量,

Tensor.transpose(dim0, dim1) or
torch.transpose(input, dim0, dim1)

参数

  • 输入- 这是一个要转置的 PyTorch 张量。

  • dim0 – 这是要转置的第一个维度。

  • dim1 – 这是要转置的第二个维度。

步骤

  • 导入火炬库。确保您已经安装了它。

import torch

  • 创建 PyTorch 张量并打印张量。在这里,我们创建了一个 3×3 张量。

t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Tensor:\n", t)

  • 使用上面定义的任何语法查找定义的张量的转置,并可选择将值分配给新变量。

transposedTensor = torch.transpose(t, 0, 1)

  • 打印转置张量。

print("Transposed Tensor:\n", transposedTensor)

示例 1

# Python program to find transpose of a 2D tensor
# import torch library
import torch

# define a 2D tensor
A = torch.rand(2,3)
print(A)

# compute the transpose of the above tensor
print(A.t())
# or print(torch.t(A))

print(A.transpose(0, 1))
# or print(torch.transpose(A, 0, 1))
输出结果
tensor([[0.0676, 0.2984, 0.6766],
   [0.6200, 0.5874, 0.4150]])
tensor([[0.0676, 0.6200],
   [0.2984, 0.5874],
   [0.6766, 0.4150]])
tensor([[0.0676, 0.6200],
   [0.2984, 0.5874],
   [0.6766, 0.4150]])

示例 2

# Python program to find transpose of a 3D tensor
# import torch library
import torch

# create a 3D tensor
A = torch.tensor([[[1,2,3],[3,4,5]],
   [[5,6,7],[1,2,2]],
   [[1,2,4],[1,2,5]]])
print("Original Tensor A:\n",A)
print("张量的大小:",A.size())

# print(A.t()) --> Error
# compute the transpose of the tensor
transposeA = torch.transpose(A, 0,1)
# other way to compute the transpose
# transposeA = A.transpose(0,1)

print("Transposed Tensor:\n",transposeA)
print("转置后的大小:",transposeA.size())
输出结果
Original Tensor A:
tensor([[[1, 2, 3],
   [3, 4, 5]],

   [[5, 6, 7],
   [1, 2, 2]],

   [[1, 2, 4],
   [1, 2, 5]]])
张量的大小: torch.Size([3, 2, 3])
Transposed Tensor:
tensor([[[1, 2, 3],
   [5, 6, 7],
   [1, 2, 4]],

   [[3, 4, 5],
   [1, 2, 2],
   [1, 2, 5]]])
转置后的大小: torch.Size([2, 3, 3])