Pytorch runtimeError“预期矩阵,在处获得1D、2D张量”

2024-04-16 05:40:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始练习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*

我怎样才能解决这个问题 谢谢你的答复


Tags: fromimportnumpytruenptorchvariablenum
2条回答

大约:

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

尝试^{}您需要将s的形状更改为(1,2),以便能够使用(2,2)张量进行matrix multiplication运算

>>> 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>)

相关问题 更多 >