PyTorch的数据类型与创建
数据对比:
python | PyTorch |
---|---|
Int | IntTensor 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:随机数种子