如何在 PyTorch 中求张量的转置?


要转置一个张量,我们需要转置两个维度。如果张量是 0 维或 1 维张量,则张量的转置与其自身相同。对于 2 维张量,转置使用两个维度 0 和 1 计算为 **transpose(input, 0, 1)**。

语法

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

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

  • 对于 <= 2D 张量:

Tensor.t()
torch.t(input)
  • 对于任何维度的张量:

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

参数

  • **input** – 要转置的 PyTorch 张量。

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

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

步骤

  • 导入 **torch** 库。确保你已经安装了它。

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

t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Tensor:
", t)
  • 使用上面定义的任何语法查找已定义张量的转置,并可选地将值赋给新变量。

transposedTensor = torch.transpose(t, 0, 1)
  • 打印转置后的张量。

print("Transposed Tensor:
", 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:
",A) print("Size of tensor:",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:
",transposeA) print("Size after transpose:",transposeA.size())

输出

Original Tensor A:
tensor([[[1, 2, 3],
   [3, 4, 5]],

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

   [[1, 2, 4],
   [1, 2, 5]]])
Size of tensor: 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]]])
Size after transpose: torch.Size([2, 3, 3])

更新于:2021年12月6日

7K+ 次查看

启动您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.