深度学习--PyTorch维度变换、自动拓展、合并与分割

一、维度变换

1.1 view/reshape 变换

​ 这两个方法用法相同,就是变换变量的shape,变换前后的数据量相等。

a=torch.rand(4,1,28,28)
a.view(4,28*28)
#tensor([[0.9787, 0.6729, 0.4877,  ..., 0.8975, 0.3361, 0.9341],
#        [0.4316, 0.8875, 0.2974,  ..., 0.3385, 0.5543, 0.5648],
#        [0.3156, 0.1170, 0.7126,  ..., 0.4445, 0.7357, 0.4900],
#        [0.7127, 0.9316, 0.7615,  ..., 0.7660, 0.5437, 0.1383]])

a.reshape(4,28*28)
#tensor([[0.9787, 0.6729, 0.4877,  ..., 0.8975, 0.3361, 0.9341],
#        [0.4316, 0.8875, 0.2974,  ..., 0.3385, 0.5543, 0.5648],
#        [0.3156, 0.1170, 0.7126,  ..., 0.4445, 0.7357, 0.4900],
#        [0.7127, 0.9316, 0.7615,  ..., 0.7660, 0.5437, 0.1383]])

1.2 squeeze/unsqueeze 挤压/拉伸 维度删除/维度添加

a.shape
#torch.Size([4, 1, 28, 28])

#a.unsqueeze(x) 在x位置之后插入
a.unsqueeze(1).shape
#torch.Size([4, 1, 1, 28, 28])


#a.squeeze(x) 删除x维度
a.squeeze(1).shape
#torch.Size([4, 28, 28])
a.squeeze(0).shape
#torch.Size([4, 1, 28, 28]) 当前维度非0,不会进行压缩

1.3 expand/reapeat 扩展/重复 对一个维度内部的大小进行扩展,增加数据

#b.expand(4,32,14,14)  对维度内进行拓展,用-1表示不对当前层进行操作
a=torch.rand(4,32,14,14)
b=torch.rand(1,32,1,1)
b.shape
#torch.Size([1, 32, 1, 1])
b.expand(4,32,14,14).shape
#torch.Size([4, 32, 14, 14])

#b.repeat(次数)  中间表示当前层拷贝的次数
b.repeat(4,1,14,14).shape
#torch.Size([4, 32, 14, 14])

1.4 转置操作 t/transpose/permute

#t()  只能对2D进行操作
a=torch.randn(3,4)
a.t().shape
#torch.Size([4, 3])

#transpose(d1,d2) 不当的操作可能对信息进行破坏
a=torch.randn(4,3,32,32)
a1=a.transpose(1,3).contiguous().view(4,3*32*32).view(4,32,32,3)
a1.shape
#torch.Size([4, 32, 32, 3])

#permute(d,d,d,d) 对维度下标进行操作
a.permute(3,2,1,0).shape
#torch.Size([32, 32, 3, 4])

二、Broadcast自动扩展

步骤为:

  1. 在前面插入一个维度dim
  2. 对新加入的维度进行扩张,扩张成对应的size

符合扩展规则才能用。

三、合并与分割

3.1合并

  • cat
#torch.cat([变量,变量],dim) 在当前维度上进行操作
a=torch.rand(4,32,8)
b=torch.rand(5,32,8)
torch.cat([a,b],dim=0).shape
#torch.Size([9, 32, 8])
  • stack
#torch.stack([变量,变量],dim) 创建一个新的维度
a=torch.rand(4,3,32,32)
b=torch.rand(4,3,32,32)
torch.stack([a,b],dim=2).shape
#torch.Size([4, 3, 2, 32, 32])

3.2拆分

  • split:按照长度拆分
#a.split([b1,b2,b3...],dim=0)  对dim进行拆分
a=torch.rand(2,4,3,32,32)
a1,a2=a.split(1,dim=0)
print(a1.shape)
print(a2.shape)
#torch.Size([1, 4, 3, 32, 32])
#torch.Size([1, 4, 3, 32, 32])
  • chunk:按数量进行拆分
#a.chunk(num,dim=0)  对当前dim的size/num进行拆分
a=torch.rand(4,4,3,32,32)
a1,a2=a.chunk(2,dim=0)
print(a1.shape)
print(a2.shape)
#torch.Size([2, 4, 3, 32, 32])
#torch.Size([2, 4, 3, 32, 32])