【问题标题】:Adding image size as second input to existing PyTorch model添加图像大小作为现有 PyTorch 模型的第二个输入
【发布时间】:2022-01-24 14:41:28
【问题描述】:

我在 PyTorch 中使用预训练的 torchvision 模型和迁移学习来分类我自己的数据集。这很好,但我认为我可以进一步提高我的分类性能。我们的图片有不同的尺寸,所有图片都调整大小以适合我的模型的输入(例如,调整为 224x224 像素)。

但是,原始图像大小通常说明了该图像所属的很多类别。所以我认为这可能有助于模型将原始图像尺寸作为第二个输入添加到模型中。

目前我在 PyTorch 中像这样构建我的模型:

model = resnet50(pretrained=True)  # Could be another base model as well
for module, param in zip(model.modules(), model.parameters()):
    if isinstance(module, nn.BatchNorm2d):
        param.requires_grad = False
model.fc = nn.Sequential(
                nn.Linear(2048, 512),
                nn.ReLU(),
                nn.Dropout(0.25),
                nn.Linear(512, 256),
                nn.ReLU(),
                nn.Dropout(0.25),
                nn.Linear(256, num_classes),
            )

现在如何向该模型添加另一个(二维?)输入,以便将原始图像的 x 和 y 维度提供给模型?此外,在哪里最有意义 - 直接进入模型的“开始”,还是更好的“介于两者之间”?

【问题讨论】:

    标签: python machine-learning deep-learning pytorch transfer-learning


    【解决方案1】:

    将数据注入模型的一种方法是直接注入线性层。

    这会有不影响卷积层的缺点。

    请注意,我注入到最后一层,但这可以进入任何层。

    model.start = nn.Sequential(
                    nn.Linear(2048, 512),
                    nn.ReLU(),
                    nn.Dropout(0.25),
                    nn.Linear(512, 256),
                    nn.ReLU(),
                    nn.Dropout(0.25),
                )
    
    model.end = nn.Sequential(   
                    nn.Linear(256 + 2, num_classes),
                )
    

    你的forward 应该是(伪代码)类似

    def forward(x):
        x1 = model.start(x)
        mid = torch.concatenate([x, extra_2d_data])
        x2 = model.end(mid)
        return x2
    

    另见this

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2021-07-25
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      相关资源
      最近更新 更多