pytorch学习问题汇总

Posted bawu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pytorch学习问题汇总相关的知识,希望对你有一定的参考价值。

问题1:torch各个类型数据格式如何转换?数据类型在官方文档torch.Tensor中,有八种类型。

#尝试一
i32=torch.IntTensor([1,2,3])
i64=torch.LongTensor([1,2,3])
#两种转换都报错
#new_i64=torch.IntTensor(i64)
#new_i32=torch.LongTensor(i32)
#didn‘t match because some of the arguments have invalid types: (!torch.LongTensor!)

#尝试二
new_i32=i32.long()
print(torch.equal(new_i32,i64))  #True
#torch.Tensor对应八种数据转换,各种数据可以相互转换
i32.float()
i32.double()
i32.half()
i32.byte()
i32.char()
i32.short()
i32.int()
i32.long()

问题2:官方文档中sequence of tensors是什么意思?在torch.stack(sequencedim=0out=None).

 是tensors构成的序列,可以为列表,也可以为元组

#torch.stack(sequence, dim=0, out=None) 连接Tensors
i32=torch.Tensor([1,2,3])
print(torch.stack([i32,i32,i32]))  #默认dim=0,以列为基准
#  1  2  3
#  1  2  3
#  1  2  3
# [torch.FloatTensor of size 3x3]
print(torch.stack([i32,i32,i32],dim=1))
#  1  1  1
#  2  2  2
#  3  3  3
# [torch.FloatTensor of size 3x3]
print(torch.stack((i32,i32,i32),dim=1))
#  1  1  1
#  2  2  2
#  3  3  3
# [torch.FloatTensor of size 3x3]

问题3:为什么有如下Tensor格式区别?有的是size 3,有的是size 4x1 ?

torch.from_numpy(np.array([1,2,3]))   #torch.IntTensor of size 3
torch.from_numpy(np.array([1.0,2,3])) #torch.DoubleTensor of size 3
torch.nonzero(torch.Tensor([1,2,3,0,4]))==torch.Tensor([0,1,2,4])
# TypeError: eq received an invalid combination of arguments - got (torch.FloatTensor), but expected one of:
#  * (int value)
#       didn‘t match because some of the arguments have invalid types: (!torch.FloatTensor!)
#  * (torch.LongTensor other)
#       didn‘t match because some of the arguments have invalid types: (!torch.FloatTensor!)
#注意上面代码中两者数据格式类型不一致,torch.FloatTensor   torch.LongTensor
#torch.unsqueeze(input,dim,out=None)
m=torch.Tensor([1,2,3,4])
print(m)                     #torch.FloatTensor of size 4
m_zero=torch.unsqueeze(m,0)
print(m_zero)                #torch.FloatTensor of size 1x4
m_one=torch.unsqueeze(m,1)
print(m_one)                 #torch.FloatTensor of size 4x1

m_zero_to_m=torch.squeeze(m_zero)
print(m_zero_to_m)           #torch.FloatTensor of size 4
print(m==m_zero_to_m)        #torch.ByteTensor of size 4
# 1
# 1
# 1
# 1
print(m.equal(m_zero_to_m))  True

可见为两种不同数据类型,可以通过unsqueeze和squeeze来相互转化。判断两个Tensor是否相等,用equal

问题4、


以上是关于pytorch学习问题汇总的主要内容,如果未能解决你的问题,请参考以下文章

20180122 PyTorch学习资料汇总

Pytorch模型训练实用教程学习笔记:三损失函数汇总

Pytorch CIFAR10 图像分类篇 汇总

Pytorch CIFAR10 图像分类篇 汇总

推荐不可思议的PyTorch:PyTorch教程论文项目社区资源大汇总

Pytorch CIFAR10图像分类 工具函数utils篇