如何在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