【資料圖】
深度學習--PyTorch維度變換、自動拓展、合并與分割
一、維度變換
1.1 view/reshape 變換
?這兩個方法用法相同,就是變換變量的shape,變換前后的數(shù)據(jù)量相等。
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 擴展/重復 對一個維度內(nèi)部的大小進行擴展,增加數(shù)據(jù)
#b.expand(4,32,14,14) 對維度內(nèi)進行拓展,用-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(次數(shù)) 中間表示當前層拷貝的次數(shù)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) 不當?shù)牟僮骺赡軐π畔⑦M行破壞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自動擴展
步驟為:
- 在前面插入一個維度dim
- 對新加入的維度進行擴張,擴張成對應的size
符合擴展規(guī)則才能用。
三、合并與分割
3.1合并
#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])
#torch.stack([變量,變量],dim) 創(chuàng)建一個新的維度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拆分
#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])
#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])
關鍵詞: