遷移學習是指將一個已經訓練好的模型的知識遷移到另一個相關任務上,以加快新任務的學習過程。在Torch中進行遷移學習可以通過以下步驟實現:
import torchvision.models as models
model = models.resnet18(pretrained=True)
import torch.nn as nn
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, num_classes)
for param in model.parameters():
param.requires_grad = False
criterion = 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()
通過以上步驟,就可以在Torch中進行遷移學習,將已有模型的知識應用到新的任務上。