pytorch中tensor張量資料型別的轉化方式
阿新 • • 發佈:2020-01-09
1.tensor張量與numpy相互轉換
tensor ----->numpy import torch a=torch.ones([2,5]) tensor([[1.,1.,1.],[1.,1.]]) # ********************************** b=a.numpy() array([[1.,1.]],dtype=float32)
numpy ----->tensor import numpy as np a=np.ones([2,5]) array([[1.,1.]]) # ********************************** b=torch.from_numpy(a) tensor([[1.,dtype=torch.float64)
2.tensor張量與list相互轉換
tensor—>list a=torch.ones([1,1.]]) # *********************************** b=a.tolist() [[1.0,1.0,1.0]] list—>tensor a=list(range(1,6)) [1,2,3,4,5] # ********************************** b=torch.tensor(a) tensor([1,5])
3.tensor張量見型別轉換
構建一個新的張量,你要轉變成不同的型別只需要根據自己的需求選擇即可
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() 將張量轉換成指定型別張量
>>> 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,-2147483648],[-2147483648,-2147483648]],dtype=torch.int32) >>> a tensor([[1.9431e-19,1.8370e+25]])
以上這篇pytorch中tensor張量資料型別的轉化方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。