[英]Pytorch runtimeError "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>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.