Pytorch學(xué)習(xí)筆記3:維度變換測(cè)試代碼
#添加到學(xué)習(xí)筆記2末尾,直接運(yùn)行。代碼意義可以看注釋。
print('——————————維度變換——————————')
va=torch.rand(4,1,28,28)
print('tensor shape:',va.shape)
vb=va.view(4,1*28*28)#把va后面三個(gè)維度合并,變成一個(gè)二維tensor,元素個(gè)數(shù)保持不變
print('tensor shape:',vb.shape)
vc=va.view(4*1*28,28)#把va前面三個(gè)維度合并,變成一個(gè)二維tensor,元素個(gè)數(shù)保持不變
print('tensor shape:',vc.shape)
vd=va.unsqueeze(0)#在第一維前面增加一個(gè)維度
print('tensor shape:',vd.shape)
ve=va.unsqueeze(-1)#在最后一維后面增加一個(gè)維度
print('tensor shape:',ve.shape)
vf=va.unsqueeze(4)#在最后一維后面增加一個(gè)維度,建議都用正數(shù),在正數(shù)序號(hào)之前插入維度
print('tensor shape:',vf.shape)
vg=torch.rand(32)#把vg擴(kuò)展成vh的維度
vh=torch.rand(4,32,14,14)
vg=vg.unsqueeze(1).unsqueeze(2).unsqueeze(0)#[32]->[32,1]->[32,1,1]->[1,32,1,1]
vi=torch.rand(1,32,1,1)#維度刪減
vj=vi.squeeze()#把1的維度全部刪掉
print('tensor shape:',vj.shape)
vk=vi.squeeze(0)#把0維刪掉
print('tensor shape:',vk.shape)
vl=torch.rand(1,32,1,1)
vm=vl.expand(4,32,14,14)#兩個(gè)tensor的維度必須相同,其中一個(gè)維度的數(shù)字相同
print('tensor shape:',vm.shape)
vn=torch.rand(4,3)#矩陣轉(zhuǎn)置
vo=vn.t()
print('tensor shape:',vn.shape)
print('tensor shape:',vo.shape)
vp=torch.rand(4,3,28,28)#維度交換1
print('tensor shape:',vp.shape)
vq=vp.transpose(1,3)
print('tensor shape:',vq.shape)
vr=vp.permute(0,3,1,2)#維度交換2
print('tensor shape:',vr.shape)
vt=torch.tensor([[[2.],[3.],[4.],[5.]],[[2.],[3.],[4.],[5.]]])#四維向量
vu=torch.randn_like(vt)#向量維度變化和跟蹤實(shí)例
print('tensor:',vu)
print('tensor shape:',vu.shape)
vs=vu.transpose(1,2)
print('tensor:',vs)
print('tensor:',vs.shape)
vs=vs.contiguous()
print('tensor:',vs)
print('tensor:',vs.shape)
vs=vs.view(1,8)
print('tensor:',vs)
print('tensor:',vs.shape)
vs=vs.view(2,4,1)
print('tensor:',vs)
print('tensor:',vs.shape)
print('tensor equal?:',torch.all(torch.eq(vs,vu)))
print('——————————維度變換——————————')