关于pytorch中部分矩阵乘法的总结(torch.mm,torch.mul,torch.matmul)

本文详细介绍了PyTorch中的三个矩阵乘法操作:torch.mul主要涉及元素级乘法,支持广播机制;torch.mm对应线性代数中的矩阵乘法;torch.matmul在torch.mm基础上增加广播机制,适用于不同形状的张量,包括一维和三维情况。
摘要由CSDN通过智能技术生成

一、torch.mul

该乘法可简单理解为矩阵各位相乘,一个常见的例子为向量点乘,源码定义为torch.mul(input,other,out=None)。其中other可以为一个数也可以为一个张量,other为数即张量的数乘。
该函数可触发广播机制(broadcast)。

tensor1 = 2*torch.ones(1,4)
tensor2 = 3*torch.ones(4,1)
print(torch.mul(tensor1, tensor2))
#输出结果为:
tensor([[6., 6., 6., 6.],
        [6., 6., 6., 6.],
        [6., 6., 6., 6.],
        [6., 6., 6., 6.]])

二、torch.mm

这是我们在线性代数课程中学习的矩阵乘法。该函数源码定义为torch.mm(input,mat2,out=None) ,参数与返回值均为tensor形式。

a=torch.ones(4,3)  
b=2*torch.ones(3,2)  
c=torch.empty(4,2)  
torch.mm(a,b,out=c)  
print(torch.mm(a,b))  
print( c )

#输出结果为
tensor([[6., 6.],
        [6., 6.],
        [6., 6.],
        [6., 6.]])
tensor([[6., 6.],
        [6., 6.],
        [6., 6.],
        [6., 6.]])

三、torch.matm

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值