您的位置:首页 > 编程语言 > Python开发

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 在进行转换。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: