PyTorch的資料型別與建立

2021-10-22 18:24:44 字數 2985 閱讀 9579

資料對比:

python

pytorch

intinttensor of size()

float

floattensor of size()

int array

inttensor of size[d1, d2,…]

float

floattensor of size [d1, d2,…]

string

沒有對string的支援,可以one-hot/embedding的編碼表示

資料型別

data type

dtype

cpu tensor

gpu tensor

32-bit floating point

torch.float32 or torch.float

torch.floattensor

torch.cuda.floattensor

64-bit floating point

torch.float64 or torch.doble

torch.doubletensor

torch.cuda.doubletensor

16-bit floating point

torch.float16 or torch.half

torch.halftensor

torch.cuda.halftensor

8-bit integer (unsigned)

torch.unit8

torch.bytetensor

torch.cuda.bytetensor

8-bit integer (signed)

torch.int8

torch.chartensor

torch.cuda.chartensor

16-bit integer (signed)

torch.short

torch.shorttensor

torch.cuda.shorttensor

32-bit integer (signed)

torch.int

torch.inttensor

torch.cuda.inttensor

64-bit integer (signed)

torch.long

torch.longtensor

torch.cuda.longtensor

型別檢查:

in [1]: a = torch.randn(2,3)

in [2]: a.type()

out[3]: 'torch.floattensor'

in [4]: type(a)

out[5]: torch.tensor

in [6]: isinstance(a, torch.floattensor)

out[7]: true

isinstance():檢查資料是否為某種型別

標量:torch.tensor()

pytorch0.3之前的版本dim=0會返回1tensor

dim為0,loss

dim為1,bias; linear input

dim為2,linear input batch

dim為3,rnn input batch

dim為4,:數量,通道,高,寬。適合卷積神經網路

陣列匯入

a = np.array([2

,3,3

])torch.from_numpy(a)

列表匯入

torch.tensor([2

.,3.2]

)torch.flosttensor([2

.,3.2]

)tensor:大寫接收維度,小寫接收資料。多用小寫的,直接用現成的data。建立後shape不變

torch.empty(

)torch.inttensor(

)

rand:隨機0-1之間的資料

rand_like(shape):生成指定shape的tensor

randint(mix_num,max_num,shape):指定最小值,最大值,shape,隨機生成tensor.(圖中第15行為:torch.randint(1,10,(3,3)) )

正態分佈:randn

full:用於全部賦值為同乙個數

生成遞增或遞減的等差數列,arrange(a,b,s),a表示起始值,b表示上限但不包括在數列中,s表示遞增或遞減的步長

生成等分的數列,linspacee(a,b,steps=num),a表示起始值,b表示上限但不包括在數列中,steps=num表示等分的個數

生成全為1,全為0和對角線的tensor,eye只能接收2個以下的引數

randperm:隨機打散;random.shuffle:隨機數種子

pytorch 資料型別

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

Pytorch資料型別轉換

pytorch的型別可以分為cpu和gpu上的tensor,它們擁有的資料型別是基本上是一樣的 tensor.floattensor tensor.longtensor tensor.bytetensor tensor.chartensor tensor.shorttensor tensor.int...

Pytorch基礎 一 資料型別和建立資料

pytorch中的資料型別主要是tensor 這種資料型別與python直譯器本身資料型別可以對應。但str型別有所不同。一般用一下幾種方式表示字串 在python直譯器中,資料無論在cpu還是gpu資料型別是相同的。但在pytorch中cpu和gpu中的資料有所不同 型別檢驗 a torch.ra...