数据处理中几种矩阵乘法
笔者在矩阵相关的数据处理中对矩阵乘法产生了一些困惑,在以往粗浅的认知中只有两种常用的乘法,但在学习“机器学习”的过程中对一些函数或名词的处理结果产生了疑惑,遂记录一下学习笔记。以下是5种乘法:哈达玛乘积、标准矩阵乘法、外积、张量积、卷积。此外,向量中的乘法也与矩阵乘法有些不同,以下2种:点积、叉积。
·
笔者在矩阵相关的数据处理中对矩阵乘法产生了一些困惑,在以往粗浅的认知中只有两种常用的乘法,但在学习“机器学习”的过程中对一些函数或名词的处理结果产生了疑惑,遂记录一下学习笔记。以下是5种乘法:哈达玛乘积、标准矩阵乘法、外积、张量积、卷积。
1、哈达玛乘积又称元素积 Element-wise (Hadamard) Product
元素对应相乘。
# 1、Element-wise (Hadamatorch. Tensor#x 1x4
x = torch.arange(4, dtype=torch.float32)
y = torch.tentorch. Tensor,[1,2,3]]) #y 2x3
y * y
tensor([[1, 4, 9],
[1, 4, 9]])
2、标准矩阵乘法
元素行列相乘,维度不变。
# 2、std-matrix multiplication
z = torch.tensor([[1,2],[1,2],[1,2]]) #z 3x2
torch.matmul(y, z), y @ z, torch.mm(y,z)
(tensor([[ 6, 12],
[ 6, 12]]),
tensor([[ 6, 12],
[ 6, 12]]),
tensor([[ 6, 12],
[ 6, 12]]))
3、外积 Outer Product
外积通常是向量生成矩阵的方法,m维列向量 n维行向量相乘为m x n的矩阵,严格来说是属于张量积的一种。
# 3、outer product
'''外积的计算方式其实是张量积的一种,前者以向量为主,后者包含在内'''
print(x.reshape(4,1) * x)
print(torch.outer(x,x))
print(torch.ger(x,x)) # 3
tensor([[0., 0., 0., 0.],
[0., 1., 2., 3.],
[0., 2., 4., 6.],
[0., 3., 6., 9.]])
tensor([[0., 0., 0., 0.],
[0., 1., 2., 3.],
[0., 2., 4., 6.],
[0., 3., 6., 9.]])
tensor([[0., 0., 0., 0.],
[0., 1., 2., 3.],
[0., 2., 4., 6.],
[0., 3., 6., 9.]])
4、张量积 Kronecker Product
将左边的矩阵每一个元素乘上后一个矩阵形成一个更大的元素。
4、Kronecker Product
m = torch.tensor([[1,2],[1,3]])
n = torch.tensor([1,2])
o = torch.tensor([[1,2],[1,2]])
print(torch.einsum('ij,k->ijk', m,n))
print(torch.einsum('ij,kl->ijkl', m,o))
print(torch.einsum('ij,kl->ijkl', z,o))
tensor([[[1, 2],
[2, 4]],
[[1, 2],
[3, 6]]])
tensor([[[[1, 2],
[1, 2]],
[[2, 4],
[2, 4]]],
[[[1, 2],
[1, 2]],
[[3, 6],
[3, 6]]]])
tensor([[[[1, 2],
[1, 2]],
[[2, 4],
[2, 4]]],
[[[1, 2],
[1, 2]],
[[2, 4],
[2, 4]]],
[[[1, 2],
[1, 2]],
[[2, 4],
[2, 4]]]])
5、卷积 Convolution
使用卷积核,滑动矩阵求和,维度降低。
import torch.nn.functional as F
x = torch.tensor([[[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]]], dtype=torch.float32)
w = torch.tensor([[[[0, 1],
[2, 3]]]], dtype=torch.float32)
b = torch.zeros(1) # 偏置为零
output = F.conv2d(x, w, b) #卷积核算的是元素积的和
print(output)
tensor([[[[30., 36., 42.],
[54., 60., 66.],
[78., 84., 90.]]]])
拓展一、向量点积
# 同标准矩阵乘法
拓展二、向量叉积
# 同外积
补充概念
矢量(向量):矢既有大小又有方向的量。
张量:一个更广义的概念。如:标量是零阶张量,矢量是一阶张量。

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)