pytorch中tensor張量數(shù)據(jù)類型的轉(zhuǎn)化方式
1.tensor張量與numpy相互轉(zhuǎn)換
tensor ----->numpy import torch a=torch.ones([2,5]) tensor([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]]) # ********************************** b=a.numpy() array([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]], dtype=float32)
numpy ----->tensor import numpy as np a=np.ones([2,5]) array([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]]) # ********************************** b=torch.from_numpy(a) tensor([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]], dtype=torch.float64)
2.tensor張量與list相互轉(zhuǎn)換
tensor—>list a=torch.ones([1,5]) tensor([[1., 1., 1., 1., 1.]]) # *********************************** b=a.tolist() [[1.0, 1.0, 1.0, 1.0, 1.0]] list—>tensor a=list(range(1,6)) [1, 2, 3, 4, 5] # ********************************** b=torch.tensor(a) tensor([1, 2, 3, 4, 5])
3.tensor張量見類型轉(zhuǎn)換
構(gòu)建一個新的張量,你要轉(zhuǎn)變成不同的類型只需要根據(jù)自己的需求選擇即可
tensor = torch.Tensor(3, 5) # torch.long() 將tensor投射為long類型 newtensor = tensor.long() # torch.half()將tensor投射為半精度浮點類型 newtensor = tensor.half() # torch.int()將該tensor投射為int類型 newtensor = tensor.int() # torch.double()將該tensor投射為double類型 newtensor = tensor.double() # torch.float()將該tensor投射為float類型 newtensor = tensor.float() # torch.char()將該tensor投射為char類型 newtensor = tensor.char() # torch.byte()將該tensor投射為byte類型 newtensor = tensor.byte() # torch.short()將該tensor投射為short類型 newtensor = tensor.short()
4.type_as() 將張量轉(zhuǎn)換成指定類型張量
>>> a=torch.Tensor(2,5) >>> a tensor([[1.9431e-19, 4.8613e+30, 1.4603e-19, 2.0704e-19, 4.7429e+30], [1.6530e+19, 1.8254e+31, 1.4607e-19, 6.8801e+16, 1.8370e+25]]) >>> b=torch.IntTensor(1,2) >>> b tensor([[16843009, 1]], dtype=torch.int32) >>> a.type_as(b) tensor([[ 0, -2147483648, 0, 0, -2147483648], [-2147483648, -2147483648, 0, -2147483648, -2147483648]], dtype=torch.int32) >>> a tensor([[1.9431e-19, 4.8613e+30, 1.4603e-19, 2.0704e-19, 4.7429e+30], [1.6530e+19, 1.8254e+31, 1.4607e-19, 6.8801e+16, 1.8370e+25]])
以上這篇pytorch中tensor張量數(shù)據(jù)類型的轉(zhuǎn)化方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
json-server?如何快速搭建REST?API?服務(wù)器
json-server 是一個非常流行的開源工具,用于快速搭建一個完整的 REST API 服務(wù)器,它使用 JSON 文件作為數(shù)據(jù)源,通過簡單的配置即可模擬復(fù)雜的服務(wù)器功能,這篇文章主要介紹了json-server如何快速搭建REST API服務(wù)器,需要的朋友可以參考下2017-10-10Python tkinter分隔控件(Seperator)的使用
這篇文章主要介紹了Python tkinter分隔控件(Seperator)的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04python實現(xiàn)用類讀取文件數(shù)據(jù)并計算矩形面積
今天小編就為大家分享一篇python實現(xiàn)用類讀取文件數(shù)據(jù)并計算矩形面積,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01python學(xué)習(xí)之基于Python的人臉識別技術(shù)學(xué)習(xí)
面部識別技術(shù)的應(yīng)用越來越廣泛,它廣泛應(yīng)用于安全系統(tǒng)、人機交互、社交媒體、醫(yī)療保健等領(lǐng)域。本文介紹了基于Python的人臉識別技術(shù),感興趣的小伙伴可以參考閱讀2023-03-03python Web開發(fā)你要理解的WSGI & uwsgi詳解
這篇文章主要給大家介紹了關(guān)于python Web開發(fā)你一定要理解的WSGI & uwsgi的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08