Fonction torch.transpose de PyTorch
Manuel de référence PyTorch torch
torch.transposeEst une fonction de PyTorch utilisée pour échanger deux dimensions d'un tenseur. Elle renvoie une vue transposée du tenseur d'entrée.
Il s'agit d'une opération couramment utilisée en apprentissage profond pour modifier la forme des données afin de répondre à différents besoins de calcul.
Définition de fonction
torch.transpose(input, dim0, dim1)
Parameters:
input(Tensor) : Le tenseur d'entrée.dim0(int): La première dimension à échanger.dim1(int): La deuxième dimension à échanger.
Valeur de retour:
torch.Tensor: Renvoie la vue transposée du tenseur.
Exemples d'utilisation
Exemple 1: Transposition de matrice 2D
Exemple
import torch
# Créer une matrice 3x4
x = torch.randn(3, 4)
# Transposition
y = torch.transpose(x, 0, 1)
print("Forme d'origine :", x.shape)
print("Forme après transposition :", y.shape)
print("Original:")
print(x)
print("Après transposition :")
print(y)
# Créer une matrice 3x4
x = torch.randn(3, 4)
# Transposition
y = torch.transpose(x, 0, 1)
print("Forme d'origine :", x.shape)
print("Forme après transposition :", y.shape)
print("Original:")
print(x)
print("Après transposition :")
print(y)
La sortie est :
原始形状: torch.Size([3, 4])
转置后形状: torch.Size([4, 3])
原始:
tensor([[ 0.3364, -0.7844, 0.9760, 0.4381],
[ 0.7865, -1.2775, 0.5767, -0.5268],
[-0.6399, -0.6743, -0.2972, -0.4781]])
转置后:
tensor([[ 0.3364, 0.7865, -0.6399],
[-0.7844, -1.2775, -0.6743],
[ 0.9760, 0.5767, -0.2972],
[ 0.4381, -0.5268, -0.4781]])
Exemple 2 : Transposition de tenseur multidimensionnel
Exemple
import torch
# Créer un tenseur 3D
x = torch.randn(2, 3, 4)
# Échanger dim=1 et dim=2
y = torch.transpose(x, 1, 2)
print("Forme d'origine :", x.shape)
print("Forme après transposition :", y.shape)
# Créer un tenseur 3D
x = torch.randn(2, 3, 4)
# Échanger dim=1 et dim=2
y = torch.transpose(x, 1, 2)
print("Forme d'origine :", x.shape)
print("Forme après transposition :", y.shape)
La sortie est :
原始形状: torch.Size([2, 3, 4]) 转置后形状: torch.Size([2, 4, 3])
Notes
torch.transposeIl renvoie une vue, pas une copie.- Pour les tenseurs 2D, vous pouvez également utiliser la
tensor.t()méthode.
Autres extensions