如何在 PyTorch 中将矩阵乘以向量

How to multiply a matrix by a vector in PyTorch

我正在玩 PyTorch,目的是学习它,但我有一个非常愚蠢的问题:如何将矩阵乘以单个向量?

这是我尝试过的方法:

>>> import torch
>>> a = torch.rand(4,4)
>>> a

 0.3162  0.4434  0.9318  0.8752
 0.0129  0.8609  0.6402  0.2396
 0.5720  0.7262  0.7443  0.0425
 0.4561  0.1725  0.4390  0.8770
[torch.FloatTensor of size 4x4]

>>> b = torch.rand(4)
>>> b

 0.1813
 0.7090
 0.0329
 0.7591
[torch.FloatTensor of size 4]

>>> a.mm(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: invalid argument 2: dimension 1 out of range of 1D tensor at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensor.c:24
>>> a.mm(b.t())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: t() expects a 2D tensor, but self is 1D
>>> b.mm(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: matrices expected, got 1D, 2D tensors at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensorMath.c:1288
>>> b.t().mm(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: t() expects a 2D tensor, but self is 1D

另一方面,如果我这样做

>>> b = torch.rand(4,2)

那么我的第一次尝试 a.mm(b) 工作正常。所以问题只是我乘以向量而不是矩阵 --- 但我该怎么做呢?

您正在寻找

torch.mv(a,b)

请注意,您将来可能还会发现 torch.matmul() 有用。 torch.matmul() 推断您的参数的维数,并相应地执行向量之间的点积、矩阵-向量或向量-矩阵乘法、矩阵乘法或高阶张量的批量矩阵乘法。

这是一个自我回答,以补充@mexmex 的正确和有用的答案。

在 PyTorch 中,与 numpy 不同,一维张量不能与 1xN 或 Nx1 张量互换。如果我更换

>>> b = torch.rand(4)

>>> b = torch.rand((4,1))

然后我将有一个列向量,矩阵乘法与 mm 将按预期工作。

但这不是必需的,因为正如@mexmex 指出的那样,有一个用于矩阵向量乘法的 mv 函数,以及一个 matmul 函数,它根据输入的维度。