在Torch中进行迁移学习通常涉及以下步骤:
import torchvision.models as models
model = models.resnet18(pretrained=True)
model.fc = nn.Linear(model.fc.in_features, 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中进行迁移学习了。根据具体的任务和数据集,可能需要调整模型结构和训练策略。