PyTorch中预训练模型的微调主要包括以下步骤:
import torchvision.models as models
pretrained_model = models.resnet18(pretrained=True)
import torch.nn as nn
num_classes = 10 # CIFAR-10数据集的分类数量
pretrained_model.fc = nn.Linear(pretrained_model.fc.in_features, num_classes)
requires_grad
属性设置为False
来实现这一点:for param in pretrained_model.parameters():
param.requires_grad = False
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(pretrained_model.parameters(), lr=0.001, momentum=0.9)
for epoch in range(num_epochs):
for images, labels in train_loader:
optimizer.zero_grad()
outputs = pretrained_model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
这就是使用PyTorch微调预训练模型的基本过程。请注意,这只是一个简单的示例,实际应用中可能需要根据具体任务进行调整。