如何在PyTorch中执行置换操作?
**torch.permute()** 方法用于对PyTorch张量执行置换操作。它返回输入张量的一个视图,其维度已重新排列。它不会复制原始张量。
例如,一个维度为[2, 3]的张量可以被置换为[3, 2]。我们也可以使用**Tensor.permute()**来使用新的维度置换张量。
语法
torch.permute(input,dims)
参数
**input** – PyTorch张量。
**dims** – 期望维度的元组。
步骤
导入**torch**库。确保你已经安装了它。
import torch
创建一个PyTorch张量并打印张量及其大小。
t = torch.tensor([[1,2],[3,4],[5,6]])
print("Tensor:
", t)
print("Size of tensor:", t.size()) # size 3x2计算**torch.permute(input, dims)**并将值赋给一个变量。它不会改变原始张量**input**。
t1 = torch.permute(t, (1,0))
打印置换操作后生成的张量及其大小。
print("Tensor after Permuting:
", t1)
print("Size after permuting:", t1.size())示例1
在下面的Python程序中,输入张量的维度为[3,2]。我们使用dims = (1, 0)来将张量置换为新的维度[2,3]。
# import the torch library
import torch
# create a tensor
t = torch.tensor([[1,2],[3,4],[5,6]])
# print the created tensor
print("Tensor:
", t)
print("Size of tensor:", t.size())
# perform permute operation
t1 = torch.permute(t,(1,0))
# print the permuted tensor
print("Tensor after Permuting:
", t1)
print("Size after permuting:", t1.size())输出
Tensor:
tensor([[1, 2],
[3, 4],
[5, 6]])
Size of tensor: torch.Size([3, 2])
Tensor after Permuting:
tensor([[1, 3, 5],
[2, 4, 6]])
Size after permuting: torch.Size([2, 3])示例2
在下面的Python代码中,输入张量的大小为[2,3,1]。我们使用**dims = (0,2,1)**。它会返回一个具有维度[2,1,3]的输入张量视图。
# import torch library
import torch
# create a tensor
t = torch.randn(2,3,1)
# print the created tensor
print("Tensor:
", t)
print("Size of tensor:", t.size())
# perform permute
t1 = torch.permute(t, (0,2,1))
# print the resultant tensor
print("Tensor after Permuting:
", t1)
print("Size after permuting:", t1.size())输出
Tensor:
tensor([[[ 1.5285],
[-0.2401],
[ 0.2378]],
[[ 0.4733],
[-1.7317],
[ 0.7557]]])
Size of tensor: torch.Size([2, 3, 1])
Tensor after Permuting:
tensor([[[ 1.5285, -0.2401, 0.2378]],
[[ 0.4733, -1.7317, 0.7557]]])
Size after permuting: torch.Size([2, 1, 3])
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP