我有一個來自 PyTorch 的 3dResNet 模型。我還注釋掉了 resnet.py 源代碼中的 flatten 行,所以我的輸出不應該是一維的。
這是我的代碼:
class VideoModel(nn.Module):
def __init__(self,num_channels=3):
super(VideoModel, self).__init__()
self.r2plus1d = models.video.r2plus1d_18(pretrained=True)
self.r2plus1d.fc = Identity()
for layer in self.r2plus1d.children():
layer.requires_grad_ = False
def forward(self, x):
print(x.shape)
x = self.r2plus1d(x)
print(x.shape)
return x
我的身份類的存在只是為了忽略一個層:
class Identity(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return x
當我torch.randn(1, 3, 8, 112, 112)作為輸入運行時,我得到以下輸出:
torch.Size([1, 3, 8, 112, 112])
torch.Size([1, 512, 1, 1, 1])
為什么即使我洗掉了 fc 層和展平操作,我也有 1D 輸出?有沒有更好的方法來消除展平操作?
uj5u.com熱心網友回復:
原因是AdaptiveAvgPool3d展平步驟之前的圖層。它是用引數呼叫的output_size=(1,1,1),因此將最后三個維度合并為(1,1,1)不管它們的原始維度。
在您的情況下,平均池之后的輸出具有 shape (1,512,1,1,1), flatten 之后具有 shape (1,512),并且 fc 層之后具有 shape (1,400)。
所以flatten操作是不負責的,禁用平均池和所有后續步驟,才能得到想要的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/533066.html
