码迷,mamicode.com
首页 > 其他好文 > 详细

pytorch学习问题汇总

时间:2018-01-29 15:56:31      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:转换   use   mat   int()   nbsp   class   ali   学习   种类型   

问题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学习问题汇总

标签:转换   use   mat   int()   nbsp   class   ali   学习   种类型   

原文地址:https://www.cnblogs.com/bawu/p/8267474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!