【问题标题】:How to use Pytorch to create a custom EfficientNet with the last layer written correctly如何使用 Pytorch 创建最后一层正确编写的自定义 EfficientNet
【发布时间】:2021-03-04 11:00:54
【问题描述】:

我有一个分类问题来预测 8 个类,例如,我在来自 here 的 pytorch 中使用 EfficientNetB3。但是,我对我的自定义类是否正确编写感到困惑。我想我想剥离预训练模型的最后一层以适应 8 个输出,对吗?我做对了吗?因为当我在我的DataLoader 中打印y_preds = model(images) 时,它似乎给了我1536 的预测。这是预期的行为吗?

!pip install geffnet 
import geffnet

class EfficientNet(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.model = geffnet.create_model(config.effnet, pretrained=True)
        n_features = self.model.classifier.in_features
        # does the name fc matter?
        self.fc = nn.Linear(n_features, config.num_classes)
        self.model.classifier = nn.Identity()
        
    def extract(self, x):
        x = self.model(x)
        return x

    def forward(self, x):
        x = self.extract(x).squeeze(-1).squeeze(-1)
        return x
    
model = EfficientNet(config=config)
if torch.cuda.is_available():
    model.cuda()

打印y_pred的示例代码:

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

for step, (images, labels) in enumerate(sample_loader):
    images = images.to(device)
    labels = labels.to(device)
    batch_size = images.shape[0]        
    y_preds = model(images)
    print('The predictions of the 4 images is as follows\n', y_preds)
    break

【问题讨论】:

    标签: machine-learning deep-learning pytorch classification conv-neural-network


    【解决方案1】:

    你甚至没有在前向传递中使用self.fc

    或者直接介绍为:

    def forward(self, x):
        ....
        x = extract(x)...
        x = fc(x)
        return x
    

    或者您可以简单地替换名为分类器的层(这样您就不需要身份层):

    self.model.classifier = nn.Linear(n_features, config.num_classes)
    

    另外,这里config.num_classes 应该是8。

    【讨论】:

    • 非常感谢您的解释,如果可以的话,还有一个问题,为什么我们需要在forward 传递中使用self.extract(x).squeeze(-1).squeeze(-1),为什么我们不能只说:x = self.model(x) 并删除extract 方法?
    • torch.squeeze 删除了额外的维度 1,你在这里不需要它。你可以直接调用self.model(x)。我不知道你为什么首先使用它。
    • 感谢您的回复,不胜感激。你什么时候想使用squeeze?正如我看到一些人这样做。
    • 有时,您可能会获得额外的维度,例如 (1, 1, 3, 224, 224),为了使其与可能仅适用于 4 个维度的其他操作兼容,您可以使用挤压。您也可能使用unsqeeze(),例如在输入一个大小为 (3, 224, 224) 的图像张量进行建模之前,使其大小变为 (1, 3, 224, 224),因为 pytorch 需要形状为 [N,C,H,W],其中 N 是 batch_size .
    • 水晶清晰的解释。如果可以的话,我会投票给你两次。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 2023-01-25
    • 2021-02-05
    相关资源
    最近更新 更多