Pytorch--Tensor, Numpy--Array,Python--List 相互之间的转换。
2019-08-13 17:02
4717 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_37589575/article/details/99446394
1.1 List --> Arrary: np.array(List 变量)
a = [1, 2, 3, 4] b = np.array(a)
1.2 Arrary --> List: Array 变量.tolist()
a = [1, 2, 3, 4] b = np.array(a)c = b.tolist()
2.1 List --> Tensor: torch.Tensor(List 变量)
a = [1, 2, 3, 4] b = torch.Tensor(a)
2.2 Tensor --> List: Tensor 变量.numpy().tolist()
a = [1, 2, 3, 4] b = torch.Tensor(a)c = b.numpy().tolist()
这里 c 和 a 的差异在于 List 转为 Tensor 的时候默认 Tensor 中的数据为 float 类型,所以转回来的时候会变为浮点数。
3.1 Array --> Tensor: torch.from_numpy(Array 变量)
a = [1, 2, 3, 4] b = np.array(a)c = torch.from_numpy(b)
3.2 Tensor --> Array: torch.numpy(Tensor 变量)
a = [1, 2, 3, 4] b = np.array(a)c = torch.from_numpy(b) d = c.numpy()
如果需要转换 GPU 上的张量 Tensor,需要将其转换到 CPU 上,例如 GPU 上的 Tensor :
a = [1, 2, 3, 4] b = np.array(a)c = torch.from_numpy(b).cuda() d = c.numpy()
会报错: TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
这时应该使用
d = c.cpu().numpy()
先放回 CPU 在进行转换。
相关文章推荐
- numpy的array和python中自带的list之间相互转化
- Python中的list与NumPy中array的区别 及相互转换
- 图像处理之PIL.Image与numpy.array之间的相互转换 (Python-OpenCV)
- numpy的array和python中自带的list之间相互转化
- 对numpy的array和python中自带的list之间相互转化详解
- 用list去初始化numpy的array数组 numpy的array和python中自带的list之间相互转化
- python内置array模块,与numpy中的array和list之间的转换
- python中的list以及list与array相互转换
- python3 list、tuple(元组)、str之间的相互转换
- numpy、pandas包List, Dict, Array, Series, DataFrame 相互转换
- 莫烦pytorch学习01:pytorch与numpy之间的转换
- List,Set,Map,Array之间相互转换
- python 中list(列表),tupe(元组),str(字符串),dict(字典)之间的相互转换
- Python中list、tuple、str和dict之间的相互转换
- python list 与 array 相互转换
- Python中列表list以及list与数组array的相互转换实现方法
- Python——array与list相互转换
- python中的list以及list与array相互转换
- list array相互之间转换(算法题常用到)
- numpy.array和python中list的相互转化