Deep learning with fastai — Dogs and cats classification

Thomas Laurent
2 min readMay 9, 2020

--

Here is a simple example of using supervised learning, with fastai to classify images of cats and dogs, using a custom dataset (obtained using flickr). I used a pretrained resnet34 models based on ImageNet dataset. I could achieve a 1% error rate with 300 images for each category (cats or dogs). Please note that I did not use data augmentation so there is still room for improvement.

Here are some examples of the input

# Importing the different libraries

from fastai.vision import *
from fastai.metrics import error_rate
from pathlib import Path
#Trick to solve ndim issue
torch.Tensor.ndim = property(lambda x: len(x.size()))

# Setting batchsize (24)

bs=24

# Importing the data (Please note that I choose an image size of 224 pixels)

data=ImageDataBunch.from_folder(path,train="train",valid="valid",ds_tfms=get_transforms(),size=224
).normalize(imagenet_stats)

Training the custom head

# Training (4 epochs)

learn=cnn_learner(data,models.resnet34,metrics=error_rate)
learn.fit_one_cycle(4)

# Visualizing examples with the highest losses

interp=ClassificationInterpretation.from_learner(learn)
losses,idxs=interp.top_losses()
interp.plot_top_losses(9,figsize=(15,11))

# and the confusion matrix

Fine-tuning the model

I unfreezed previous layers and used different learning rates (with lower rates for earliest layers).

# Training for 2 epochs

# Here is the final confusion matrix

Conclusion

I could reach a relatively low error event though my dataset was pretty small. Better accuracy of the model might be attained using several strategies (i.e data augmentation, alternative model, and so on).

--

--