Plotting predicted values causes error: 'Tensor' object has no attribute 'ndim'
How do I properly write the code to plot the predicted values in this linear regression model?

I am using this tutorial to learn Linear regression:https://www.deeplearningwizard.com/deep_learning/practical_pytorch/pytorch_linear_regression/

I was able to successfully implement GPU. My issue is plotting the predicted values. I tried searching for solutions to learn how to keep the values as a tensor, but it seems that I don't have the syntactical knowledge to do this.

Here is where I'll start

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


Prediction is made here and I choose to use 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)


The error is called here after it is unable to plot

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

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


Error Given:

Traceback (most recent call last):
  File "D:/Test with GPU/Linear regression.py", line 101, in &lt;module&gt;
    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 &gt; 2 or y.ndim &gt; 2:
AttributeError: 'Tensor' object has no attribute 'ndim'


plt.plot function expects its inputs to be numpy arrays, rather than torch.tensor.
You can use .numpy() to view the internal data of the tensor as a numpy array.

Try

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

