Pytorch資料型別轉換

2021-10-23 14:08:30 字數 2157 閱讀 7508

**:

pytorch的型別可以分為cpu和gpu上的tensor, 它們擁有的資料型別是基本上是一樣的:

tensor.floattensor

tensor.longtensor

tensor.bytetensor

tensor.chartensor

tensor.shorttensor

tensor.inttensor

torch.longtensor

其中torch.tensor是預設的tensor.floattensor的簡稱。

tensor = torch.tensor(3, 5)

torch.long() 將tensor投射為long型別:

newtensor = torch.long()

torch.int()將該tensor投射為int型別:

newtensor = torch.int()

torch.double()將該tensor投射為double型別:

newtensor = torch.double()

一般,只要在tensor後加long(), int(), double(), float(), byte()等函式就能將tensor的型別進行轉換

除此之外,可以使用type()函式,data為tensor資料型別,data.type()給出data的型別,如果使用data.type(torch.floattensor)則強制轉換為torch.floattensor型別的張量, 如果不知道什麼型別,可以使用tensor_1.type_as(tensor_2), 將tensor_1轉換成tensor_2。

self = torch.

longtensor(

3, 5)

# 轉換為其他型別

print self.

type(torch.floattensor)

如果沒有特別說明:tensor是cpu上的變數

使用gpu張量:tensor.cuda()

使用cpu張量:tensor.cpu()

variable轉換成普通的tensor:variable.data()

tesnor轉換成numpy array的格式:tensor.numpy()

numpy資料轉換成tensor:torch.from_numpy(np_data)

tensor轉換成variable:variable(tensor)

pytorch資料類似pytorch中的tensor, 更重要的是tensor可以使用gpu來加速,並且變成variable可以實現自動求導的功能variable是對tensor物件的封裝。

邏輯值truefalse轉成0和1.+0

print

(y)print

(y+0

)

輸出結果

tensor(

[true

,false

,false

,true

,true

,false

,false

,true

,true

,false])

tensor([1

,0,0

,1,1

,0,0

,1,1

,0])

pytorch 資料型別

torch 定義了九種cpu tensor型別和九種gpu tensor型別 data type dtype cpu tensor gpu tensor 32位浮點型 torch.float32或torch.float torch.floattensor torch.cuda.floattensor...

資料型別 型別轉換

這樣的語句將報錯,因為char型別精度低於int型別,編譯器無法將其自動轉換,只能進行強制轉換 int x 65 char ch char x 舉例1 int age 19 char 女 char result age int 不可以自動轉換成char 精度損失 舉例2 int a 10 int b...

Objective C資料型別 資料型別轉換

資料型別 1.objective c資料型別可以分為 基本資料型別 物件資料型別和id型別。2.基本資料型別有 int float double和char型別。3.物件型別就是類或協議所宣告的指標型別,例如 nsautoreleasepool pool 其中,nsautoreleasepool是乙個...