在PyTorch中实现迁移学习通常包括以下步骤:
import torch
import torchvision.models as models
model = models.resnet18(pretrained=True)
n_features = model.fc.in_features
model.fc = torch.nn.Linear(n_features, num_classes) # num_classes为新任务的类别数
for param in model.parameters():
param.requires_grad = False
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
for epoch in range(num_epochs):
for inputs, labels in dataloader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
这样就完成了迁移学习的实现过程。通过以上步骤,你可以利用预训练的模型在新任务上快速进行模型训练。