list python 转tensor_Pytorch--Tensor, Numpy--Array,Python--List 相互之间的转换。
版權聲明:本文為博主原創(chuàng)文章,遵循CC 4.0 by-sa版權協(xié)議,轉載請附上原文出處鏈接和本聲明。
本文鏈接: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 中的數(shù)據(jù)為 float 類型,所以轉回來的時候會變?yōu)楦↑c數(shù)。
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 在進行轉換。
總結
以上是生活随笔為你收集整理的list python 转tensor_Pytorch--Tensor, Numpy--Array,Python--List 相互之间的转换。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 西门子S7-200PLC基本入门编程
- 下一篇: mysql查询字段为null的方法