在GPU环境下使用pytorch出现:can’t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
原代码
import matplotlib.pyplot as plt
# 折线图
plt.plot(x, y, label='sin')
plt.plot(x, a + b*x + c*x**2+ d*x**3, label='me')
# 图例
plt.legend()
# 画图
plt.show()
出现这个问题,只需要在变量后加上.cpu().numpy()
即可。
修改后的代码:
import matplotlib.pyplot as plt
# 折线图
plt.plot(x.cpu().numpy(), y.cpu().numpy(), label='sin')
plt.plot(x.cpu().numpy(), (a + b*x + c*x**2 + d*x**3).cpu().numpy(), label='me')
# 图例
plt.legend()
# 画图
plt.show()
成功解决