pytorch中tensor張量數(shù)據(jù)類型的轉(zhuǎn)化方式
更新時間:2019年12月31日 10:21:32 作者:|晴天|
今天小編就為大家分享一篇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)文章
Python?xlrd實現(xiàn)從讀取Excel到高效數(shù)據(jù)提取的全面指南
xlrd?是一個專門用于讀取?Excel?文件內(nèi)容的?Python?庫,它支持從?Excel?工作簿中提取工作表(Sheet),單元格內(nèi)容,數(shù)據(jù)類型等信息,下面小編就為大家詳細介紹一下它的具體使用吧2025-10-10
Python集成開發(fā)環(huán)境Pycharm的使用及技巧
本文詳細講解了Python集成開發(fā)環(huán)境Pycharm的使用及技巧,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06

