2017-12-18 90 views
0

我正在玩弄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),做工精細。所以問題只是我乘以一個矢量而不是一個矩陣---但我該怎麼做呢?

回答

1

您正在尋找

torch.mv(a,b) 

注意,對於未來,你也可能會發現torch.matmul()有用。 torch.matmul()推斷參數的維數,並相應地執行向量之間的點積,矩陣向量或向量矩陣乘法,矩陣乘法或批次矩陣乘法以獲得更高階張量。

+1

謝謝!爲了未來的訪問者,我寫了一些自我回答和一些補充信息。 – Nathaniel

1

這是一個自我回答@ mexmex的正確和有用的答案。

在PyTorch中,與numpy不同,1D張量與1xN或Nx1張量不可互換。如果我更換

>>> b = torch.rand(4) 

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

那麼我將有一個列向量,並預期與mm矩陣乘法會工作。

但是,這不是必要的,因爲如@mexmex指出有一個mv函數矩陣 - 向量乘法,以及一個matmul函數根據其輸入的尺寸,它能將適當的功能。