python中的乘法
1. Hadamard积(按元素相乘):x*y、torch.mul
可用于矩阵*矩阵;
// 矩阵 * 矩阵
x = torch.tensor([[1,2],[3,4]])
y = torch.tensor([[1,2],[3,4]])
x,y,x*y,torch.mul(x,y)
//out
(tensor([[1, 2],
[3, 4]]),
tensor([[1, 2],
[3, 4]]))
tensor([[ 1, 4],
[9, 16]])
tensor([[ 1, 4],
[9, 16]])
也可用于向量*向量
x = torch.tensor([1,2,3,4])
y = torch.tensor([1,2,3,4])
x*y,torch.mul(x,y)
//out
tensor([ 1, 4, 9, 16])
tensor([ 1, 4, 9, 16])
2. 向量点积:torch.dot(x,y)
用于向量乘法
# 向量的点积,只可用于一维。对应元素相乘再相加
import torch
x = torch.tensor([1,2,3,4])
y = torch.tensor([1,2,3,4])
torch.dot(x,y)
//out
tensor(30)
用于矩阵*向量,意义也是对应元素相乘再相加
A_t = np.arange(10).reshape(5,2)
b_t = np.array([1,2])
A_t,b_t,np.dot(A_t,b_t)
//out
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
array([1, 2])
array([ 2, 8, 14, 20, 26])
3. 矩阵-向量积:torch.mv(A,x)
看做矩阵乘法,只不过一个元素必须是向量
A = torch.tensor([[1,2],[3,4]])
x = torch.tensor([1,2])
A,x,torch.mv(A,x)
//out
(tensor([[1, 2],
[3, 4]]),
tensor([1, 2]),
tensor([ 5, 11]))
4. 矩阵-矩阵积:torch.mm
矩阵乘法
A = torch.tensor([[1,2],[3,4]])
B = torch.tensor([[1,2],[3,4]])
A,B,torch.mm(A,B)
//out
(tensor([[1, 2],
[3, 4]]),
tensor([[1, 2],
[3, 4]]),
tensor([[ 7, 10],
[15, 22]]))
5. 用法多样的torch.matmul()函数
灵活利用了广播机制。
5.1 两个一维向量相乘
此时相当于点积torch.dot(x,y),对应元素相乘再求和。
import torch
x = torch.tensor([1,2])
y = torch.tensor([3,4])
torch.matmul(x,y)
//out
tensor(11)
5.2 两个二维矩阵相乘
此时相当于矩阵-矩阵积:torch.mm(x,y)
x = torch.tensor([[1,2],[3,4]])
y = torch.tensor([[5,6,7],[8,9,10]])
x,y,torch.matmul(x,y)
//out
(tensor([[1, 2],
[3, 4]]),
tensor([[ 5, 6, 7],
[ 8, 9, 10]]),
tensor([[21, 24, 27],
[47, 54, 61]]))
5.3 一维向量*二维矩阵
利用广播机制,看做矩阵*矩阵
x = torch.tensor([1,2])
y = torch.tensor([[5,6,7],[8,9,10]])
z = torch.matmul(x,y)
x,y,z
//out
(tensor([1, 2]),
tensor([[ 5, 6, 7],
[ 8, 9, 10]]),
tensor([21, 24, 27]))
注意维度的变化用了广播机制:
首先将x维度从(2)扩充为(1,2),然后将x(1,2) 与y(2,3)进行相乘,得到(1,3),最后去掉一维部分,得到(3)
x.size(),y.size(),z.size()
//out
(torch.Size([2]), torch.Size([2, 3]), torch.Size([3]))
5.4 二维矩阵*一维向量
利用广播机制,看做矩阵*矩阵
x = torch.tensor([[1,2,3],[4,5,6]])
y = torch.tensor([7,8,9])
z = torch.matmul(x,y)
x,y,z
(tensor([[1, 2, 3],
[4, 5, 6]]),
tensor([7, 8, 9]),
tensor([ 50, 122]))
注意维度的变化用了广播机制:
首先将y维度从(3)扩充为(3,1),然后将x(2,3) 与y(3,1)进行相乘,得到(2,1),最后去掉一维部分,得到(2)
x.size(),y.size(),z.size()
(torch.Size([2, 3]), torch.Size([3]), torch.Size([2]))
有待补充…
李沐动手深度学习
torch.matmul()函数用法总结