Pytorch學(xué)習(xí)筆記5:統(tǒng)計(jì)計(jì)算與高階賦值操作
#添加到學(xué)習(xí)筆記2末尾,直接運(yùn)行。代碼意義可以看注釋。
print('——————————統(tǒng)計(jì)計(jì)算——————————')
norm1=torch.full([8],1.0)
print('norm1:',norm1.shape)
norm2=norm1.view(2,4)
norm3=norm1.view(2,2,2)
print('norm2:',norm2.shape)
print('norm3:',norm3.shape)
print('norm1.norm(1):',norm1.norm(1))#1范數(shù),元素平方和
print('norm2.norm(1):',norm2.norm(1))
print('norm3.norm(1):',norm3.norm(1))
print('norm1.norm(2):',norm1.norm(2))#2范數(shù),元素平方和再開方
print('norm2.norm(2):',norm2.norm(2))
print('norm3.norm(2):',norm3.norm(2))
print('norm2.norm(1,dim=1):',norm2.norm(1,dim=1).shape)#指定維度求范數(shù)
print('norm2.norm(1,dim=1):',norm2.norm(1,dim=1))
print('norm3.norm(1,dim=2):',norm3.norm(2,dim=2).shape)#指定維度求范數(shù)
print('norm3.norm(1,dim=2):',norm3.norm(2,dim=2))
tongji1=torch.arange(8).view(2,2,2).float()
print('tongji1:',tongji1)
print('min:',tongji1.min())
print('max:',tongji1.max())
print('mean:',tongji1.mean())#平均值
print('prod:',tongji1.prod())#累乘
print('argmax:',tongji1.argmax())#最大值索引
print('argmin:',tongji1.argmin())#最小值索引
tongji2=tongji1.view(8).view(2,4)
print('tongji2:',tongji2)
print('argmax:',tongji2.argmax(dim=1))#指定維度/行,求最大值索引
print('max:',tongji2.max(dim=1))#max會(huì)返回最大值以及最大值索引
print('argmax:',tongji2.argmax(dim=1,keepdim=True))#保持維度不變
print('max:',tongji2.max(dim=1,keepdim=True))#保持維度不變
topk1=torch.rand(4,10)
print('top3:',topk1.topk(3,dim=1))#求最大的3個(gè)數(shù)及其索引
print('last3:',topk1.topk(3,dim=1,largest=False))#求最小的3個(gè)數(shù)及其索引
print('第3小的值:',topk1.kthvalue(3,dim=1))#第3小的值及其索引
print('大于0.5的值:',topk1>0.5)#每一個(gè)元素和0.5比較,大于0.5就賦值為Ture,小于0.5賦值為False
print('不等于0.5的值:',topk1!=0.5)#不等于0.5
equal1=torch.randn(3,3)
equal2=torch.ones(3,3)
print('兩個(gè)tensor元素比較:',torch.eq(equal1,equal2))#比較每一個(gè)元素
print('兩個(gè)tensor比較:',torch.equal(equal1,equal2))#返回一個(gè)bool值
print('——————————統(tǒng)計(jì)計(jì)算——————————')
print('——————————高階操作——————————')
cond=torch.eye(3,3)
a=torch.full([9],5.).view(3,3)
b=torch.full([9],7.).view(3,3)
print(a)
print(b)
c=(cond==1)
print(c)#condition需要是bool值組成的tensor
print(torch.where(c,a,b))#根據(jù)c的bool表來在a,b中取值
prob=torch.rand(4,10)
print(prob)
idx=prob.topk(5,dim=1)
print(idx)
idx=idx[1]
print(idx)
label=torch.arange(10)+100
print(label.expand(4,10))
print(torch.gather(label.expand(4,10),dim=1,index=idx))#根據(jù)idx的值查表賦值,返回tensor的shape與idx一樣
print('——————————高階操作——————————')