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