Skip to content

Instantly share code, notes, and snippets.

@Hanrui-Wang
Created July 17, 2019 17:45
Show Gist options
  • Select an option

  • Save Hanrui-Wang/d8430cee34a78f308020fac58afa5eae to your computer and use it in GitHub Desktop.

Select an option

Save Hanrui-Wang/d8430cee34a78f308020fac58afa5eae to your computer and use it in GitHub Desktop.
how to use a pretrained model as feature extractor and only finetune the last layer?
model_conv = torchvision.models.resnet18(pretrained=True)
for param in model_conv.parameters():
param.requires_grad = False
# Parameters of newly constructed modules have requires_grad=True by default
num_ftrs = model_conv.fc.in_features
model_conv.fc = nn.Linear(num_ftrs, 2)
model_conv = model_conv.to(device)
criterion = nn.CrossEntropyLoss()
# Observe that only parameters of final layer are being optimized as
# opposed to before.
optimizer_conv = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)
# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1)
model_conv = train_model(model_conv, criterion, optimizer_conv,
exp_lr_scheduler, num_epochs=25)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment