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

问题描述 投票:5回答:2

我正在玩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),工作正常。所以问题只是我将一个向量而不是一个矩阵相乘---但我怎么能这样做呢?

pytorch
2个回答
16
投票

您正在寻找

torch.mv(a,b)

请注意,对于未来,您可能还会发现torch.matmul()很有用。 torch.matmul()推断出你的论证的维度,因此在向量,矩阵向量或向量矩阵乘法,矩阵乘法或批量矩阵乘法之间执行高阶张量的点积。


4
投票

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

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

>>> b = torch.rand(4)

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

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

但这不是必需的,因为@mexmex指出有矩阵向量乘法的mv函数,以及根据其输入的维度调度适当函数的matmul函数。

© www.soinside.com 2019 - 2024. All rights reserved.