【张量乘法】pytorch中的mul、dot、mm、matmul

发布于:2024-05-31 ⋅ 阅读:(146) ⋅ 点赞:(0)

张量的乘法是pytorch等神经网络开发框架中最常见、最基本的操作之一。

1,torch.mul

对应位置的元素相乘。mul即表示张量中对应位置元素的相乘,也是最容易理解的乘法。

import torch
a = torch.tensor([[1, 2], [3, 4]])
b = torch.tensor([[5, 6], [7, 8]])
res = torch.mul(a, b)
print(res)

# [[ 5, 12], [21, 32]]

2, torch.dot

表示两个1D向量的点乘:(注意:torch.dot和np.dot用法差异较大
t o r c h . d o t ( [ x 1 , y 1 ] , [ x 2 , y 2 ] ) = x 1 ⋅ x 2 + y 1 ⋅ y 2 (1) torch.dot([x_1,y_1], [x_2,y_2]) =x_1\cdot x_2+ y_1\cdot y_2 \tag{1} torch.dot([x1,y1],[x2,y2])=x1x2+y1y2(1)
两个1D-vector在torch.dot后变成一个标量。实验代码:

res = torch.dot(torch.tensor([2, 3]), torch.tensor([2, 1]))
print(res)
# 7

torch.dot使用有以下要求:

  1. 只针对1D向量;
  2. 向量必须等长;

3,torch.mm

表示矩阵乘法, ( m , n ) × ( n , p ) → ( m , p ) (m,n) \times (n,p) \rightarrow (m, p) (m,n)×(n,p)(m,p)

import torch
a = torch.tensor([[1, 2], [3, 4]])
b = torch.tensor([[5, 6], [7, 8]])
res = torch.mm(a, b)
print(res)
# [[19, 22], [43, 50]]

4,torch.matmul

也表示矩阵乘,在输入2个1D向量时,表现出与torch.dot一样的效果:

res = torch.matmul(torch.tensor([2, 3]), torch.tensor([2, 1]))
print(res)
# 7

输入2个2D向量时,表达的是矩阵乘法,与torch.mm有一样的效果。

import torch

# 1D x 1D
res = torch.matmul(torch.tensor([2, 3]), torch.tensor([2, 1]))
print(res)
# 7

# 2D x 2D
a = torch.tensor([[1, 2], [3, 4]])
b = torch.tensor([[5, 6], [7, 8]])
res = torch.matmul(a, b)
print(res)
# [[19, 22], [43, 50]]

# 1D x 2D
a = torch.tensor([1, 2])
b = torch.tensor([[5, 6], [7, 8]])
res = torch.matmul(a, b)
print(res)
# [19, 22]

# 2D x 1D
a = torch.tensor([[1, 2], [3, 4]])
b = torch.tensor([5, 6])
res = torch.matmul(a, b)
print(res)
# [17, 39]

# (j, 1, n, n) x (k, n, n) -> (j, k, n, n)
# (j, 1, n, m) x (k, m, p) -> (j, k, n, p)