在PyTorch中使用预训练的模型进行迁移学习可以通过以下步骤实现:
- 加载预训练模型:首先,使用torchvision.models模块中提供的预训练模型来加载已经训练好的模型,例如ResNet、VGG等。
import torchvision.models as models # Load pre-trained ResNet-50 model model = models.resnet50(pretrained=True)
- 修改模型的最后一层:由于迁移学习通常涉及到不同的任务,需要将预训练模型的最后一层替换为新的全连接层,以适应新的任务要求。
import torch.nn as nn # Modify the last layer of the model num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, num_classes) # num_classes为新任务的类别数
- 设置优化器和损失函数:根据新任务的要求设置优化器和损失函数。
import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
- 训练模型:使用新的数据集对模型进行训练。
# 训练代码
通过以上步骤,您可以在PyTorch中使用预训练的模型进行迁移学习。