Pytorch 維度處理

viewsqueezeunsqueezetransposetpermuteexpandrepeat

import torch

# view
a = torch.rand(4, 1, 28, 28)
a.view(4, 28*28)	# 按實際意義合併數據,這裏將單通道圖片合成一個矢量


# unsqueeze
# add dim
a.unsqueeze(0).shape
# torch.Size([1, 4, 1, 28, 28])	# 前插 [x] num
a.unsqueeze(-1).shape
# torch.Size([4, 1, 28, 28, 1])	# 後插 num [x]

b = torch.rand(32)
b = b.unsqueeze(1).unsqueeze(2).unsqueeze(0)
# torch.Size([1, 32, 1, 1])


# expand & repeat
# 推薦使用expand,repeat要重開新內存
a = torch.rand(4, 32, 14, 14)
b.expand(4, 32, 14, 14).shape

# 跳過處理某個維度, 設置對應維度參數爲-1
b.expand(-1, 32, -1, -1)

# repeat
b.repeat(4, 32, 1, 1).shape	# batch 1 --> 4

# t
# 二維矩陣轉置
a = torch.randn(3, 4)
a.t()

# transpose
a = torch.rand(4, 3, 32, 32)

a1 = a.transpose(1, 3).contiguous().view(4, 3*32*32).view(4, 32, 32, 3).transpose(1, 3)
# [4, 3, 32, 32] --> [4, 32, 32, 3] --> [4, 3*32*32] --> [4, 32, 32, 3] --> [4, 3, 32, 32]
# verify
a1.shape

torch.all(torch.eq(a, a1))


# permute
a.permute(0, 2, 3, 1).shape
# 括號裏是對應維度位置的索引
發佈了41 篇原創文章 · 獲贊 51 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章