python - 训练 fc 层后微调 PyTorch 模型

标签 python machine-learning pytorch

我正在尝试使用 PyTorch 进行迁移学习。我想先训练 FC 层,然后微调整个网络。不幸的是,在训练 fc 层然后通过我的网络进行微调之后,我失去了在第一次训练中获得的准确性。这是预期的行为还是我在这里做错了什么?

这是代码:

model = torchvision.models.resnet50(pretrained=True)
for param in model.parameters():
    param.requires_grad = False

num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 4)
model = model.to(device)

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

model = trainer.fit_model(dataloader, model, criterion, optimizer, num_epochs=10)
# fit model is basic PyTorch training function found here: https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#convnet-as-fixed-feature-extractor The only difference is that scheduler is an optional param.

for param in model.parameters():
    param.requires_grad = True

torch.cuda.empty_cache()
exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)

# Here I am finetuning the model
model_ft = trainer.fit_model(
    dataloader, model, criterion, optimizer, scheduler=exp_lr_scheduler, num_epochs=10
)

我在这里遗漏了一些东西还是我应该只训练模型一次?

最佳答案

这是在执行迁移学习时可能发生的事情,称为 灾难性遗忘。基本上,您过多地更新了预训练权重,并且“忘记”了之前学到的内容。如果你的学习率太高,这种情况可能会发生。我建议首先尝试较低的学习率,或者使用可微分的学习率(网络头部和预训练部分的学习率不同,这样你就可以在 fc 层上获得比其余部分更高的学习率)网络)。

关于python - 训练 fc 层后微调 PyTorch 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57655007/

相关文章:

python - 最大化形成交集的集合数

python - 在我的模型中使用 Pytorch SSIM 损失函数

numpy - .nu​​mpy() 函数有什么作用?

python - pytorch 可以优化顺序操作(如 tensorflow 图或 JAX 的 jit)吗?

python - 迭代解析 JSON 文件

python - 尝试删除 Pandas 中的异常值时出现 ValueError

python - 如何理解字节对编码?

Python:使用 scikit-learn 的 dbscan 进行字符串聚类,使用 Levenshtein 距离作为度量:

machine-learning - Java 中回归的机器学习特征排名/评分

machine-learning - run 在 openml 上代表什么?