Skip to main content
Open In Colab

title: Transfer Learning for Computer Vision Tutorial sidebar: sidebar-dnn

Author: Sasank Chilamkurthy <https://chsasank.github.io>_ In this tutorial, you will learn how to train a convolutional neural network for image classification using transfer learning. You can read more about the transfer learning at cs231n notes <https://cs231n.github.io/transfer-learning/>__ In practice, very few people train an entire Convolutional Network from scratch (with random initialization), because it is relatively rare to have a dataset of sufficient size. Instead, it is common to pretrain a ConvNet on a very large dataset (e.g. ImageNet, which contains 1.2 million images with 1000 categories), and then use the ConvNet either as an initialization or a fixed feature extractor for the task of interest. These two major transfer learning scenarios look as follows:
  • Finetuning the convnet: Instead of random initialization, we initialize the network with a pretrained network, like the one that is trained on imagenet 1000 dataset. Rest of the training looks as usual.
  • ConvNet as fixed feature extractor: Here, we will freeze the weights for all of the network except that of the final fully connected layer. This last fully connected layer is replaced with a new one with random weights and only this layer is trained.

Load Data

We will use torchvision and torch.utils.data packages for loading the data. The problem we’re going to solve today is to train a model to classify ants and bees. We have about 120 training images each for ants and bees. There are 75 validation images for each class. Usually, this is a very small dataset to generalize upon, if trained from scratch. Since we are using transfer learning, we should be able to generalize reasonably well. This dataset is a very small subset of imagenet. The data was downloaded from https://download.pytorch.org/tutorial/hymenoptera_data.zip_ and extract it to the current directory.

Visualize a few images

Let’s visualize a few training images so as to understand the data augmentations.
Output from cell 5

Training the model

Now, let’s write a general function to train a model. Here, we will illustrate:
  • Scheduling the learning rate
  • Saving the best model
In the following, parameter scheduler is an LR scheduler object from torch.optim.lr_scheduler.

Visualizing the model predictions

Generic function to display predictions for a few images

Finetuning the convnet

Load a pretrained model and reset final fully connected layer.

Train and evaluate

It should take around 15-25 min on CPU. On GPU though, it takes less than a minute.
Output from cell 10 Output from cell 10 Output from cell 10 Output from cell 10 Output from cell 10 Output from cell 10

ConvNet as fixed feature extractor

Here, we need to freeze all the network except the final layer. We need to set requires_grad = False to freeze the parameters so that the gradients are not computed in backward(). You can read more about this in the documentation here <https://pytorch.org/docs/notes/autograd.html#excluding-subgraphs-from-backward>__.

Train and evaluate

On CPU this will take about half the time compared to previous scenario. This is expected as gradients don’t need to be computed for most of the network. However, forward does need to be computed.
Output from cell 13 Output from cell 13 Output from cell 13 Output from cell 13 Output from cell 13 Output from cell 13

Further Learning

If you would like to learn more about the applications of transfer learning, checkout our Quantized Transfer Learning for Computer Vision Tutorial <https://pytorch.org/tutorials/intermediate/quantized_transfer_learning_tutorial.html>_.

PyTorch reference


Found an error on this page? Report an issue.