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(

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

3376

被折叠的 条评论
为什么被折叠?



