Pytorch 运行时错误"matrices expected, got 1D, 2D tensors at"



我开始练习Pytorch,尝试使用 torch.mm((方法。

下面是我的代码

import torch 
import numpy as np
from torch.autograd import Variable
num_x = np.array([[1.0, 2.0]
,[3.0,4.0]])
tensor_x = torch.from_numpy(num_x)
x = Variable(tensor_x,requires_grad = True)
s = Variable(torch.DoubleTensor([0.01,0.02]),requires_grad = True)
print(s)
s = s.mm(x)
print(s)

不幸的是,存在运行时错误

*RuntimeError                              Traceback (most recent call last)
<ipython-input-58-e8a58ffb2545> in <module>()
9 s = Variable(torch.DoubleTensor([0.01,0.02]),requires_grad = True)
10 print(s)
---> 11 s = s.mm(x)
12 print(s)
RuntimeError: matrices expected, got 1D, 2D tensors at /pytorch/aten/src/TH/generic/THTensorMath.cpp:131*

我该如何解决这个问题。 感谢您的回复

尝试reshape您需要将s的形状更改为(1,2),以使使用(2,2)张量的矩阵乘法运算成为可能

>>> s.reshape(1,2).mm(x)
tensor([[0.0700, 0.1000]], dtype=torch.float64, grad_fn=<MmBackward>)

或者在初始化s时给出正确的形状

>>> s = Variable(torch.DoubleTensor([[0.01,0.02]]),requires_grad = True)
>>> s.mm(x)
tensor([[0.0700, 0.1000]], dtype=torch.float64, grad_fn=<MmBackward>)

左右:

>>> s @ x
tensor([0.0700, 0.1000], dtype=torch.float64, grad_fn=<SqueezeBackward3>)

最新更新