绘制预测值会导致错误:“张量”对象没有属性“ ndim”

时间:2019-08-18 01:44:19

标签: python numpy matplotlib pytorch

如何正确编写代码以绘制此线性回归模型中的预测值?

我正在使用本教程来学习线性回归:https://www.deeplearningwizard.com/deep_learning/practical_pytorch/pytorch_linear_regression/

我能够成功实现GPU。我的问题是绘制预测值。我尝试寻找解决方案以学习如何将值保持为张量,但似乎我没有语法知识来做到这一点。

这是我要开始的地方

epochs = 100
for epoch in range(epochs):
    epoch += 1

    # Convert numpy array to torch Variable
    if torch.cuda.is_available():
        inputs = (torch.from_numpy(x_train).cuda())
        labels = (torch.from_numpy(y_train).cuda())
    else:
        inputs = (torch.from_numpy(x_train))
        labels = (torch.from_numpy(y_train))

    # Clear gradients w.r.t. parameters
    optimizer.zero_grad()

    # Forward to get output
    outputs = model(inputs)

    # Calculate Loss
    loss = criterion(outputs, labels)

    # Getting gradients w.r.t. parameters
    loss.backward()

    # Updating parameters
    optimizer.step()

    # Logging
    print('epoch {}, loss {}'.format(epoch, loss.item()))

在这里进行预测,我选择使用cuda

predicted = model(Variable(torch.from_numpy(x_train).requires_grad_().cuda()))

print("Predicted")
print(predicted)
print("Output")
print(y_train)

plt.clf()

# Get predictions

#predicted = model(Variable(torch.from_numpy(x_train).requires_grad_().cuda()))

# Plot true data
plt.plot(x_train, y_train, 'go', label='True data', alpha=0.5)

无法绘制后在这里调用错误

# Plot predictions
plt.plot(x_train, predicted, '--', label='Predictions', alpha=0.5)

# Legend and plot
plt.legend(loc='best')
plt.show()

给出错误:

Traceback (most recent call last):
  File "D:/Test with GPU/Linear regression.py", line 101, in <module>
    plt.plot(x_train, predicted, '--', label='Predictions', alpha=0.5)
  File "D:\Anaconda3\envs\gputest\lib\site-packages\matplotlib\pyplot.py", line 2795, in plot
    is not None else {}), **kwargs)
  File "D:\Anaconda3\envs\gputest\lib\site-packages\matplotlib\axes\_axes.py", line 1666, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]
  File "D:\Anaconda3\envs\gputest\lib\site-packages\matplotlib\axes\_base.py", line 225, in __call__
    yield from self._plot_args(this, kwargs)
  File "D:\Anaconda3\envs\gputest\lib\site-packages\matplotlib\axes\_base.py", line 391, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File "D:\Anaconda3\envs\gputest\lib\site-packages\matplotlib\axes\_base.py", line 271, in _xy_from_xy
    if x.ndim > 2 or y.ndim > 2:
AttributeError: 'Tensor' object has no attribute 'ndim'

2 个答案:

答案 0 :(得分:2)

plt.plot函数期望其输入为numpy数组,而不是torch.tensor
您可以使用.numpy()numpy数组的形式查看张量的内部数据。

尝试

with torch.no_grad():
  plt.plot(x_train, predicted.cpu().numpy(), '--', label='Predictions', alpha=0.5)

答案 1 :(得分:1)

Ndim是matplotlib所需的属性。

import matplotlib.pyplot as plt   
torch.Tensor.ndim = property(lambda x: len(x.size()))
N = 42
t = torch.rand(N)
plt.plot(t)
plt.show()
plt.close()

但是我认为PyTorch直到1.2版才具备张量。

您可以添加这部分torch.Tensor.ndim = property(lambda x: len(x.size())),并且可以绘制PyTorch张量而不会出现问题。

enter image description here