gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:57:35 25 4
gpt4 key购买 nike

我正在玩 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() 推断参数的维数,并相应地执行向量之间的点积、矩阵向量或向量矩阵乘法、矩阵乘法或高阶张量的批量矩阵乘法。

关于pytorch - 如何在 PyTorch 中将矩阵乘以向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47870003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com