【问题标题】:Flattening Efficientnet model展平 Efficientnet 模型
【发布时间】:2020-07-17 13:27:33
【问题描述】:

我正在尝试删除高效网络-pytorch 实现中的顶层。但是,如果我只是按照作者in this github comment 的建议,将最终的_fc 层替换为我自己的全连接层,我担心即使在此层之后仍然有swish 激活,而不是什么都没有正如我所料。当我打印模型时,最后几行如下:

(_bn1): BatchNorm2d(1280, eps=0.001, momentum=0.010000000000000009, affine=True, track_running_stats=True)
    (_avg_pooling): AdaptiveAvgPool2d(output_size=1)
    (_dropout): Dropout(p=0.2, inplace=False)
    (_fc): Sequential(
      (0): Linear(in_features=1280, out_features=512, bias=True)
      (1): ReLU()
      (2): Dropout(p=0.25, inplace=False)
      (3): Linear(in_features=512, out_features=128, bias=True)
      (4): ReLU()
      (5): Dropout(p=0.25, inplace=False)
      (6): Linear(in_features=128, out_features=1, bias=True)
    )
    (_swish): MemoryEfficientSwish()
  )
)

_fc 是我替换的模块。

我希望做的是:

base_model = EfficientNet.from_pretrained('efficientnet-b3')
model = nn.Sequential(*list(base_model.children()[:-3]))

在我看来base_model.children() 将模型从嵌套结构中展平。但是,现在我似乎无法像使用虚拟输入一样使用模型,x=torch.randn(1,3,255,255) 我收到错误:TypeError: forward() takes 1 positional argument but 2 were given

应该注意model[:2](x) 有效,但model[:3](x) 无效。 model[2] 好像是移动方块。

这是带有上述代码的colab notebook

【问题讨论】:

    标签: deep-learning pytorch conv-neural-network efficientnet


    【解决方案1】:

    这是对print(net) 实际作用的常见误解。

    _swish 模块在_fc 之后的事实仅仅意味着前者是在后者之后注册的。您可以在code 中查看:

    class EfficientNet(nn.Module):
        def __init__(self, blocks_args=None, global_params=None):
    
            # [...]
    
            # Final linear layer
            self._avg_pooling = nn.AdaptiveAvgPool2d(1)
            self._dropout = nn.Dropout(self._global_params.dropout_rate)
            self._fc = nn.Linear(out_channels, self._global_params.num_classes)
            self._swish = MemoryEfficientSwish()
    

    定义它们的顺序是它们将被打印的顺序。至于具体执行什么,你必须检查forward

    def forward(self, inputs):
        # Convolution layers
        x = self.extract_features(inputs)
    
        # Pooling and final linear layer
        x = self._avg_pooling(x)
        x = x.flatten(start_dim=1)
        x = self._dropout(x)
        x = self._fc(x)
    
        return x
    

    如您所见,self._fc(x) 之后没有任何内容,这意味着不会应用 Swish

    【讨论】:

    • 哇!我不知道。那么,截至 2021 年 8 月,检查 print(inspect.getsource(model.forward)) 的订单是否是唯一可靠的方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2020-08-25
    • 1970-01-01
    相关资源
    最近更新 更多