• 1. 数据类型:

在torch中CPU和GPU张量分别有8种数据类型, GPU tensor比CPU tensor多了.cuda

张量数据类型
数据类型 dtype CPU tensor GPU tensor
32位浮点型 torch.float32 或 torch.float torch.FloatTensor torch.cuda.FloatTensor
64位浮点型 torch.float64 或 torch.double torch.DoubleTensor torch.cuda.DoubleTensor
16位浮点型 torch.float16 或 torch.half torch.HalfTensor torch.cuda.HalfTensor
8位无符号整型 torch.uint8 torch.ByteTensor torch.cuda.ByteTensor
8位有符号整型 torch.int8 torch.CharTensor torch.cuda.CharTensor
16位有符号整型 torch.int16 或 torch.short torch.ShortTensor torch.cuda.ShortTensor
32位有符号整型 torch.int32 或 torch.int torch.IntTensor torch.cuda.IntTensor
64位有符号整型 torch.int64 或 torch.long torch.LongTensor

torch.cuda.LongTensor

在torch中默认的数据类型是32位浮点型(torch.FloatTensor), 

在程序中使用torch.tensor()生成一个张量, 然后使用.dtype获取张量的数据类型

实例:

import torch 

a = torch.tensor([1.3,4.6])
print('a.dtype:',a.dtype)

 

  • 2. 数据类型之间的相互转化:

方法1:

使用a.int(), a.long(), a.short(), a.float(), a.double(), a.half(), a.char(), a.byte() 进行转化

import torch 

a = torch.tensor([1.3,4.6])
b = a.byte()
print('b:',b)

方法2:

使用torch.type()函数, 直接输入需要转化成的类型

import torch 

a = torch.tensor([1.3,4.6])
b = a.type(torch.short)
print('b:',b)

方法3:

使用type_as() 函数,  该函数的作用是将该tensor的类型转化成另一个tensor的类型

import torch 

a = torch.tensor([1.3,4.6])
b = torch.tensor([2,4],dtype=torch.short)
c = a.type_as(b)
print('c:',c)

 

 

 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐