torch 的 3种矩阵乘法运算

本文详细探讨了PyTorch中torch.tensor的element-wise乘法、矩阵乘法torch.mm与torch.matmul的区别,涉及广播机制、不同维度的乘法示例,以及批矩阵乘法、向量点乘等。重点展示了操作符*、mm和matmul的用法及常见错误案例。

torch.tensor * torch.tensor

当操作符是最最最自然的 *. 时,执行的时 element-wise 乘法,操作数会 broadcast。
更多细节请见Tensor unsqueeze 以 broadcast

torch.mm(就是执行矩阵乘法,1维不能作参数)

就是执行矩阵乘法
torch.mm(input, mat2, *, out=None) → Tensor
Performs a matrix multiplication of the matrices input and mat2.
If input is a (n × \times × m) tensor, mat2 is a (m × \times × p) tensor, out will be a (n × \times × p)tensor.

例1: [3,3] [3,3]

import torch
Mat1 = torch.tensor([[1, 6, 7],
                      [2, 5, 8],
                      [3, 4, 9]])
Mat2 = torch.tensor([[9, 6, 3],
                      [8, 5, 2],
                      [7, 4, 1]])

Mat3 = torch.mm(Mat1, Mat2, out=None)
print(Mat3)

输出

tensor([[106,  64,  22],
        [114,  69,  24],
        [122,  74,  26]])

例2 [1,2] [2,3]

import torch
Mat1 = torch.tensor([[1, 3]])
print("Mat1's shape: ",Mat1.shape)
Mat2 = torch.tensor([[6, 4, 2],
                      [5, 3, 1]])
print("Mat2's shape: ",Mat2.shape)
Mat3 = torch.mm(Mat1, Mat2, out=None)
print(Mat3)

输出:

Mat1's shape:  torch.Size([1, 2])
Mat2's shape:  torch.Size([2, 3])
tensor(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

培之

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值