Pytorch学习笔记3:维度变换测试代码
#添加到学习笔记2末尾,直接运行。代码意义可以看注释。
print('——————————维度变换——————————')
va=torch.rand(4,1,28,28)
print('tensor shape:',va.shape)
vb=va.view(4,1*28*28)#把va后面三个维度合并,变成一个二维tensor,元素个数保持不变
print('tensor shape:',vb.shape)
vc=va.view(4*1*28,28)#把va前面三个维度合并,变成一个二维tensor,元素个数保持不变
print('tensor shape:',vc.shape)
vd=va.unsqueeze(0)#在第一维前面增加一个维度
print('tensor shape:',vd.shape)
ve=va.unsqueeze(-1)#在最后一维后面增加一个维度
print('tensor shape:',ve.shape)
vf=va.unsqueeze(4)#在最后一维后面增加一个维度,建议都用正数,在正数序号之前插入维度
print('tensor shape:',vf.shape)
vg=torch.rand(32)#把vg扩展成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)#两个tensor的维度必须相同,其中一个维度的数字相同
print('tensor shape:',vm.shape)
vn=torch.rand(4,3)#矩阵转置
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)#向量维度变化和跟踪实例
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('——————————维度变换——————————')