{"cells":[{"metadata":{"_uuid":"5d52707f344f0dcfe5baa73532d64fc3456e06c6"},"cell_type":"markdown","source":"## Image classification with Convolutional Neural Networks"},{"metadata":{"_uuid":"c1a51714a4b27163ad6421b9661ba6c872eed83b"},"cell_type":"markdown","source":"Welcome to the first week of the second deep learning certificate! We're going to use convolutional neural networks (CNNs) to allow our computer to see - something that is only possible thanks to deep learning."},{"metadata":{"_uuid":"fe57324f4745fb9d4383198da02a202031625fbb"},"cell_type":"markdown","source":"## Introduction to our first task: 'Dogs vs Cats'"},{"metadata":{"_uuid":"dbac44c46ab037faf84621b6c1a8d582b7ef31a4"},"cell_type":"markdown","source":"We're going to try to create a model to enter the Dogs vs Cats competition at Kaggle. There are 25,000 labelled dog and cat photos available for training, and 12,500 in the test set that we have to try to label for this competition. According to the Kaggle web-site, when this competition was launched (end of 2013): \"State of the art: The current literature suggests machine classifiers can score above 80% accuracy on this task\". So if we can beat 80%, then we will be at the cutting edge as of 2013!"},{"metadata":{"collapsed":true,"_uuid":"acec03a5349f652365134989c150cbdf28ba2076","trusted":true},"cell_type":"code","source":"# Put these at the top of every notebook, to get automatic reloading and inline plotting\n%reload_ext autoreload\n%autoreload 2\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"600da1f542a804eca39699c43f0b3fb4246d8a6e"},"cell_type":"markdown","source":"Here we import the libraries we need. We'll learn about what each does during the course."},{"metadata":{"collapsed":true,"_uuid":"23458afac17c6c5ab691b5bad3e1292082539bfc","trusted":true},"cell_type":"code","source":"# This file contains all the main external libs we'll use\nfrom fastai.imports import *","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"_uuid":"14fa222ea053d567aaeb95f9786449c34bf87617","trusted":true},"cell_type":"code","source":"from fastai.transforms import *\nfrom fastai.conv_learner import *\nfrom fastai.model import *\nfrom fastai.dataset import *\nfrom fastai.sgdr import *\nfrom fastai.plots import *","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"188e90203f18be6de43fd149dbe94af0da40eb03"},"cell_type":"markdown","source":"`PATH` is the path to your data - if you use the recommended setup approaches from the lesson, you won't need to change this. `sz` is the size that the images will be resized to in order to ensure that the training runs quickly. We'll be talking about this parameter a lot during the course. Leave it at `224` for now."},{"metadata":{"collapsed":true,"_uuid":"276daac1c68af55ffc03e89d20c853bdf23e8522","trusted":true},"cell_type":"code","source":"PATH = \"../input/\"\nTMP_PATH = \"/tmp/tmp\"\nMODEL_PATH = \"/tmp/model/\"\nsz=224","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2a6564a6294ee094ba60038c5a94074318f18337"},"cell_type":"markdown","source":"It's important that you have a working NVidia GPU set up. The programming framework used to behind the scenes to work with NVidia GPUs is called CUDA. Therefore, you need to ensure the following line returns `True` before you proceed. If you have problems with this, please check the FAQ and ask for help on [the forums](http://forums.fast.ai)."},{"metadata":{"_uuid":"9ba310c51d959cab508081d01d87a3aaa2ab5085","trusted":true},"cell_type":"code","source":"torch.cuda.is_available()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"13b963795d3ecd9c86cffa9044eaf5145df56e56"},"cell_type":"markdown","source":"In addition, NVidia provides special accelerated functions for deep learning in a package called CuDNN. Although not strictly necessary, it will improve training performance significantly, and is included by default in all supported fastai configurations. Therefore, if the following does not return `True`, you may want to look into why."},{"metadata":{"_uuid":"aeffd45f60ecfcb90aa0cd37f09bbb89cbee8c01","trusted":true},"cell_type":"code","source":"torch.backends.cudnn.enabled","execution_count":null,"outputs":[]},{"metadata":{"heading_collapsed":true,"_uuid":"e7371d1918f4903352b82bb8f4b2ca55fa4386ca"},"cell_type":"markdown","source":"## First look at cat pictures"},{"metadata":{"hidden":true,"scrolled":true,"_uuid":"ee3a6d31ba52de6d1f294998d48b56073ee31604","trusted":true},"cell_type":"code","source":"os.listdir(PATH)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"a9fb6a8048fa18c65800b1865876bf8cccfa0e86","trusted":true,"collapsed":true},"cell_type":"code","source":"fnames = np.array([f'train/{f}' for f in sorted(os.listdir(f'{PATH}train'))])\nlabels = np.array([(0 if 'cat' in fname else 1) for fname in fnames])","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"09f87570c2cd82eb3eed603565240021a5a888fe","trusted":true},"cell_type":"code","source":"img = plt.imread(f'{PATH}{fnames[0]}')\nplt.imshow(img);","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"1d87111c18c0cb0b3326f8e5ff61e18651c13b40"},"cell_type":"markdown","source":"Here is how the raw data looks like"},{"metadata":{"hidden":true,"_uuid":"5ba79cbbb1fbab9dbcbc35834f62a8b024942d2e","trusted":true},"cell_type":"code","source":"img.shape","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"cfef74b040d59c22cb769c6cdfa5cb9cf40066cf","trusted":true},"cell_type":"code","source":"img[:4,:4]","execution_count":null,"outputs":[]},{"metadata":{"heading_collapsed":true,"_uuid":"500f86792c2bd9c9373d883eb301b74219a9b2a7"},"cell_type":"markdown","source":"## Our first model: quick start"},{"metadata":{"hidden":true,"_uuid":"98cddf2e4f8c750fb55756749af75acb62500c73"},"cell_type":"markdown","source":"We're going to use a <b>pre-trained</b> model, that is, a model created by some one else to solve a different problem. Instead of building a model from scratch to solve a similar problem, we'll use a model trained on ImageNet (1.2 million images and 1000 classes) as a starting point. The model is a Convolutional Neural Network (CNN), a type of Neural Network that builds state-of-the-art models for computer vision. We'll be learning all about CNNs during this course.\n\nWe will be using the <b>resnet34</b> model. resnet34 is a version of the model that won the 2015 ImageNet competition. Here is more info on [resnet models](https://github.com/KaimingHe/deep-residual-networks). We'll be studying them in depth later, but for now we'll focus on using them effectively.\n\nHere's how to train and evalulate a *dogs vs cats* model in 3 lines of code, and under 20 seconds:"},{"metadata":{"collapsed":true,"_uuid":"7aa60a8f5fecaf1e2054fbb53029fa881108ea24","trusted":true},"cell_type":"code","source":"# Uncomment the below if you need to reset your precomputed activations\n# shutil.rmtree(f'{PATH}tmp', ignore_errors=True)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"scrolled":false,"_uuid":"34c2f123f94ac01f68f8ab36a2943486fbe35ab5","trusted":true},"cell_type":"code","source":"arch=resnet34\ndata = ImageClassifierData.from_names_and_array(\n    path=PATH, \n    fnames=fnames, \n    y=labels, \n    classes=['dogs', 'cats'], \n    test_name='test', \n    tfms=tfms_from_model(arch, sz)\n)\nlearn = ConvLearner.pretrained(arch, data, precompute=True, tmp_name=TMP_PATH, models_name=MODEL_PATH)\nlearn.fit(0.01, 2)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"3fd2cdb6e89c1163a19008ce233445b192db8d9a"},"cell_type":"markdown","source":"How good is this model? Well, as we mentioned, prior to this competition, the state of the art was 80% accuracy. But the competition resulted in a huge jump to 98.9% accuracy, with the author of a popular deep learning library winning the competition. Extraordinarily, less than 4 years later, we can now beat that result in seconds! Even last year in this same course, our initial model had 98.3% accuracy, which is nearly double the error we're getting just a year later, and that took around 10 minutes to compute."},{"metadata":{"heading_collapsed":true,"_uuid":"17f0e5c8170bbcd4a0371c95d5a136e9674f7c31"},"cell_type":"markdown","source":"## Analyzing results: looking at pictures"},{"metadata":{"hidden":true,"_uuid":"b986461621fef09d1aadfe6c7c04ff21f18eca6e"},"cell_type":"markdown","source":"As well as looking at the overall metrics, it's also a good idea to look at examples of each of:\n1. A few correct labels at random\n2. A few incorrect labels at random\n3. The most correct labels of each class (i.e. those with highest probability that are correct)\n4. The most incorrect labels of each class (i.e. those with highest probability that are incorrect)\n5. The most uncertain labels (i.e. those with probability closest to 0.5)."},{"metadata":{"hidden":true,"_uuid":"942e14027848dcad6d6c80422b5bbf56f63bc1c7","trusted":true},"cell_type":"code","source":"# This is the label for a val data\ndata.val_y","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"6378a93c7e03118e0b12d423d31b2be8f95c1005","trusted":true},"cell_type":"code","source":"# from here we know that 'cats' is label 0 and 'dogs' is label 1.\ndata.classes","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"1326d53d70acad37272afa71c20d6ff39e165c89","trusted":true},"cell_type":"code","source":"# this gives prediction for validation set. Predictions are in log scale\nlog_preds = learn.predict()\nlog_preds.shape","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"b7ff16accb5fa5104de318bd261abcdee72530aa","trusted":true},"cell_type":"code","source":"log_preds[:10]","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"b8709f3bac05d50ee2f7b0b774eb86af8f0f709c","trusted":true},"cell_type":"code","source":"preds = np.argmax(log_preds, axis=1)  # from log probabilities to 0 or 1\nprobs = np.exp(log_preds[:,1])        # pr(dog)","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"37901ee29c7a90714b6385d51eb4126b890f4f8e","trusted":true},"cell_type":"code","source":"def rand_by_mask(mask): return np.random.choice(np.where(mask)[0], 4, replace=False)\ndef rand_by_correct(is_correct): return rand_by_mask((preds == data.val_y)==is_correct)","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"f9de40f3a17b608fb5c4baea893e138c88464fd7","trusted":true},"cell_type":"code","source":"def plots(ims, figsize=(12,6), rows=1, titles=None):\n    f = plt.figure(figsize=figsize)\n    for i in range(len(ims)):\n        sp = f.add_subplot(rows, len(ims)//rows, i+1)\n        sp.axis('Off')\n        if titles is not None: sp.set_title(titles[i], fontsize=16)\n        plt.imshow(ims[i])","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"f64c7bef125f50701884273ed8d161de25b9703b","trusted":true},"cell_type":"code","source":"def load_img_id(ds, idx): return np.array(PIL.Image.open(PATH+ds.fnames[idx]))\n\ndef plot_val_with_title(idxs, title):\n    imgs = [load_img_id(data.val_ds,x) for x in idxs]\n    title_probs = [probs[x] for x in idxs]\n    print(title)\n    return plots(imgs, rows=1, titles=title_probs, figsize=(16,8))","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"9b2fac071b6f72c82cb4a499dffe9dc77b5b57e3","trusted":true},"cell_type":"code","source":"# 1. A few correct labels at random\nplot_val_with_title(rand_by_correct(True), \"Correctly classified\")","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"2380c1cc7a75c19c96a72fdafed058c7fbd92815","trusted":true},"cell_type":"code","source":"# 2. A few incorrect labels at random\nplot_val_with_title(rand_by_correct(False), \"Incorrectly classified\")","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"c0782f2afa83cc74dac7239cb7d6fa5d7f034aab","trusted":true},"cell_type":"code","source":"def most_by_mask(mask, mult):\n    idxs = np.where(mask)[0]\n    return idxs[np.argsort(mult * probs[idxs])[:4]]\n\ndef most_by_correct(y, is_correct): \n    mult = -1 if (y==1)==is_correct else 1\n    return most_by_mask(((preds == data.val_y)==is_correct) & (data.val_y == y), mult)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"127110ef2fedc2f795b08d494adf9ce7d666d88c","trusted":true},"cell_type":"code","source":"plot_val_with_title(most_by_correct(0, True), \"Most correct cats\")","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"c59754e3ca49c83553d7b86959071fd331a3e4f2","trusted":true},"cell_type":"code","source":"plot_val_with_title(most_by_correct(1, True), \"Most correct dogs\")","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"e47ad9fca54f184cf737e77103987ea6d89ebddc","trusted":true},"cell_type":"code","source":"plot_val_with_title(most_by_correct(0, False), \"Most incorrect cats\")","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"5f4b6c4800ce0c32a3619205607e574231b5bae1","trusted":true},"cell_type":"code","source":"plot_val_with_title(most_by_correct(1, False), \"Most incorrect dogs\")","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"3fa2abbbf44c4b364d8415df7566419742935146","trusted":true},"cell_type":"code","source":"most_uncertain = np.argsort(np.abs(probs -0.5))[:4]\nplot_val_with_title(most_uncertain, \"Most uncertain predictions\")","execution_count":null,"outputs":[]},{"metadata":{"heading_collapsed":true,"_uuid":"9881009afc9dae99a579b5d7409dbc662a61b638"},"cell_type":"markdown","source":"## Choosing a learning rate"},{"metadata":{"hidden":true,"_uuid":"14336cf080fda4f6c9ef0f6b1d59367353e3129d"},"cell_type":"markdown","source":"The *learning rate* determines how quickly or how slowly you want to update the *weights* (or *parameters*). Learning rate is one of the most difficult parameters to set, because it significantly affects model performance.\n\nThe method `learn.lr_find()` helps you find an optimal learning rate. It uses the technique developed in the 2015 paper [Cyclical Learning Rates for Training Neural Networks](http://arxiv.org/abs/1506.01186), where we simply keep increasing the learning rate from a very small value, until the loss stops decreasing. We can plot the learning rate across batches to see what this looks like.\n\nWe first create a new learner, since we want to know how to set the learning rate for a new (untrained) model."},{"metadata":{"hidden":true,"_uuid":"5564b4234690421173ae39c0838d84ad119b0d16","trusted":true,"collapsed":true},"cell_type":"code","source":"learn = ConvLearner.pretrained(arch, data, precompute=True, tmp_name=TMP_PATH, models_name=MODEL_PATH)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"scrolled":true,"_uuid":"9c6b0f525504ab510c3b7eb93f86abf57c85780c","trusted":true},"cell_type":"code","source":"lrf=learn.lr_find()","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"406f9a032a24f185b1cff7d746083f98a50db198"},"cell_type":"markdown","source":"Our `learn` object contains an attribute `sched` that contains our learning rate scheduler, and has some convenient plotting functionality including this one:"},{"metadata":{"hidden":true,"_uuid":"6d74efa10daaf966acd3a5d8d0bd625a07f06975","trusted":true},"cell_type":"code","source":"learn.sched.plot_lr()","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"4d12db6775555887d09fa4fdbfbef0395c28b866"},"cell_type":"markdown","source":"Note that in the previous plot *iteration* is one iteration (or *minibatch*) of SGD. In one epoch there are \n(num_train_samples/num_iterations) of SGD.\n\nWe can see the plot of loss versus learning rate to see where our loss stops decreasing:"},{"metadata":{"hidden":true,"_uuid":"8b482b17a6580590ddf2014561fc9052b148637a","trusted":true},"cell_type":"code","source":"learn.sched.plot()","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"701680e992c45ee0cf3e273aef1a9cc2232cf0ec"},"cell_type":"markdown","source":"The loss is still clearly improving at lr=1e-2 (0.01), so that's what we use. Note that the optimal learning rate can change as we train the model, so you may want to re-run this function from time to time."},{"metadata":{"_uuid":"19f87b4870f685b6897b1e918d9e33474d61e5bd"},"cell_type":"markdown","source":"## Improving our model"},{"metadata":{"heading_collapsed":true,"_uuid":"bba9ebcf431f6911b6ee491f4a3efbe5539513cc"},"cell_type":"markdown","source":"### Data augmentation"},{"metadata":{"hidden":true,"_uuid":"37738a8f24efaf49df891f30c7ffa09522dd6fc0"},"cell_type":"markdown","source":"If you try training for more epochs, you'll notice that we start to *overfit*, which means that our model is learning to recognize the specific images in the training set, rather than generalizing such that we also get good results on the validation set. One way to fix this is to effectively create more data, through *data augmentation*. This refers to randomly changing the images in ways that shouldn't impact their interpretation, such as horizontal flipping, zooming, and rotating.\n\nWe can do this by passing `aug_tfms` (*augmentation transforms*) to `tfms_from_model`, with a list of functions to apply that randomly change the image however we wish. For photos that are largely taken from the side (e.g. most photos of dogs and cats, as opposed to photos taken from the top down, such as satellite imagery) we can use the pre-defined list of functions `transforms_side_on`. We can also specify random zooming of images up to specified scale by adding the `max_zoom` parameter."},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"3627c934894df77312bf946dd383d8ed91580ca7","trusted":true},"cell_type":"code","source":"tfms = tfms_from_model(resnet34, sz, aug_tfms=transforms_side_on, max_zoom=1.1)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"3b7e3db8eede987cf9c23a40453e0353e5e9d130","trusted":true,"collapsed":true},"cell_type":"code","source":"def get_augs():\n    data = ImageClassifierData.from_names_and_array(\n        path=PATH, \n        fnames=fnames, \n        y=labels, \n        classes=['dogs', 'cats'], \n        test_name='test', \n        tfms=tfms,\n        num_workers=1,\n        bs=2\n    )\n    x,_ = next(iter(data.aug_dl))\n    return data.trn_ds.denorm(x)[1]","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"8cd403dd064ac1e33733fe7af1effca2c894adef","trusted":true,"collapsed":true},"cell_type":"code","source":"ims = np.stack([get_augs() for i in range(6)])","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"31c0c10e4aa7b1984a7ec72eca5bc1786f4796bb","trusted":true},"cell_type":"code","source":"plots(ims, rows=2)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"08126fb56d6b3e703d33f193f20407a41f8e4acf"},"cell_type":"markdown","source":"Let's create a new `data` object that includes this augmentation in the transforms."},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"0689463ec7e5001677da591f587da2ef99157943","trusted":true},"cell_type":"code","source":"data = ImageClassifierData.from_names_and_array(\n    path=PATH, \n    fnames=fnames, \n    y=labels, \n    classes=['dogs', 'cats'], \n    test_name='test', \n    tfms=tfms\n)\nlearn = ConvLearner.pretrained(arch, data, precompute=True, tmp_name=TMP_PATH, models_name=MODEL_PATH)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"scrolled":false,"_uuid":"7e36bc862b4b7b927a64d41ec5f17b5d431e0303","trusted":true},"cell_type":"code","source":"learn.fit(1e-2, 1)","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"ab745a8ac2c0ac1ed0a3103e536785ef668dd749","trusted":true},"cell_type":"code","source":"learn.precompute=False","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"5ebcae9477b240a02026779ef51f2b1e591719ac"},"cell_type":"markdown","source":"By default when we create a learner, it sets all but the last layer to *frozen*. That means that it's still only updating the weights in the last layer when we call `fit`."},{"metadata":{"hidden":true,"scrolled":false,"_uuid":"8ce740cf07ae3d41f84fbb9ea83fc48b7f31d150","trusted":true},"cell_type":"code","source":"learn.fit(1e-2, 3, cycle_len=1)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"346f9a8c8b4b05e56941ea2f6cac954f3f84c198"},"cell_type":"markdown","source":"What is that `cycle_len` parameter? What we've done here is used a technique called *stochastic gradient descent with restarts (SGDR)*, a variant of *learning rate annealing*, which gradually decreases the learning rate as training progresses. This is helpful because as we get closer to the optimal weights, we want to take smaller steps.\n\nHowever, we may find ourselves in a part of the weight space that isn't very resilient - that is, small changes to the weights may result in big changes to the loss. We want to encourage our model to find parts of the weight space that are both accurate and stable. Therefore, from time to time we increase the learning rate (this is the 'restarts' in 'SGDR'), which will force the model to jump to a different part of the weight space if the current area is \"spikey\". Here's a picture of how that might look if we reset the learning rates 3 times (in this paper they call it a \"cyclic LR schedule\"):\n\n<img src=\"images/sgdr.png\" width=\"80%\">\n(From the paper [Snapshot Ensembles](https://arxiv.org/abs/1704.00109)).\n\nThe number of epochs between resetting the learning rate is set by `cycle_len`, and the number of times this happens is refered to as the *number of cycles*, and is what we're actually passing as the 2nd parameter to `fit()`. So here's what our actual learning rates looked like:"},{"metadata":{"hidden":true,"_uuid":"56de6b06af18a856a076de6d1eed1945b268a07a","trusted":true},"cell_type":"code","source":"learn.sched.plot_lr()","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"f9f0745a19a6ade9de4588ee65c2a7065fc40ed9"},"cell_type":"markdown","source":"Our validation loss isn't improving much, so there's probably no point further training the last layer on its own."},{"metadata":{"hidden":true,"_uuid":"7e3fc80daed27e97c2299a0bf8d4cad409e5c788"},"cell_type":"markdown","source":"Since we've got a pretty good model at this point, we might want to save it so we can load it again later without training it from scratch."},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"e8dab6b7777e0a41c50934b155ab6eedab6a76f2","trusted":true},"cell_type":"code","source":"learn.save('224_lastlayer')","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"cf96b675d212554de2a045b495d479e2b210cd9a","trusted":true},"cell_type":"code","source":"learn.load('224_lastlayer')","execution_count":null,"outputs":[]},{"metadata":{"heading_collapsed":true,"_uuid":"e4887b3912cdbee010acf5482b03b568c83bcc73"},"cell_type":"markdown","source":"### Fine-tuning and differential learning rate annealing"},{"metadata":{"hidden":true,"_uuid":"a65f823c7c6ec90b6968674bd198ff1bcf6feac4"},"cell_type":"markdown","source":"Now that we have a good final layer trained, we can try fine-tuning the other layers. To tell the learner that we want to unfreeze the remaining layers, just call (surprise surprise!) `unfreeze()`."},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"fd878a989d38240f8a49075e4e14d60d71f9fdbd","trusted":true},"cell_type":"code","source":"learn.unfreeze()","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"02fe74dfb7127c5e89b49be653f5511faf35b80f"},"cell_type":"markdown","source":"Note that the other layers have *already* been trained to recognize imagenet photos (whereas our final layers where randomly initialized), so we want to be careful of not destroying the carefully tuned weights that are already there.\n\nGenerally speaking, the earlier layers (as we've seen) have more general-purpose features. Therefore we would expect them to need less fine-tuning for new datasets. For this reason we will use different learning rates for different layers: the first few layers will be at 1e-4, the middle layers at 1e-3, and our FC layers we'll leave at 1e-2 as before. We refer to this as *differential learning rates*, although there's no standard name for this techique in the literature that we're aware of."},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"bbcf5aa0a288af99cbaa0b548431863e1600e6cd","trusted":true},"cell_type":"code","source":"lr=np.array([1e-4,1e-3,1e-2])","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"scrolled":false,"_uuid":"23dc5be9566216982d8caf86c69d423968e2fdb7","trusted":true},"cell_type":"code","source":"learn.fit(lr, 3, cycle_len=1, cycle_mult=2)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"036723d06133d8f64e5a49706deee1b4cb701daf"},"cell_type":"markdown","source":"Another trick we've used here is adding the `cycle_mult` parameter. Take a look at the following chart, and see if you can figure out what the parameter is doing:"},{"metadata":{"hidden":true,"_uuid":"4d306aaf497e76140674b7aa60e9e59b33c335d4","trusted":true},"cell_type":"code","source":"learn.sched.plot_lr()","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"5a2a8416aa9055d83bc705cce15c4131854873b9"},"cell_type":"markdown","source":"Note that's what being plotted above is the learning rate of the *final layers*. The learning rates of the earlier layers are fixed at the same multiples of the final layer rates as we initially requested (i.e. the first layers have 100x smaller, and middle layers 10x smaller learning rates, since we set `lr=np.array([1e-4,1e-3,1e-2])`."},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"7a7040e56743d89bd6a4e26f1f93a6b13660087e","trusted":true},"cell_type":"code","source":"learn.save('224_all')","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"d7ec35d73d1cf40e4f8f49fd82429136787214fa","trusted":true},"cell_type":"code","source":"learn.load('224_all')","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"cb6102e09fd3c172d9f3ff644b97a6fa488b24c9"},"cell_type":"markdown","source":"There is something else we can do with data augmentation: use it at *inference* time (also known as *test* time). Not surprisingly, this is known as *test time augmentation*, or just *TTA*.\n\nTTA simply makes predictions not just on the images in your validation set, but also makes predictions on a number of randomly augmented versions of them too (by default, it uses the original image along with 4 randomly augmented versions). It then takes the average prediction from these images, and uses that. To use TTA on the validation set, we can use the learner's `TTA()` method."},{"metadata":{"hidden":true,"_uuid":"455b5b3f31f3b3f51773f3d7f3bb7752b9fa28bc","trusted":true},"cell_type":"code","source":"log_preds,y = learn.TTA()\nprobs = np.mean(np.exp(log_preds),0)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"cfdd304ce317bc907af404f30546572da3d2a220","trusted":true},"cell_type":"code","source":"accuracy_np(probs, y)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"fcb92d519aaa2d5a8982a6f7c280ec6ee6a0916d"},"cell_type":"markdown","source":"I generally see about a 10-20% reduction in error on this dataset when using TTA at this point, which is an amazing result for such a quick and easy technique!"},{"metadata":{"_uuid":"3068e3a8473a2c1ac558780c107d0158bd338e51"},"cell_type":"markdown","source":"## Analyzing results"},{"metadata":{"heading_collapsed":true,"_uuid":"667093c0f80a6477a5d25c4fbe3f0e071a9520ab"},"cell_type":"markdown","source":"### Confusion matrix "},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"d9a8432f73faf42db4d6cd386a07667b6d813b59","trusted":true},"cell_type":"code","source":"preds = np.argmax(probs, axis=1)\nprobs = probs[:,1]","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"5c75497abd825d42fb477f3e869d79c332f8aeba"},"cell_type":"markdown","source":"A common way to analyze the result of a classification model is to use a [confusion matrix](http://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/). Scikit-learn has a convenient function we can use for this purpose:"},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"8b014d4a3e735cafdb1aa8d53d2dc6847be12367","trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y, preds)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"e1efa2ca5de43c3c212ac4ee12e9f9d90eae4598"},"cell_type":"markdown","source":"We can just print out the confusion matrix, or we can show a graphical view (which is mainly useful for dependents with a larger number of categories)."},{"metadata":{"hidden":true,"_uuid":"8b005778bedce93b8c9754d1fed58c98404f553d","trusted":true},"cell_type":"code","source":"plot_confusion_matrix(cm, data.classes)","execution_count":null,"outputs":[]},{"metadata":{"heading_collapsed":true,"_uuid":"22ca13a90fe2dda24234ae5bc7d2a712d740d03f"},"cell_type":"markdown","source":"### Looking at pictures again"},{"metadata":{"hidden":true,"_uuid":"2c1c45c78ce3e9fa4b94b5fb0b232142cc8cbc8d","trusted":true},"cell_type":"code","source":"plot_val_with_title(most_by_correct(0, False), \"Most incorrect cats\")","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"fbb1f131b8f1abb95223a5850f37991fe918ac27","trusted":true},"cell_type":"code","source":"plot_val_with_title(most_by_correct(1, False), \"Most incorrect dogs\")","execution_count":null,"outputs":[]},{"metadata":{"heading_collapsed":true,"_uuid":"3e3db3bd9fe817641063ff0e37bfb4bcf6b33967"},"cell_type":"markdown","source":"## Review: easy steps to train a world-class image classifier"},{"metadata":{"hidden":true,"_uuid":"54eef5b76bc4e37be5aee47b7eab68fe04bea567"},"cell_type":"markdown","source":"1. precompute=True\n1. Use `lr_find()` to find highest learning rate where loss is still clearly improving\n1. Train last layer from precomputed activations for 1-2 epochs\n1. Train last layer with data augmentation (i.e. precompute=False) for 2-3 epochs with cycle_len=1\n1. Unfreeze all layers\n1. Set earlier layers to 3x-10x lower learning rate than next higher layer\n1. Use `lr_find()` again\n1. Train full network with cycle_mult=2 until over-fitting"},{"metadata":{"heading_collapsed":true,"_uuid":"31140b1c0297d19384efb837711bc33681865aa7"},"cell_type":"markdown","source":"## Understanding the code for our first model"},{"metadata":{"hidden":true,"_uuid":"b25762f95ea64a6f9fafdc92e045774e060a4815"},"cell_type":"markdown","source":"Let's look at the Dogs v Cats code line by line.\n\n**tfms** stands for *transformations*. `tfms_from_model` takes care of resizing, image cropping, initial normalization (creating data with (mean,stdev) of (0,1)), and more."},{"metadata":{"collapsed":true,"hidden":true,"scrolled":true,"_uuid":"712901eb7d1065e6b942fa38e44b39b9e991e0a4","trusted":true},"cell_type":"code","source":"tfms = tfms_from_model(resnet34, sz)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"fcd6f2de7e5b05bbe632db5ef8542b3a3846c513"},"cell_type":"markdown","source":"We need a <b>path</b> that points to the dataset. In this path we will also store temporary data and final results. `ImageClassifierData.from_names_and_array` takes in the names of the image files as well as an array of ground-truth labels and creates a dataset ready for training."},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"3ceff3244a2c6968ab015303f402d9ea52ddd78b","trusted":true},"cell_type":"code","source":"data = ImageClassifierData.from_names_and_array(\n    path=PATH, \n    fnames=fnames, \n    y=labels, \n    classes=['dogs', 'cats'], \n    test_name='test', \n    tfms=tfms\n)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"51e3570dd17c5f6f4200f71c97eee9660f45b5cc"},"cell_type":"markdown","source":"`ConvLearner.pretrained` builds *learner* that contains a pre-trained model. The last layer of the model needs to be replaced with the layer of the right dimensions. The pretained model was trained for 1000 classes therfore the final layer predicts a vector of 1000 probabilities. The model for cats and dogs needs to output a two dimensional vector. The diagram below shows in an example how this was done in one of the earliest successful CNNs. The layer \"FC8\" here would get replaced with a new layer with 2 outputs.\n\n<img src=\"https://image.slidesharecdn.com/practicaldeeplearning-160329181459/95/practical-deep-learning-16-638.jpg\" width=\"500\">\n[original image](https://image.slidesharecdn.com/practicaldeeplearning-160329181459/95/practical-deep-learning-16-638.jpg)"},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"b5abef3ef44a93301d0bfd6ad96b7f18d1317463","trusted":true},"cell_type":"code","source":"learn = ConvLearner.pretrained(resnet34, data, precompute=True, tmp_name=TMP_PATH, models_name=MODEL_PATH)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"0ad6dd4ebc10ad532f13277dc3dd45fa10629309"},"cell_type":"markdown","source":"*Parameters*  are learned by fitting a model to the data. *Hyperparameters* are another kind of parameter, that cannot be directly learned from the regular training process. These parameters express “higher-level” properties of the model such as its complexity or how fast it should learn. Two examples of hyperparameters are the *learning rate* and the *number of epochs*.\n\nDuring iterative training of a neural network, a *batch* or *mini-batch* is a subset of training samples used in one iteration of Stochastic Gradient Descent (SGD). An *epoch* is a single pass through the entire training set which consists of multiple iterations of SGD.\n\nWe can now *fit* the model; that is, use *gradient descent* to find the best parameters for the fully connected layer we added, that can separate cat pictures from dog pictures. We need to pass two hyperameters: the *learning rate* (generally 1e-2 or 1e-3 is a good starting point, we'll look more at this next) and the *number of epochs* (you can pass in a higher number and just stop training when you see it's no longer improving, then re-run it with the number of epochs you found works well.)"},{"metadata":{"hidden":true,"_uuid":"05ab7b6bf9ecfadc3470960db1770aafc7ec9f32","trusted":true},"cell_type":"code","source":"learn.fit(1e-2, 1)","execution_count":null,"outputs":[]},{"metadata":{"heading_collapsed":true,"_uuid":"1c8befa45315236b9d6dd4a914dc0f92e796539e"},"cell_type":"markdown","source":"## Analyzing results: loss and accuracy"},{"metadata":{"hidden":true,"_uuid":"3b04656ea2ab9401544240311d337f5978c18b51"},"cell_type":"markdown","source":"When we run `learn.fit` we print 3 performance values (see above.) Here 0.03 is the value of the **loss** in the training set, 0.0226 is the value of the loss in the validation set and 0.9927 is the validation accuracy. What is the loss? What is accuracy? Why not to just show accuracy?\n\n**Accuracy** is the ratio of correct prediction to the total number of predictions.\n\nIn machine learning the **loss** function or cost function is representing the price paid for inaccuracy of predictions.\n\nThe loss associated with one example in binary classification is given by:\n`-(y * log(p) + (1-y) * log (1-p))`\nwhere `y` is the true label of `x` and `p` is the probability predicted by our model that the label is 1."},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"bb2a64cd874109173e3b1d4cf1d4e6bc05901025","trusted":true},"cell_type":"code","source":"def binary_loss(y, p):\n    return np.mean(-(y * np.log(p) + (1-y)*np.log(1-p)))","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"2f9fce27e3cd2184b9e7843616cb5c47dcece24b","trusted":true},"cell_type":"code","source":"acts = np.array([1, 0, 0, 1])\npreds = np.array([0.9, 0.1, 0.2, 0.8])\nbinary_loss(acts, preds)","execution_count":null,"outputs":[]},{"metadata":{"hidden":true,"_uuid":"8ff2a3bf035280ba414708c6615e15a09b0ebe05"},"cell_type":"markdown","source":"Note that in our toy example above our accuracy is 100% and our loss is 0.16. Compare that to a loss of 0.03 that we are getting while predicting cats and dogs. Exercise: play with `preds` to get a lower loss for this example. \n\n**Example:** Here is an example on how to compute the loss for one example of binary classification problem. Suppose for an image x with label 1 and your model gives it a prediction of 0.9. For this case the loss should be small because our model is predicting a label $1$ with high probability.\n\n`loss = -log(0.9) = 0.10`\n\nNow suppose x has label 0 but our model is predicting 0.9. In this case our loss should be much larger.\n\nloss = -log(1-0.9) = 2.30\n\n- Exercise: look at the other cases and convince yourself that this make sense.\n- Exercise: how would you rewrite `binary_loss` using `if` instead of `*` and `+`?\n\nWhy not just maximize accuracy? The binary classification loss is an easier function to optimize."},{"metadata":{"collapsed":true,"hidden":true,"_uuid":"288b455ed693196360ce02d77bcf321cc0d76ede","trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"toc":{"colors":{"hover_highlight":"#DAA520","navigate_num":"#000000","navigate_text":"#333333","running_highlight":"#FF0000","selected_highlight":"#FFD700","sidebar_border":"#EEEEEE","wrapper_background":"#FFFFFF"},"moveMenuLeft":true,"nav_menu":{"height":"266px","width":"252px"},"navigate_menu":true,"number_sections":true,"sideBar":true,"threshold":4,"toc_cell":false,"toc_section_display":"block","toc_window_display":false,"widenNotebook":false}},"nbformat":4,"nbformat_minor":1}