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

张量的乘法是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)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木盏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值