在PyTorch中進行模型遷移學習通常需要以下步驟:
import torch
import torchvision.models as models
pretrained_model = models.resnet18(pretrained=True)
pretrained_model.fc = nn.Linear(pretrained_model.fc.in_features, num_classes)
for param in pretrained_model.parameters():
param.requires_grad = False
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(pretrained_model.fc.parameters(), lr=0.001)
for epoch in range(num_epochs):
for images, labels in dataloader:
optimizer.zero_grad()
outputs = pretrained_model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
通過以上步驟,你可以在PyTorch中進行模型遷移學習。你可以根據具體的任務需求對以上步驟進行調整和擴展。