pytorch中的tensor以numpy形式进行输出保存

pytorch中的tensor以numpy形式进行输出保存


因为tensor和numpy不是一种数据类型,所以,在将数据输出保存之前,需要将tensor的数据类型进行转换,否则会报一下的错误

TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

以下先贴一版没修改之前的代码,也就是会报error的。

# a是我需要保存的数据,其数据类型为tensor,但是还没有转换为numpy格式。
numpy.save("output.npy",a)

修改后的:

b = a.data.cpu().numpy() # 数据类型转换
numpy.save("output.npy",b) # 大功告成

说一下我的思考,看到error后,我首先去看了一下a的数据类型格式,确实不是numpy类型,而是tensor类型。

pytorch中的tensor以numpy形式进行输出保存_第1张图片

在我转换完成后,可以看见数据的类型是array。

pytorch中的tensor以numpy形式进行输出保存_第2张图片

你可能感兴趣的:(python,python)