python中l(wèi)ist,ndarray,Tensor間的轉換小結
一、list,ndarray,Tensor間的轉化
廢話不多說,看表格就行
| 數(shù)據(jù)類型 | 所屬包 |
|---|---|
| list | python |
| ndarray | numpy |
| Tensor | pytorch |
| 轉化類型 | 對應API | 注意點 |
|---|---|---|
| list轉換為ndarray | numpy.array() | |
| ndarray轉換為list | ndarray對象.tolist() | |
| list轉換為Tensor | torch.tensor() | list中的int類型數(shù)據(jù)轉換后會變?yōu)閒olat,若需要保持int,則轉換時需要加上類型 |
| Tensor轉換為list | Tensor對象.tolist() | |
| ndarray轉換為Tensor | torch.from_numpy()torch.tensor() | |
| Tensor(CPU)轉換為ndarray | Tensor對象.numpy() | GPU上的Tensor不能直接轉換為numpy,需要間接轉換 |
| Tensor(GPU)轉換為ndarray | Tensor對象.cpu().numpy() | GPU上的Tensor不能直接轉換為numpy,需要間接轉換 |
ndarray --> PILimage
From PIL import Image y = Image.fromarray(array)
PILimage --> ndarray
From PIL import Image image = Image.open(“…..”) img = np.asarray(image)
Tensor --> ndarray
import numpy as np yy = np.array(tensor)
ndarray --> Tensor
tensor = torch.from_numpy(ndarray)
tip:返回的張量和ndarray共享同一內存。對張量的修改將反映在ndarray中,反之亦然。
ndarray數(shù)據(jù)轉換數(shù)據(jù)類型
array.astype(np.uint8)
將array復制,并將數(shù)據(jù)類型強制轉化為int8
ndarray --> List
import numpy as np n = np.array([[1,2],[3,4],[5,6]]) m = n.tolist()
List --> Tensor
tensor = torch.tensor(list)
二、例程
import numpy as np import torch #list轉換為ndarray li=[[1,2,3],[4,5,6],[7,8,9]] a=np.array(li) #list轉換為ndarray print(a) print(type(a),'\n') #ndarray轉換為list b=a.tolist()#ndarray轉換為list print(b) print(type(b),'\n') #list轉換為Tensor li=[[1,2,3],[4,5,6],[7,8,9]] c=torch.tensor(li) #list轉換為Tensor print(c) print(type(c),'\n') #Tensor轉換為list d=c.tolist() #Tensor轉換為list print(d) print(type(d),'\n') #ndarray轉換為Tensor nd=np.arange(0,12).reshape(3,4) e=torch.from_numpy(nd) #ndarray轉換為Tensor # e=torch.tensor(nd) #ndarray轉換為Tensor print(e) print(type(e),'\n') #Tensor轉換為ndarray f=e.numpy() print(f) print(type(f),'\n')
運行結果
[[1 2 3]
[4 5 6]
[7 8 9]]
<class 'numpy.ndarray'>[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
<class 'list'>tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
<class 'torch.Tensor'>[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
<class 'list'>tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]], dtype=torch.int32)
<class 'torch.Tensor'>[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
<class 'numpy.ndarray'>
到此這篇關于python中l(wèi)ist,ndarray,Tensor間的轉化小結的文章就介紹到這了,更多相關python list,ndarray,Tensor轉化內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python+PyQt5開發(fā)一個智能鍵盤模擬輸入器(附整體源碼)
在當今數(shù)字化辦公時代,自動化工具已經(jīng)成為提高工作效率的重要利器,今天我要向大家介紹一款基于PyQt5和pynput庫開發(fā)的智能鍵盤模擬輸入器,感興趣的小伙伴可以了解下2025-10-10
python實現(xiàn)一行輸入多個值和一行輸出多個值的例子
今天小編就為大家分享一篇python實現(xiàn)一行輸入多個值和一行輸出多個值的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
Django的URLconf中使用缺省視圖參數(shù)的方法
這篇文章主要介紹了Django的URLconf中使用缺省視圖參數(shù)的方法,Django是最著名的Python的web開發(fā)框架,需要的朋友可以參考下2015-07-07

