Pytorch、Python中的矩阵乘法

1、线代中的矩阵乘法(叉乘)

np.dot、torch.mm用法一样,但是torch对应的是tensor

# 生成3行4列的矩阵a和4行8列的矩阵b
a = np.random.rand(3,4)
b = np.random.rand(4,8)
c = a @ b
d = np.dot(a,b)
print("c: " , c.shape) # [3, 8]
print("d: " , d.shape) # [3, 8]


a = torch.rand(3,4)
b = torch.rand(4,8)
c = torch.mm(a,b)
c.shape  # [3, 8]
d = a @ b 
d.shape  # [3, 8]

2、对应元素相乘(点乘)

np.multiply、torch.mul

a = np.array([[1,2],[3,4]])
b = np.array([[6,7],[8,9]])
c = a * b 
d = np.multiply(a,b)
print(c)
# [[ 6 14]
#  [24 36]]
print(d)
# [[ 6 14]
#  [24 36]]


a = torch.Tensor([[1,2],[3,4]])
b = torch.Tensor([[6,7],[8,9]])
c = a * b 
d = torch.mul(a,b)
d
# tensor([[ 6., 14.],
#         [24., 36.]])

3、torch.matmul()

和线代中的矩阵乘法一样

a = torch.rand(3,4)
b = torch.rand(4,8)
c = torch.matmul(a,b)
c.shape  # [3, 8]

当高纬度时,对后两维进行叉乘

 4、torch.einsum

a = torch.rand(10,3,4)
b = torch.rand(10,4,8)
c = torch.einsum('ijk,ikp->ijp' , a , b)

# 下面对c[0][0][0]进行验证
ra = a[0,0,:].view(-1,4)
rb = b[0,:,0].view(4,-1)
rs = ra @ rb
rs == c[0][0][0]

# tensor([[True]])

        a的维度命名为 ijk , b的维度命名为 ikp ,输出的维度为 ijp 。a中与ikp相同的字母有ij,同理,b中有ip。所以将a中所有的a(ij*)与b中所有的b(i*p)相乘累加得到c(ijp),公式如下:

 

  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值