PyTorch學習之torch.transpose函數
一、簡介
torch.transpose
函數我們用于交換張量的維度。
二、語法
torch.transpose
函數用于交換給定張量的兩個維度,其語法如下:
torch.transpose(input, dim0, dim1)
三、參數
input
:待交換維度的張量。dim0
:第一個要交換的維度。dim1
:第二個要交換的維度。
四、示例
示例 1:基本用法
import torch# 創建一個 2x3 的張量
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
print("原始張量:")
print(x)# 交換第 0 維和第 1 維
# x_transposed = torch.transpose(x, 0, 1)
x_transposed = x.transpose(0, 1)
print("交換維度后的張量:")
print(x_transposed)
輸出:
原始張量:
tensor([[1, 2, 3],[4, 5, 6]])
交換維度后的張量:
tensor([[1, 4],[2, 5],[3, 6]])
在這個例子中,原始的 2x3 張量通過交換維度變成了 3x2 張量。
示例 2:高維張量的維度交換
# 創建一個 2x3x4 的張量
x = torch.arange(24).reshape(2, 3, 4)
print("原始張量:")
print(x)# 交換第 0 維和第 2 維
x_transposed = torch.transpose(x, 0, 2)
print("交換維度后的張量:")
print(x_transposed)
輸出:
原始張量:
tensor([[[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11]],[[12, 13, 14, 15],[16, 17, 18, 19],[20, 21, 22, 23]]])
交換維度后的張量:
tensor([[[ 0, 12],[ 4, 16],[ 8, 20]],[[ 1, 13],[ 5, 17],[ 9, 21]],[[ 2, 14],[ 6, 18],[10, 22]],[[ 3, 15],[ 7, 19],[11, 23]]])
在這個例子中,原始的 2x3x4 張量通過交換第 0 維和第 2 維變成了 4x3x2 張量。