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
Quoting these notes,
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.
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.
Let’s visualize a few training images so as to understand the data
augmentations.
defimshow(inp,title=None):"""Display image for Tensor."""inp=inp.numpy().transpose((1,2,0))mean=np.
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.
deftrain_model(model,criterion,optimizer,scheduler,num_epochs=25):since=time.time()# Create a temporary directory to save training checkpointswithTemporaryDirectory()astempdir:best_model_params_path=os.path.join(tempdir,'best_model_params.pt')torch.save(model.state_dict(),best_model_params_path)best_acc=0.0forepochinrange(num_epochs):print(f'Epoch {epoch}/{num_epochs-1}')print('-'*10)# Each epoch has a training and validation phaseforphasein['train','val']:ifphase=='train':model.train()# Set model to training modeelse:model.eval()# Set model to evaluate moderunning_loss=0.0running_corrects=0# Iterate over data.forinputs,labelsindataloaders[phase]:inputs=inputs.to(device)labels=labels.to(device)# zero the parameter gradientsoptimizer.zero_grad()# forward# track history if only in trainwithtorch.set_grad_enabled(phase=='train'):outputs=model(inputs)_,preds=torch.max(outputs,1)loss=criterion(outputs,labels)# backward + optimize only if in training phaseifphase=='train':loss.backward()optimizer.step()# statisticsrunning_loss+=loss.item()*inputs.size(0)running_corrects+=torch.sum(preds==labels.data)ifphase=='train':scheduler.step()epoch_loss=running_loss/dataset_sizes[phase]epoch_acc=running_corrects.double()/dataset_sizes[phase]print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')# deep copy the modelifphase=='val'andepoch_acc>best_acc:best_acc=epoch_acctorch.save(model.state_dict(),best_model_params_path)print()time_elapsed=time.time()-sinceprint(f'Training complete in {time_elapsed//60:.0f}m {time_elapsed%60:.0f}s')print(f'Best val Acc: {best_acc:4f}')# load best model weightsmodel.load_state_dict(torch.load(best_model_params_path,weights_only=True))returnmodel
Visualizing the model predictions
Generic function to display predictions for a few images
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.
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.