如何从 PyTorch 中的 ResNet 模型中删除最后一个 FC 层?

问题描述 投票:0回答:5

我正在使用 PyTorch 的 ResNet152 模型。我想从模型中去掉最后一个 FC 层。这是我的代码:

from torchvision import datasets, transforms, models
model = models.resnet152(pretrained=True)
print(model)

当我打印模型时,最后几行看起来像这样:

    (2):  Bottleneck(
      (conv1):  Conv2d(2048,  512,  kernel_size=(1,  1),  stride=(1,  1),  bias=False)
      (bn1):  BatchNorm2d(512,  eps=1e-05,  momentum=0.1,  affine=True,  track_running_stats=True)
      (conv2):  Conv2d(512,  512,  kernel_size=(3,  3),  stride=(1,  1),  padding=(1,  1),  bias=False)
      (bn2):  BatchNorm2d(512,  eps=1e-05,  momentum=0.1,  affine=True,  track_running_stats=True)
      (conv3):  Conv2d(512,  2048,  kernel_size=(1,  1),  stride=(1,  1),  bias=False)
      (bn3):  BatchNorm2d(2048,  eps=1e-05,  momentum=0.1,  affine=True,  track_running_stats=True)
      (relu):  ReLU(inplace)
    )
  )
  (avgpool):  AvgPool2d(kernel_size=7,  stride=1,  padding=0)
  (fc):  Linear(in_features=2048,  out_features=1000,  bias=True)
)

我想从模型中删除最后一个 fc 层。

我在这里找到了答案(如何将预训练的FC层转换为Pytorch中的CONV层),其中mexmex似乎提供了我正在寻找的答案:

list(model.modules()) # to inspect the modules of your model
my_model = nn.Sequential(*list(model.modules())[:-1]) # strips off last linear layer

所以我将这些行添加到我的代码中,如下所示:

model = models.resnet152(pretrained=True)
list(model.modules()) # to inspect the modules of your model
my_model = nn.Sequential(*list(model.modules())[:-1]) # strips off last linear layer
print(my_model)

但是这段代码并不像宣传的那样工作——至少不适合我。这篇文章的其余部分详细解释了为什么这个答案不起作用,因此这个问题不会作为重复问题被关闭。

首先,打印的模型比以前大了近 5 倍。我看到与之前相同的模型,但后面似乎是该模型的重复,但可能是扁平化的。

    (2): Bottleneck(
      (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
      (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (relu): ReLU(inplace)
    )
  )
  (avgpool): AvgPool2d(kernel_size=7, stride=1, padding=0)
  (fc): Linear(in_features=2048, out_features=1000, bias=True)
)
(1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
(2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(3): ReLU(inplace)
(4): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)
(5): Sequential(
  . . . this goes on for ~1600 more lines . . .
  (415): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (416): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
  (417): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (418): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
  (419): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (420): ReLU(inplace)
  (421): AvgPool2d(kernel_size=7, stride=1, padding=0)
)

其次,fc 层仍然存在——而它之后的 Conv2D 层看起来就像 ResNet152 的第一层。

第三,如果我尝试调用

my_model.forward()
,pytorch 会抱怨大小不匹配。它期望大小为 [1, 3, 224, 224],但输入为 [1, 1000]。所以看起来整个模型的副本(减去 fc 层)被附加到原始模型中。

底线,我在 SO 上找到的唯一答案实际上不起作用。

python pytorch resnet
5个回答
62
投票

对于ResNet模型,您可以使用children属性来访问层,因为pytorch中的ResNet模型由nn个模块组成。 (在 pytorch 0.4.1 上测试)

model = models.resnet152(pretrained=True)
newmodel = torch.nn.Sequential(*(list(model.children())[:-1]))
print(newmodel)

更新:虽然这个问题没有一个适用于所有 pytorch 模型的通用答案,但它应该适用于所有结构良好的模型。您添加到模型中的现有层(例如 torch.nn.Lineartorch.nn.Conv2dtorch.nn.BatchNorm2d...)均基于 torch.nn.Module 类。如果您实现自定义层并将其添加到网络中,您应该从 pytorch 的 torch.nn.Module 类继承它。正如文档中所写,children 属性允许您访问类/模型/网络的模块。

def children(self):
        r"""Returns an iterator over immediate children modules.  

更新:值得注意的是,children() 返回“立即”模块,这意味着如果网络的最后一个模块是顺序的,它将返回整个顺序。


30
投票

您可以简单地做到这一点:

Model.fc = nn.Sequential()

或者您可以创建身份层:

class Identity(nn.Module):
    def __init__(self):
        super().__init__()
        
    def forward(self, x):
        return x

并用它替换 fc 层:

Model.fc = Identity()

17
投票

如果您不仅希望剥离最后一个 FC 层的模型,而是希望用自己的模型替换它,从而利用迁移学习技术,您可以这样做:

import torch.nn as nn
from collections import OrderedDict

n_inputs = model.fc.in_features

# add more layers as required
classifier = nn.Sequential(OrderedDict([
    ('fc1', nn.Linear(n_inputs, 512))
]))

model.fc = classifier

3
投票

来自 PyTorch 教程 “微调 TorchVision 模型”

这里我们使用 Resnet18,因为我们的数据集很小并且只有两个类。当我们打印模型时,我们看到最后一层是全连接层,如下所示:

(fc): Linear(in_features=512, out_features=1000, bias=True)

因此,我们必须将

model.fc
重新初始化为具有 512 个输入特征和 2 个输出特征的线性层:

model.fc = nn.Linear(512, num_classes)

0
投票

或者,将 fc 层更改为 Identity。

nn.Identity()
只是将其输入转发到输出:

import torch.nn as nn
from torchvision.models import resnet50, ResNet50_Weights

# load a pretrained resnet50 model
model = resnet50(weights = ResNet50_Weights.DEFAULT)
model.fc = nn.Identity()
© www.soinside.com 2019 - 2024. All rights reserved.