自学内容网 自学内容网

PyTorch中的常见乘法运算(*、@、Mul、Matmul)

哈达玛积:torch.mul()、torch.dot()、*

两个相同尺寸的张量相乘,然后对应元素的相乘就是哈达玛积,这种乘法要求参与运算的矩阵唯独相同,运算结果还是一个相同维度的矩阵。在这个运算中,torch.mul()和*以及torch.dot()的作用是等价的:

a = torch.tensor([1,2])
b = torch.tensor([2,3])
print(a*b)
print(torch.mul(a,b))
>>> tensor([2, 6])
>>> tensor([2, 6])

这与除法的运算规则相同,torch中的torch.div()其实就是/, 类似的:torch.add就是+,torch.sub()就是-,不过符号的运算更简单常用:

a = torch.tensor([1.,2.])
b = torch.tensor([2.,3.])
print(a/b)
print(torch.div(a/b))
>>> tensor([0.5000, 0.6667])
>>> tensor([0.5000, 0.6667])

矩阵乘法:torch.mm()、torch.matmul()、@

如果参与运算的是一个多维张量,那么最好torch.matmul(),由于广播机制的原因,在多维张量中,参与矩阵运算的其实只有后两个维度,前面的维度则被认为是batch:

a = torch.tensor([1.,2.])
b = torch.tensor([2.,3.]).view(1,2)
print(torch.mm(a, b))
print(torch.matmul(a, b))
print(a @ b)

tensor([[2., 3.],
        [4., 6.]])
tensor([[2., 3.],
        [4., 6.]])
tensor([[2., 3.],
        [4., 6.]])

原文地址:https://blog.csdn.net/zly_Always_be/article/details/138008967

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!