Using the fastai library in computer vision.
from fastai.vision.all import *

This tutorial highlights on how to quickly build a Learner and fine tune a pretrained model on most computer vision tasks.

Single-label classification

For this task, we will use the Oxford-IIIT Pet Dataset that contains images of cats and dogs of 37 different breeds. We will first show how to build a simple cat-vs-dog classifier, then a little bit more advanced model that can classify all breeds.

The dataset can be downloaded and decompressed with this line of code:

path = untar_data(URLs.PETS)

It will only do this download once, and return the location of the decompressed archive. We can check what is inside with the .ls() method.

path.ls()
(#3) [Path('/home/ashwin/.fastai/data/oxford-iiit-pet/images'),Path('/home/ashwin/.fastai/data/oxford-iiit-pet/models'),Path('/home/ashwin/.fastai/data/oxford-iiit-pet/annotations')]

We will ignore the annotations folder for now, and focus on the images one. get_image_files is a fastai function that helps us grab all the image files (recursively) in one folder.

files = get_image_files(path/"images")
len(files)
7390

Cats vs dogs

To label our data for the cats vs dogs problem, we need to know which filenames are of dog pictures and which ones are of cat pictures. There is an easy way to distinguish: the name of the file begins with a capital for cats, and a lowercased letter for dogs:

files[0],files[6]
(Path('/home/ashwin/.fastai/data/oxford-iiit-pet/images/yorkshire_terrier_102.jpg'),
 Path('/home/ashwin/.fastai/data/oxford-iiit-pet/images/great_pyrenees_102.jpg'))

We can then define an easy label function:

def label_func(f): return f[0].isupper()

To get our data ready for a model, we need to put it in a DataLoaders object. Here we have a function that labels using the file names, so we will use ImageDataLoaders.from_name_func. There are other factory methods of ImageDataLoaders that could be more suitable for your problem, so make sure to check them all in vision.data.

dls = ImageDataLoaders.from_name_func(path, files, label_func, item_tfms=Resize(224))

We have passed to this function the directory we're working in, the files we grabbed, our label_func and one last piece as item_tfms: this is a Transform applied on all items of our dataset that will resize each imge to 224 by 224, by using a random crop on the largest dimension to make it a square, then resizing to 224 by 224. If we didn't pass this, we would get an error later as it would be impossible to batch the items together.

We can then check if everything looks okay with the show_batch method (True is for cat, False is for dog):

dls.show_batch()

Then we can create a Learner, which is a fastai object that combines the data and a model for training, and uses transfer learning to fine tune a pretrained model in just two lines of code:

learn = cnn_learner(dls, resnet34, metrics=error_rate)
learn.fine_tune(1)
epoch train_loss valid_loss error_rate time
0 0.138543 0.023240 0.008119 00:18
epoch train_loss valid_loss error_rate time
0 0.055319 0.017367 0.004736 00:24

The first line downloaded a model called ResNet34, pretrained on ImageNet, and adapted it to our specific problem. It then fine tuned that model and in a relatively short time, we get a model with an error rate of 0.3%... amazing!

If you want to make a prediction on a new image, you can use learn.predict:

learn.predict(files[0])
('False', tensor(0), tensor([9.9970e-01, 2.9784e-04]))

The predict method returns three things: the decoded prediction (here False for dog), the index of the predicted class and the tensor of probabilities that our image is one of a dog (here the model is quite confident!) This method accepts a filename, a PIL image or a tensor directly in this case.

We can also have a look at some predictions with the show_results method:

learn.show_results()

Check out the other applications like text or tabular, or the other problems covered in this tutorial, and you will see they all share a consistent API for gathering the data and look at it, create a Learner, train the model and look at some predictions.

Classifying breeds

To label our data with the breed name, we will use a regular expression to extract it from the filename. Looking back at a filename, we have:

files[0].name
'yorkshire_terrier_187.jpg'

so the class is everything before the last _ followed by some digits. A regular expression that will catch the name is thus:

pat = r'^(.*)_\d+.jpg'

Since it's pretty common to use regular expressions to label the data (often, labels are hidden in the file names), there is a factory method to do just that:

dls = ImageDataLoaders.from_name_re(path, files, pat, item_tfms=Resize(224))

Like before, we can then use show_batch to have a look at our data:

dls.show_batch()

Since classifying the exact breed of cats or dogs amongst 37 different breeds is a harder problem, we will slightly change the definition of our DataLoaders to use data augmentation:

dls = ImageDataLoaders.from_name_re(path, files, pat, item_tfms=Resize(460),
                                    batch_tfms=aug_transforms(size=224))

This time we resized to a larger size before batching, and we add batch_tfms. aug_transforms is a function that provides a collection of data augmentation transforms with defaults we found worked very well on most datasets (you can customize each one by passing the right arguments).

dls.show_batch()

We can then create our Learner exactly as before and train our model.

learn = cnn_learner(dls, resnet34, metrics=error_rate)

We used the default learning rate before, but we might want to find the best one possible. For this, we can use the learning rate finder:

learn.lr_find()
(0.010000000149011612, 0.00363078061491251)

It plots the graph of the learning rate finder and gives us two suggestions (minimum divided by 10 and steepest gradient). Let's use 3e-3 here. We will also do a bit more epochs:

learn.fine_tune(4, 3e-3)
epoch train_loss valid_loss error_rate time
0 1.282734 0.274779 0.085250 00:14
epoch train_loss valid_loss error_rate time
0 0.464303 0.334058 0.102165 00:17
1 0.433266 0.319324 0.094723 00:17
2 0.259503 0.202348 0.066306 00:17
3 0.145520 0.183488 0.060217 00:17

Again, we can have a look at some predictions with show_results:

learn.show_results()

Another thing that is useful is an interpretation object, it can show us where the model made the worse predictions:

interp = Interpretation.from_learner(learn)
interp.plot_top_losses(9, figsize=(15,10))

With the data block API

We can also use the data block API to get our data in a DataLoaders. This is a bit more advanced, so fell free to skip this part if you are not comfortable with learning new API's just yet.

A datablock is built by giving the fastai library a bunch of informations:

  • the types used, through an argument called blocks: here we have images and categories, so we pass ImageBlock and CategoryBlock.
  • how to get the raw items, here our function get_image_files.
  • how to label those items, here with the same regular expression as before.
  • how to split those items, here with a random splitter.
  • the item_tfms and batch_tfms like before.
pets = DataBlock(blocks=(ImageBlock, CategoryBlock), 
                 get_items=get_image_files, 
                 splitter=RandomSplitter(),
                 get_y=using_attr(RegexLabeller(r'(.+)_\d+.jpg$'), 'name'),
                 item_tfms=Resize(460),
                 batch_tfms=aug_transforms(size=224))

The pets object by itself is empty: it only containes the functions that will help us gather the data. We have to call dataloaders method to get a DataLoaders. We pass it the source of the data:

dls = pets.dataloaders(untar_data(URLs.PETS)/"images")

Then we can look at some of our pictures with dls.show_batch()

dls.show_batch(max_n=9)

Multi-label classification

For this task, we will use the Pascal Dataset that contains images with different kinds of objects/persons. It's orginally a dataset for object detection, meaning the task is not only to detect if there is an instance of one class of an image, but to also draw a bounding box around it. Here we will just try to predict all the classes in one given image.

Multi-label classification defers from before in the sense each image does not belong to one category. An image could have a person and a horse inside it for instance. Or have none of the categories we study.

As before, we can download the dataset pretty easily:

path = untar_data(URLs.PASCAL_2007)
path.ls()
(#9) [Path('/home/ashwin/.fastai/data/pascal_2007/valid.json'),Path('/home/ashwin/.fastai/data/pascal_2007/segmentation'),Path('/home/ashwin/.fastai/data/pascal_2007/train.csv'),Path('/home/ashwin/.fastai/data/pascal_2007/test.csv'),Path('/home/ashwin/.fastai/data/pascal_2007/models'),Path('/home/ashwin/.fastai/data/pascal_2007/test'),Path('/home/ashwin/.fastai/data/pascal_2007/train.json'),Path('/home/ashwin/.fastai/data/pascal_2007/train'),Path('/home/ashwin/.fastai/data/pascal_2007/test.json')]

The information about the labels of each image is in the file named train.csv. We load it using pandas:

df = pd.read_csv(path/'train.csv')
df.head()
fname labels is_valid
0 000005.jpg chair True
1 000007.jpg car True
2 000009.jpg horse person True
3 000012.jpg car False
4 000016.jpg bicycle True

Using the high-level API

That's pretty straightforward: for each filename, we get the different labels (separated by space) and the last column tells if it's in the validation set or not. To get this in DataLoaders quickly, we have a factory method, from_df. We can specify the underlying path where all the images are, an additional folder to add between the base path and the filenames (here train), the valid_col to consider for the validation set (if we don't specify this, we take a random subset), a label_delim to split the labels and, as before, item_tfms and batch_tfms.

Note that we don't have to specify the fn_col and the label_col because they default to the first and second column respectively.

dls = ImageDataLoaders.from_df(df, path, folder='train', valid_col='is_valid', label_delim=' ',
                               item_tfms=Resize(460), batch_tfms=aug_transforms(size=224))

As before, we can then have a look at the data with the show_batch method.

dls.show_batch()

Training a model is as easy as before: the same functions can be applied and the fastai library will automatically detect that we are in a multi-label problem, thus picking the right loss function. The only difference is in the metric we pass: error_rate will not work for a multi-label problem, but we can use accuracy_thresh.

learn = cnn_learner(dls, resnet50, metrics=partial(accuracy_multi, thresh=0.5))

As before, we can use learn.lr_find to pick a good learning rate:

learn.lr_find()
(0.025118863582611083, 0.033113110810518265)

We can pick the suggested learning rate and fine-tune our pretrained model:

learn.fine_tune(4, 3e-2)
epoch train_loss valid_loss accuracy_multi time
0 0.429346 0.128341 0.958785 00:15
epoch train_loss valid_loss accuracy_multi time
0 0.161289 0.466793 0.925856 00:17
1 0.167091 0.269290 0.945757 00:16
2 0.145694 0.121434 0.956355 00:17
3 0.118979 0.105355 0.962570 00:17

Like before, we can easily have a look at the results:

learn.show_results()

Or get the predictions on a given image:

learn.predict(path/'train/000005.jpg')
((#1) ['chair'],
 tensor([False, False, False, False, False, False, False, False,  True, False,
         False, False, False, False, False, False, False, False, False, False]),
 tensor([6.0259e-05, 6.2471e-04, 2.9542e-04, 3.7423e-04, 3.9715e-02, 1.9572e-03,
         7.3608e-04, 1.7575e-02, 9.2661e-01, 6.8919e-04, 4.9777e-01, 1.2133e-02,
         1.1415e-03, 1.6763e-03, 1.2275e-01, 7.3525e-02, 5.6224e-04, 2.1502e-01,
         1.7034e-03, 1.4736e-01]))

As for the single classification predictions, we get three things. The last one is the prediction of the model on each class (going from 0 to 1). The second to last cooresponds to a one-hot encoded targets (you get True for all predicted classes, the ones that get a probability > 0.5) and the first is the decoded, readable version.

And like before, we can check where the model did its worse:

interp = Interpretation.from_learner(learn)
interp.plot_top_losses(9)
target predicted probabilities loss
0 chair;diningtable;person;pottedplant person tensor([1.3859e-07, 2.0057e-05, 1.3330e-05, 4.4968e-05, 2.4639e-05, 3.7735e-06,\n 8.4346e-04, 2.1878e-04, 1.1218e-03, 4.2916e-08, 1.4975e-03, 2.5902e-03,\n 2.4724e-05, 1.0664e-05, 9.9991e-01, 3.4751e-03, 1.5933e-05, 5.5496e-04,\n 3.3906e-05, 3.2141e-02]) 0.9498050808906555
1 bottle;person person tensor([1.7861e-12, 2.4931e-09, 1.8502e-09, 1.2212e-09, 1.9618e-08, 1.3690e-11,\n 3.2873e-06, 5.8404e-08, 2.5140e-07, 2.7120e-14, 7.0966e-07, 6.9432e-04,\n 1.1541e-09, 1.0451e-09, 1.0000e+00, 6.0462e-07, 3.4618e-08, 4.7445e-06,\n 4.1124e-09, 9.9111e-04]) 0.8874256014823914
2 bus;car;person person tensor([4.9122e-08, 5.5848e-06, 2.1049e-06, 8.9707e-06, 5.6819e-06, 1.3298e-05,\n 1.4959e-03, 5.9346e-05, 5.3715e-05, 2.1142e-09, 2.5905e-05, 6.1096e-03,\n 5.5608e-06, 3.3048e-06, 9.9968e-01, 5.6836e-05, 6.0220e-06, 2.0087e-04,\n 2.4676e-05, 3.3325e-03]) 0.8871580362319946
3 bottle;person person tensor([5.2528e-13, 1.7562e-09, 3.2824e-10, 1.1594e-09, 2.1161e-08, 1.3134e-11,\n 2.4606e-06, 3.8796e-08, 8.5993e-07, 3.3807e-15, 1.6779e-06, 1.5134e-04,\n 1.5394e-10, 5.9556e-10, 1.0000e+00, 3.3567e-06, 9.9627e-09, 8.0715e-06,\n 2.5843e-09, 4.6214e-03]) 0.8837955594062805
4 bottle;person person tensor([1.8547e-12, 2.8884e-09, 1.6598e-09, 2.4114e-09, 2.3059e-08, 6.5701e-11,\n 3.9855e-06, 4.8739e-08, 8.4072e-07, 1.9686e-14, 2.4176e-06, 3.3824e-04,\n 2.4855e-09, 1.2725e-09, 1.0000e+00, 1.8027e-06, 2.5171e-08, 6.1435e-06,\n 1.4883e-08, 3.2184e-03]) 0.8794390559196472
5 bottle;person person tensor([4.1999e-11, 1.2264e-08, 2.6133e-08, 2.0119e-08, 1.3637e-07, 6.2015e-10,\n 1.6232e-05, 1.7808e-07, 6.3830e-07, 1.1085e-12, 9.6746e-07, 4.1021e-04,\n 1.1263e-08, 1.4854e-08, 9.9999e-01, 2.1052e-06, 1.7178e-07, 8.3955e-06,\n 7.8824e-08, 1.1336e-03]) 0.7904742360115051
6 chair;diningtable;person person tensor([3.2536e-08, 5.8821e-06, 4.8512e-06, 1.5012e-05, 4.5857e-04, 1.0428e-06,\n 2.9736e-04, 4.4146e-05, 4.0318e-04, 3.7364e-09, 4.8184e-04, 1.9579e-03,\n 8.3174e-07, 3.4988e-06, 9.9994e-01, 1.4466e-03, 7.1675e-06, 4.5994e-04,\n 9.3516e-06, 2.8538e-02]) 0.774388313293457
7 bus;person person tensor([3.3093e-08, 3.1500e-06, 5.7413e-06, 3.6701e-06, 2.1493e-05, 3.8484e-07,\n 2.8466e-04, 2.2827e-05, 9.6937e-05, 1.6873e-09, 6.1497e-05, 5.1155e-03,\n 1.3798e-06, 2.3416e-06, 9.9984e-01, 8.3490e-05, 6.5483e-06, 3.6999e-04,\n 5.8180e-06, 8.0087e-03]) 0.7392368316650391
8 bus;car train tensor([1.6565e-03, 4.2173e-04, 3.1245e-04, 1.5796e-03, 2.6684e-04, 9.8883e-03,\n 1.2766e-02, 1.8388e-04, 4.5448e-03, 6.0582e-04, 1.0346e-03, 5.2797e-04,\n 1.3014e-03, 1.6428e-03, 5.4353e-02, 5.3857e-04, 8.4819e-04, 3.2369e-04,\n 9.8810e-01, 6.4698e-04]) 0.674037516117096