日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

list python 转tensor_Pytorch--Tensor, Numpy--Array,Python--List 相互之间的转换。

發布時間:2023/12/10 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 list python 转tensor_Pytorch--Tensor, Numpy--Array,Python--List 相互之间的转换。 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

版權聲明:本文為博主原創文章,遵循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 在進行轉換。

總結

以上是生活随笔為你收集整理的list python 转tensor_Pytorch--Tensor, Numpy--Array,Python--List 相互之间的转换。的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。