深度学习中特征(tensor)维度转换
深度学习中使用其他模块或者通道调整时常常需要维度转换,比如三维转四维或者四维转三维,下面用代码示例转换过程。
四维转三维 BCHW->BCN
import torch
x = torch.randn(8, 3, 32, 32) #BCN
print(x.shape)
b, c, h, w = x.size()
out = x.view(b, h*w, c)
print(out.shape)
'''
torch.Size([8, 3, 32, 32])
torch.Size([8, 1024, 3])
'''
核心方法是view函数,根据输入参数自动调整通道中的特征信息。
三维转四维 BCN->BCH*W
import torch
x = torch.randn(8, 3, 1024) #BCN
print(x.shape)
b, c, n = x.size()
h = 32
w = 32
out = x.view(-1, h, w, c)
print(out.shape)
out = x.view(b, h, w, c)
print(out.shape)
'''
torch.Size([8, 3, 1024])
torch.Size([8, 32, 32, 3])
torch.Size([8, 32, 32, 3])
'''
view中参数取-1会自动调整数值大小,如果手动设定,则要保证数值大小对应。