【问题标题】:Pytorch runtimeError "matrices expected, got 1D, 2D tensors at"Pytorch runtimeError“预期矩阵,得到一维,二维张量”
【发布时间】:2020-05-23 05:11:29
【问题描述】:

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

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

【问题讨论】:

标签: python pytorch runtime-error


【解决方案1】:

尝试reshape,您需要将s 的形状更改为(1,2) 以使matrix multiplication 操作与(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>)

【讨论】:

    【解决方案2】:

    左右:

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

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    猜你喜欢
    • 2020-09-26
    • 2019-09-15
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    相关资源
    最近更新 更多