x,y均为Tensor
plt.plot(x, y)
报错:

‘Tensor‘ object has no attribute ‘ndim‘

原因:
plt.plot()函数期望其输入为numpy数组,而不是torch.tensor
需要用.numpy()将Tensor转化为numpy类型

plt.plot(x.numpy(), y.numpy())
再次报错:

TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

原因:
numpy只能在CPU里操作
Tensor能在CPU和GPU里操作
而这里的Tensor此时在GPU里,在转化为numpy类型之前,需要把Tensor转入CPU里。

plt.plot(x.cpu().numpy(), y.cpu().numpy())

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐