Fonction torch.matmul de PyTorch
Manuel de référence torch de Pytorch
torch.matmulIl s'agit d'une fonction de PyTorch utilisée pour effectuer une multiplication matricielle. Elle prend en charge des entrées de dimensions différentes et peut gérer la multiplication de tenseurs à une, deux et plusieurs dimensions.
Il s'agit de l'une des opérations les plus couramment utilisées en apprentissage profond. La propagation avant d'un réseau de neurones est essentiellement une série de multiplications matricielles.
Définition de fonction
torch.matmul(input, other, out=None)
Parameters:
input(Tensor) : Le premier tenseur d'entrée.other(Tensor) : Le deuxième tenseur d'entrée.out(Tensor, optionnel) : Le tenseur de sortie.
Valeur de retour:
torch.Tensor: Renvoie le résultat de la multiplication matricielle.
Exemples d’utilisation
Exemple 1 : Multiplication de matrices bidimensionnelles
Exemple
# Créer deux matrices 2D
a = torch.randn(3, 4) # matrice 3x4
b = torch.randn(4, 5) # matrice 4x5
# Multiplication matricielle
c = torch.matmul(a, b)
print("Forme de a :", a.shape)
print("Forme de b :", b.shape)
print("Forme de c :", c.shape)
La sortie est :
a 的形状: torch.Size([3, 4]) b 的形状: torch.Size([4, 5]) c 的形状: torch.Size([3, 5])
Exemple 2 : Multiplication d'un vecteur et d'une matrice
Exemple
# Créer un vecteur et une matrice
vector = torch.randn(4) # vecteur à 4 dimensions
matrix = torch.randn(4, 5) # matrice 4x5
# Multiplier un vecteur et une matrice
result = torch.matmul(vector, matrix)
print("Forme du vecteur :", vector.shape)
print("Forme de la matrice :", matrix.shape)
print("Forme du résultat :", result.shape)
print(result)
La sortie est :
向量的形状: torch.Size([4]) 矩阵的形状: torch.Size([4, 5]) 结果的形状: torch.Size([5]) tensor([-0.7837, 0.3684, -0.6542, -0.4594, 1.5328]) </p> <h3>示例 3: 批量矩阵乘法</h3> <div class="example"> <h2 class="example">实例</h2> <div class="example_code"> <span style="color: Green;font-weight:bold;">import</span> torch<br /> <br /> <span style="color: #a50"># 创建批量矩阵</span><br /> batch_a <span style="color: Gray;">=</span> torch.<span style="color: #05a;">randn</span><span style="color: Olive;">(</span><span style="color: Maroon;">10</span><span style="color: Gray;">,</span> <span style="color: Maroon;">3</span><span style="color: Gray;">,</span> <span style="color: Maroon;">4</span><span style="color: Olive;">)</span> <span style="color: #a50"># 10 个 3x4 矩阵</span><br /> batch_b <span style="color: Gray;">=</span> torch.<span style="color: #05a;">randn</span><span style="color: Olive;">(</span><span style="color: Maroon;">10</span><span style="color: Gray;">,</span> <span style="color: Maroon;">4</span><span style="color: Gray;">,</span> <span style="color: Maroon;">5</span><span style="color: Olive;">)</span> <span style="color: #a50"># 10 个 4x5 矩阵</span><br /> <br /> <span style="color: #a50"># 批量矩阵乘法</span><br /> batch_c <span style="color: Gray;">=</span> torch.<span style="color: #05a;">matmul</span><span style="color: Olive;">(</span>batch_a<span style="color: Gray;">,</span> batch_b<span style="color: Olive;">)</span><br /> <br /> <span style="color: Green;font-weight:bold;">print</span><span style="color: Olive;">(</span><span style="color: #a11;">"批量 a 的形状:"</span><span style="color: Gray;">,</span> batch_a.<span style="color: #05a;">shape</span><span style="color: Olive;">)</span><br /> <span style="color: Green;font-weight:bold;">print</span><span style="color: Olive;">(</span><span style="color: #a11;">"批量 b 的形状:"</span><span style="color: Gray;">,</span> batch_b.<span style="color: #05a;">shape</span><span style="color: Olive;">)</span><br /> <span style="color: Green;font-weight:bold;">print</span><span style="color: Olive;">(</span><span style="color: #a11;">"批量结果 c 的形状:"</span><span style="color: Gray;">,</span> batch_c.<span style="color: #05a;">shape</span><span style="color: Olive;">)</span><br /> </div> </div> <p>输出结果为:</p> <pre> 批量 a 的形状: torch.Size([10, 3, 4]) 批量 b 的形状: torch.Size([10, 4, 5]) 批量结果 c 的形状: torch.Size([10, 3, 5])
La multiplication matricielle par lots est une opération courante en apprentissage profond, par exemple dans le mécanisme d'attention des Transformers.
Exemple 4 : Multiplication matricielle dans les réseaux de neurones
Exemple
# Simuler une couche de réseau de neurones : entrée xW + b
x = torch.randn(32, 128) # Taille de lot 32, dimension des caractéristiques 128
W = torch.randn(128, 256) # Matrice de poids
b = torch.randn(256) # Vecteur de biais
# Transformation linéaire : y = x @ W^T + b (dans PyTorch, W est généralement transposé)
# Ici, nous démontrons x @ W
y = torch.matmul(x, W) + b
print("Forme de l'entrée x :", x.shape)
print("Forme du poids W :", W.shape)
print("Forme de la sortie y :", y.shape)
La sortie est :
输入 x 形状: torch.Size([32, 128]) 权重 W 形状: torch.Size([128, 256]) 输出 y 形状: torch.Size([32, 256])
Cet exemple simule le processus de propagation avant d'une couche entièrement connectée dans un réseau de neurones.
Notes
torch.matmulLa diffusion (broadcasting) est prise en charge, mais les deux dernières dimensions des deux entrées doivent respecter les contraintes de dimensions de la multiplication matricielle.- Pour la multiplication matricielle en deux dimensions, vous pouvez également utiliser
torch.mm(), maistorch.matmulest plus général. - Notez la différence entre
torch.matmul(multiplication matricielle) ettorch.mul(multiplication élément par élément).
Autres extensions