1.數據類型簡介
Numpy
NumPy 支持比 Python 更多種類的數值類型。 下表顯示了 NumPy 中定義的不同標量數據類型。

Pytorch
Torch定義了七種CPU張量類型和八種GPU張量類型,這里我們就只講解一下CPU中的,其實GPU中只是中間加一個cuda即可,如torch.cuda.FloatTensor:
- torch.FloatTensor(2,3) 構建一個2*3 Float類型的張量
- torch.DoubleTensor(2,3) 構建一個2*3 Double類型的張量
- torch.ByteTensor(2,3) 構建一個2*3 Byte類型的張量
- torch.CharTensor(2,3) 構建一個2*3 Char類型的張量
- torch.ShortTensor(2,3) 構建一個2*3 Short類型的張量
- torch.IntTensor(2,3) 構建一個2*3 Int類型的張量
- torch.LongTensor(2,3) 構建一個2*3 Long類型的張量
同樣,直接使用類型名很可能會報錯,正確的使用方式是torch.調用,eg,torch.FloatTensor()
2.Python的type()函數
type函數可以由變量調用,或者把變量作為參數傳入。
返回的是該變量的類型,而非數據類型。
data = np.random.randint(0, 255, 300) print(type(data)) # <class 'numpy.ndarray'>
3.Numpy/Pytorch的dtype屬性
返回值為變量的數據類型
t_out = torch.Tensor(1,2,3) print(t_out.dtype) # torch.float32 t_out = torch.Tensor(1,2,3) print(t_out.numpy().dtype) # float32
4.Numpy中的類型轉換
n_out = n_out.astype(np.uint8) # 由變量調用,但是直接調用不會改變原變量的數據類型,是返回值是改變類型后的新變量,所以要賦值回去。
#初始化隨機數種子 np.random.seed(0) data = np.random.randint(0, 255, 300) print(data.dtype) n_out = data.reshape(10,10,3) #強制類型轉換 n_out = n_out.astype(np.uint8) print(n_out.dtype) img = transforms.ToPILImage()(n_out) img.show()
Pytorch中的類型轉換
pytorch中沒有astype函數,正確的轉換方法是
1.變量直接調用類型
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() # 同樣,和numpy中的astype函數一樣,是返回值才是改變類型后的結果,調用的變量類型不變
2.變量直接調用pytorch中的type函數
type(new_type=None, async=False)如果未提供new_type,則返回類型,否則將此對象轉換為指定的類型。 如果已經是正確的類型,則不會執行且返回原對象。
用法如下:
t = torch.LongTensor(3, 5)
t = t.type(torch.FloatTensor)
3.變量調用pytorch中的type_as函數
如果張量已經是正確的類型,則不會執行操作。具體操作方法如下:
t = torch.Tensor(3,5) tensor = torch.IntTensor(2, 3) t = t.type_as(tensor)
——————————
版權聲明:本文為CSDN博主「嘖嘖嘖biubiu」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_37385726/article/details/81774150
