<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rakesh Sukumar on Medium]]></title>
        <description><![CDATA[Stories by Rakesh Sukumar on Medium]]></description>
        <link>https://medium.com/@rakesh.sukumar88?source=rss-6ca79b036138------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*LLit1oK9OML6u83g.jpg</url>
            <title>Stories by Rakesh Sukumar on Medium</title>
            <link>https://medium.com/@rakesh.sukumar88?source=rss-6ca79b036138------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:52:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rakesh.sukumar88/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding FastAI v2 Training with a Computer Vision Example- Part 3: FastAI Learner and…]]></title>
            <link>https://medium.com/analytics-vidhya/understanding-fastai-v2-training-with-a-computer-vision-example-part-3-fastai-learner-and-a3ea85c6fe78?source=rss-6ca79b036138------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3ea85c6fe78</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rakesh Sukumar]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 19:20:18 GMT</pubDate>
            <atom:updated>2020-10-21T12:25:06.202Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding FastAI v2 Training with a Computer Vision Example- Part 3: FastAI Learner and Callbacks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hc2LV0GFMaYQ47wH2w0lBg.png" /><figcaption>Image Source: <a href="https://images.app.goo.gl/juHhyxgoGhUPRNY38">https://images.app.goo.gl/juHhyxgoGhUPRNY38</a></figcaption></figure><p>This is my third article in this series. This series is aimed at those who are already familiar with FastAI and want to dig a little deeper and understand what is happening behind the scene. In this article, we will use the resnet model built in the first article to understand FastAI Learner &amp; Callbacks. The overall structure of this series is as below:</p><ol><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-1-the-resnet-model-dd9270450bb8">Study the resnet34 model architecture and build it using plain Python &amp; PyTorch</a>.</li><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-2-fastai-optimizers-df65cb018604">Deep dive into FastAI optimizers &amp; implement a NAdam optimizer.</a></li><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-3-fastai-learner-and-a3ea85c6fe78">Study FastAI Learner and Callbacks &amp; implement a learning rate finder (lr_find method) with callbacks.</a></li></ol><p>We will use Google Colab to run our code. You can find the code files for this article <a href="https://github.com/Rakeshsuku/Medium-Blog/tree/master/Understanding%20FastAI%20v2%20Training"><em>here</em></a>. Let’s get started..!</p><p>First, we will quickly recreate our model from the first article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIcSODYOU68lm11j_-nzlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdxDDTY2pdRYRwBfnqRcoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FR-x0EBGV5yaKz9sk6PAew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ANM1dJOlgZPkRtNiAHmvLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leKcOEcCIgyL0TPHO3S4cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_3vHJwuHIr-HdTaHvVBFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcIjVyIPH7SwicPaLVcNrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBT4GDJdjhxa1LHUGm14eQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xudrObzeoroHIbeTu9JURw.png" /></figure><p>Let’s create a learner using our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ko6QSXIo_8Dgp7MHJfplQQ.png" /></figure><p>Let’s understand the arguments to the Leaner constructor:</p><ul><li>dls: The dataloaders object containing training &amp; validation data.</li><li>model: The neural network model.</li><li>loss_func: The loss function to be used. If no loss function is specified, the default loss function for the data loaders object is used. The dataloader object selects an appropriate loss function based on the type of the target. Here, since we have used a <em>CategoryBlock </em>(see dblock creation above)<em> for </em>our target variable, CrossEntropyLoss is added as the default loss function. FastAI has a good tutorial on creating custom the loss functions <a href="https://docs.fast.ai/tutorial.imagenette#Changing-the-loss-function"><em>here</em></a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BblAQmNpT7w-7mtXsB421w.png" /></figure><ul><li>opt_func: Function(Callable) used to create the optimizer object. By default an Adam optimizer is added.</li><li>lr: Default learning rate.</li><li>splitter: A function that takes the model as input and returns a list of parameter groups. The default function ‘<em>trainable_param()</em>’ returns all trainable parameters of the model (parameters for which requires_grad = True) as a single list creating a single parameter group.</li><li>cbs: A list of callbacks to customize the training loop. By default, FastAI adds the following callbacks to the learner: <em>TrainEvalCallback</em>, <em>Recorder</em> and <em>ProgressCallback</em>. We will study learner callbacks in details in this article.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZ_bItVRtSg_vpLhOf3ZFA.png" /></figure><ul><li>metrics: An optional list of metrics, that can be either functions or an object of FastAI Metric class. No metrics are selected by default.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1a8pOVDugk_OjUCJToNCCw.png" /></figure><ul><li>path &amp; model_dir: path and model_dir are used to save and/or load models.</li><li>wd: Default weight decay used.</li><li>moms: Default momentum used in learn.fit_one_cycle() method.</li><li>wd_bn_bias: Controls if weight decay is applied to batchnorm type layers &amp; bias parameters. Default behavior is not to apply wd for these layers.</li><li>train_bn: Controls if batchnorm type layers are to be trained even if they belong to the frozen part of the model. The default behavior is to train batchnorm type layers.</li></ul><p><strong>FastAI Training Loop</strong></p><p>We will use the learn.fit() method to study the FastAI training loop. Let’s train our model for 1 epoch for a reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNBzFaqM1ObBGbfQFQxVMA.png" /></figure><p>Let’s look at the arguments for learn.fit() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ep0yVXsN9bK3ybBZNeWqlA.png" /></figure><p>The learn.fit() method accepts the following arguments:</p><ul><li>n_epoch: the number of epochs for which the model must be trained</li><li>lr &amp; wd: the learning rate &amp; weight decay to be used by the optimizer</li><li>cbs: Any additional callback to be added to the learner for the fit operations. Note that this in addition to the callbacks added with the learner constructor. These callbacks will be removed from the learner object after the fit() operation.</li><li>reset_opt: A Boolean flag to indicate if the optimizer associated with learner object needs to be reset.</li></ul><p>A fit operations (learn.fit() method call) consists of <em>n_epoch</em> epochs through the dataset. An epoch consists of one full iteration through the training dataset followed by a full iteration through the validation dataset. FastAI uses events &amp; exceptions for control flow. There are five event types &amp; associated exceptions (the exceptions are provided in brackets) in a FastAI fit operation:</p><ol><li>fit (CancelFitException)</li><li>epoch (CancelEpochException)</li><li>train (CancelTrainException)</li><li>validate (CancelValidException)</li><li>batch (CancelBatchException)</li></ol><p>These event types have the following events associated with them:</p><ul><li>before_{event_type}</li><li>after_cancel_{event_type}</li><li>after_{event_type}.</li></ul><p>The control flow for these event types is as follows (see the figure below for a better understanding):</p><ol><li><em>before_{event_type}</em> event. I will explain the control flow for an event later.</li><li>Call a function/method associated with the event type.</li><li><em>after_cancel_{event_type}</em> event, if the associated exception is raised during step 1. Note that only step 2 is skipped if the exception occurs during step 1.</li><li><em>after_{event_type}</em> event. Step 4 &amp; 5 are always run, even if the exception is raised during step 1.</li><li>An optional ‘<em>final</em>’ function can be run at the end of the event type. In learn.fit() method call, only the ‘<em>fit</em>’ event type has a ‘<em>final</em>’ function (<em>self._end_cleanup()</em>) associated with it(see the below figure).</li></ol><p>In addition to above events, FastAI also has the following events that are encountered for every batch during a training/validation/inference run.</p><ul><li><em>after_pred</em></li><li><em>after_loss</em></li><li><em>before_backward</em> (only for training run)</li><li><em>after_backwar</em>d (only for training run)</li><li><em>after_step</em> (only for training run)</li></ul><p>An event calls the learner object passing in the event name (example: ‘after_pred’ event calls learn(‘after_pred’)). I will explain the control flow for an event in details later. First let’s study the fit operation. The control flow during the fit() operation is best explained with the below figure. Note that if no exception occurs during the <em>before_{event type}</em> event, the associated method is executed and the control passes to <em>after_{event type}</em> event. However, if a <em>Cancel{event type}Exception</em> is raised during <em>before_{event type}, </em>the associated method is skipped &amp; the control passes to <em>after_cancel_{event type}</em> event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCqbw_9Qk6lLbWOn1KrhYg.png" /><figcaption>Control flow during a FastAI fit operation. Note that if no exception occurs during the before_{event type} event, the associated method is executed and the control passes to after_{event type} event. However, if a Cancel{event type}Exception is raised during before_{event type} event, the associated method is skipped &amp; the control passes to after_cancel_{event type} event.</figcaption></figure><p>I will briefly explain what each of these methods/events does. Note that ‘learn’/’self’ below refers to the learner object .</p><ol><li>learn.fit(): The learn.fit() method creates a context with additional callbacks (passed to the fit method) added to the learner object. This ensures that the additional callbacks are removed from the learner after the execution of the fit() method. Next, it creates a new optimizer object if an optimizer object is not already associated with the learner object or if <em>reset_opt </em>argument<em> </em>is True. It then stores <em>n_epoch </em>as an attribute of the learner object and initializes loss value <em>learn.loss </em>with<em> </em>torch.Tensor([0.]). Next, it initiates the control flow for ‘<em>fit’</em> event type starting with the ‘<em>before_fit’</em> event.</li><li>before_fit: before_fit event calls learn(‘before_fit’)</li><li>learn._do_fit(): Initiates a for loop to train the model for <em>learn.n_epoch</em> epochs. For each iteration, stores the current epoch number as <em>learn.epoch</em> and initiates the control flow for ‘<em>epoch</em>’ event type starting with ‘<em>before_epoch</em>’ event.</li><li>before_epoch: before_epoch event calls learn(‘before_epoch’)</li><li>self._do_epoch(): First calls self._do_epoch_train() to run 1 epoch on training dataset then calls self._do_epoch_validate() to run 1 epoch (compute loss &amp; metrics) on validation dataset.</li><li>self._do_epoch_train(): Sets training dataloader as <em>self.dl</em> and initiates the control flow for ‘<em>train</em>’ event type starting with ‘<em>before_train</em>’ event. After the execution completes the ‘<em>train</em>’ event type, self._do_epoch_validate() is called which sets the validation dataloader as <em>self.dl </em>and initiates the control flow for ‘<em>validate</em>’ event type with torch.no_grad() so that gradient calculations are disabled for the validation run. Note that self._do_epoch_validate() method is also used at inference time in learn.predict() call to get predictions for new samples.</li><li>before_train: before_train calls learn(‘before_train’).</li><li>self.all_batches(): Sets <em>self.n_iter</em> to the length (i.e. no of batches) of self.dl. Note that self.dl is set to training data loader during the training run (event type: ‘<em>train</em>’) and validation dataloader during the validation run (event type: ‘<em>validate</em>’). Next, it calls self.one_batch(i, b) on each i, and batch ‘b’ in enumerate(<em>self.dl)</em>.</li><li>self.one_batch(i, b): Sets ‘i’ as <em>self.ite</em>r and splits the batch ‘b’ as <em>self.xb -</em> the input and <em>self.yb </em>- the target. Then, it initiates the control flow for ‘<em>batch</em>’ event type starting with ‘<em>before_batch</em>’ event.</li><li>before_batch: before_batch call learn(‘before_batch’)</li><li>self._do_one_batch(): self._do_one_batch() does the following:</li></ol><p>(i) Get’s the prediction for the batch and stores it to self.pred</p><p>(ii) after_pred: Calls learn(‘after_pred’)</p><p>(iii) Computes loss by calling self.loss_func() &amp; stores it to self.loss</p><p>(iv) after_loss: Calls learn(‘after_loss’).</p><p>(v) before_backward: Calls learn(‘before_backward’). (v) to (ix) are executed only for the training run.</p><p>(vi)self._backward(): Computes gradients by calling self.loss.backward()</p><p>(vii)after_backward: Calls learn(‘after_backward’)</p><p>(vii)self._step(): Calls self.opt.step() to update the parameters.</p><p>(viii)after_step: Calls learn(‘after_step’)</p><p>(ix) self.opt.zero_grad(): Zeroes the gradients.</p><p>12. self._end_cleanup(): Called at the end of the fit event type to reset <em>self.xb, self.yb, self.dl, self.pred</em> and <em>self.loss</em>.</p><p>Let’s look at the control flow during an event, when learn(‘event-name’) is called.</p><p><strong>Control for flow during an Event</strong></p><p>FastAI does the following when learn(‘event-name’) is called:</p><ol><li>Get all callbacks associated with the learner object.</li><li>Sort the callbacks in the correct order. (I ‘ll explain the sorting logic shortly). You can check the sorted order of callbacks using sort_by_run() function.</li><li>For each callback (let’s say cb) in the sorted list, run the method with the same name as ‘event-name’ (i.e. cb.‘event-name’) if the callback has a such a method and if it satisfies any of the following 3 conditions:</li></ol><p>(i) (cb.run = True) AND (event-name is one of the *<em>inner_events</em>)</p><p>(ii) (cb.run = True) AND (cb.run_train = True) AND (learn.training = True, if learn has a “training” attribute.)</p><p>(iii) (cb.run = True) AND (cb.run_valid = True) AND (learn.training = False, if learn has a “training” attribute)</p><p><em>inner_events: </em>before_batch, after_pred, after_loss, before_backward, after_backward, after_step, after_cancel_batch, and after_batch.</p><p>The callback attributes cb.run, cb.run_valid and cb.run_train can be used to enable/diable the callback and they are all set to True by default. As the name indicates, the attributes ‘run_train’ and ‘run_valid’ can be used to run the callback selectively during training or validation/inference respectively. Also, note that cb.run attribute is reset to True at the end of a fit operation during the ‘after_fit’ event.</p><p><strong>Callback sorting logic:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KozLSOwXJrE9PkLHwrLL-g.png" /><figcaption>Sorted order of callbacks</figcaption></figure><ol><li>Get the list of callbacks, lets call it ‘cbs’. Create an empty list, say ‘res’, as a placeholder to stored the sorted callbacks.</li><li>Move all callbacks with ‘toward_end’ attribut = True to the end of cbs.</li><li>For each callback ‘cb’ in cbs, starting from the first one, check if cb has a ‘run_after’ attribute, if yes, check if cb.run_after is equal to any other callback in cbs.</li><li>For all other callbacks ‘o’ in cbs, check if o has a ‘run_before’ attribute, if yes, check if o.run_before is equal to cb.</li><li>If the answer to both 3 and 4 are False, add (append) cb to the sorted list ‘res’. Repeat 3 to 5 until all callbacks are moved to res.</li></ol><p>We can use the learn.show_training_loop() method to see the events &amp; callbacks during a fit operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUvSHUhd8N8QZDG4E5dg-g.png" /></figure><p>Now, let’s try to implement our own LRFinder callback. As usual I have copied most of the code below from FastAI’s github repo.</p><h3><strong>LR_Finder Callback</strong></h3><p>We want the lr finder callback to do the following:</p><ul><li>The lr finder should not disturb the weights initialization, hence the lr finder callback should first save the model parameters to a local file before it starts and should reload it back at end.</li><li>The lr finder should run the fit for 100 iterations (batches) max using exponentially increasing learning rates, hence it should find the appropriate number of epochs to run the fit.</li><li>Set up an exponentially increasing learning rate schedule.</li><li>Cancel the training if the number of iterations &gt; 100 or if the loss increases above 4 times the best loss obtained.</li><li>Zero the gradients at the end of fit operation.</li><li>Create a plot of loss vs learning rate after the fit operation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLcCenDO9_5EHkZ5oASrlg.png" /></figure><p>Next, we will add a custom method to the learner to run our callback. @patch is a FastAI decorator to add a method to the type-annotation class of the first argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hirmyHBgwfOGujjPAzpsw.png" /></figure><p>Let’s use our lr_find method now. But first we will re-initialize the model weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8F_Fq5woLNCRLQ6cG9Uk3Q.png" /></figure><p>We will now try to use our learning rate finder in a transfer learning setting. We will use the Pets dataset and download FastAI’s xresnet model pretrained on Imagenet data. I decided not use our model trained on Imagenette data as we only had a single dog breed in our target class (for Imagenette data).</p><p>First let’s build the dataloaders for Pets dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LecMj7B9ulUtLKvY_g3ibw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVQ88wD1SeMDAHySGgz_8w.png" /></figure><p>We have 37 dog and cat breeds in Pets dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7_BCpjn9ysZ-Q6mQZcbUA.png" /></figure><p>Let’s download the pretrained xresnet34 model from FastAI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bitIVYYFAPfc7VFmOjkfPw.png" /></figure><p>By default, FastAI cuts a pretrained model at the pooling layer and adds a custom head according to the number of target classes. See the documentation for <a href="https://docs.fast.ai/vision.learner">Vision Learner here</a> for details. Let’s replicate the same for our study. First we will create a ‘head’ for our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBZ7ewiUH92W-NMWAcyQlA.png" /></figure><p>We will initialize the parameters of the head before joining it with the pretrained part of the model as we do not want to modify the pretrained parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiMKcFnyTL0ilqNXGhSIog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwxdRHgEY8yxtdm71x6HjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdI67INpV1Ayhy7Lvu3FoQ.png" /><figcaption>Note: I am only showing the top &amp; the bottom part of the output here..</figcaption></figure><p>We will use differential learning rates &amp; train the head of our model at 100x lr compared to the body. Hence, we will use a custom splitter function to create two parameters groups for our optimizer, one containing the parameters for the head and the other containing the rest. Note that our model head had just 6 parameters .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgeGWbSDbDkPguR2GQK_Mg.png" /></figure><p>Next, we will freeze the pretrained part of the model &amp; just train the parameters of the head. We will still train the parameters of batchnorm layers in the frozen part. Research has shown that training the batchnorm layers in a transfer learning setting generally gives better results. This behavior is controlled by the “train_bn” (default: True) argument to the Learner constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2OQKh_RURU5Jd_g8zitkA.png" /></figure><p>Let’s check the trainable parameters in the parameter group. We can see that all parameters in the first parameter group belong to batchnorm layers (compare the parameter names with the display of pet3_resnet34 architecture above).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2TqJ1OHIMrWMRoe64EHHw.png" /></figure><p>Let’s find a suitable learning for our model under the constraint that the learning rate for the head should be 100 time the learning rate for the rest of the model (body). This can be achieved by passing a numpy array to start_lr &amp; end_lr arguments of the learn.lr_find() method. However, FastAI only tracks the learning rate for the last parameter group in the Recorder callback. I will slight modify a few methods of the Recorder callback below so that it tracks the learning rate for both parameter groups and also plots them both. I will use @patch decorator to make the changes in-place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQ0QfxRX3trmbF-UkFGWbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgARtOBumJuW8t2C8eWWSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7jt0DenOmvT_zNoHMmeAw.png" /></figure><p>Let’s use our own lr_find to find an appropriate learning rate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3X7N6rqI6Pd5sEHavqvjA.png" /></figure><p>We will train the model for 3 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gq6A5kx2AUUpteeFaJoLw.png" /></figure><p>Next, unfreeze the entire model and train again. We will use my_lr_find() again to find an appropriate learning rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CkZUGwqYj7cZBwxsgApQ3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcch3KIvbieuy6vQTLxAWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLEor6sCPoY3IdGJKEgzGg.png" /></figure><p>The code files for this article can be found <a href="https://github.com/Rakeshsuku/Medium-Blog/tree/master/Understanding%20FastAI%20v2%20Training"><em>here</em></a>.</p><p><strong>Link to other articles in this series:</strong></p><ul><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-1-the-resnet-model-dd9270450bb8"><em>Study the resnet34 model architecture and build it using plain Python &amp; PyTorch.</em></a></li><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-2-fastai-optimizers-df65cb018604">Deep dive into FastAI optimizers &amp; implement a NAdam optimizer.</a></li></ul><p><strong>References:</strong></p><ol><li><a href="https://course.fast.ai/"><em>Practical Deep Learning for Coders</em></a></li><li><a href="https://github.com/fastai/fastai"><em>FastAI GitHub Repo</em></a></li><li><a href="https://github.com/fastai/fastbook"><em>FastAI Book</em></a></li><li><a href="https://docs.fast.ai/index.html">FastAI Documentation</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3ea85c6fe78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/understanding-fastai-v2-training-with-a-computer-vision-example-part-3-fastai-learner-and-a3ea85c6fe78">Understanding FastAI v2 Training with a Computer Vision Example- Part 3: FastAI Learner and…</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding FastAI v2 Training with a Computer Vision Example- Part 2: FastAI Optimizers]]></title>
            <link>https://medium.com/analytics-vidhya/understanding-fastai-v2-training-with-a-computer-vision-example-part-2-fastai-optimizers-df65cb018604?source=rss-6ca79b036138------2</link>
            <guid isPermaLink="false">https://medium.com/p/df65cb018604</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[optimizer]]></category>
            <category><![CDATA[fastai]]></category>
            <dc:creator><![CDATA[Rakesh Sukumar]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 13:16:42 GMT</pubDate>
            <atom:updated>2020-10-21T12:25:59.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*cXzglYO0mQlPVynnZKiIiA.png" /><figcaption>Image Source: <a href="https://arxiv.org/abs/1805.04829">Spatial Uncertainty Sampling for End-to-End Control</a></figcaption></figure><p>This is the second article in this series. This series is aimed at those who are already familiar with FastAI and want to dig a little deeper and understand what is happening behind the scene. The overall structure of this series is as below:</p><ol><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-1-the-resnet-model-dd9270450bb8">Study the resnet34 model architecture and build it using plain Python &amp; PyTorch.</a></li><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-2-fastai-optimizers-df65cb018604">Deep dive into FastAI optimizers &amp; implement a NAdam optimizer.</a></li><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-3-fastai-learner-and-a3ea85c6fe78">Study FastAI Learner and Callbacks &amp; implement learning rate finder (lr_find method) with callbacks.</a></li></ol><p>In this article, we will use the resnet model built in the previous article to understand FastAI optimizers. We will use Google Colab to run our code. You can find the code file for this series <a href="https://github.com/Rakeshsuku/Medium-Blog/tree/master/Understanding%20FastAI%20v2%20Training">here</a>. Let’s get started directly.</p><p>First, we will quickly recreate our model from the previous article(refer the <a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-1-the-resnet-model-dd9270450bb8">first article</a> for explanations).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oe-HyVnXfeTaS9Kpk1DHMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_TozTnXTAItO_G8pmsYIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-RpZgxM1PEuLx55aGgiDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6CSbDdVtfJKeSpgwRKs5pQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQV8wFyI0tOLntQQlLbtPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ue1L1Y0DyOXrBqpL1oojA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mj1TJ1AZujgMU94WUnpBsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18gNI_AIaC7HWnweOcUOYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WScOMuXCJaTdL_XRW9oOSQ.png" /></figure><p>The optimizer used to fit the model is saved in the learn.opt attribute of the learner object. Optimizer object is not created until we fit the model using the fit() method or any of its variants (like fit_one_cycle). The “opt_func” argument to the Learner constructor is used to create the optimizer. By default, FastAI adds an Adam optimizer. Also by default all trainable parameters of the model (i.e. parameters of all layers that are not frozen) are passed to the optimizer as a single list at the time of its creation.</p><p>FastAI optimizers create parameter groups to enable us to set different hyperparameter values for different parts of the network. The default behavior is to create a single parameter group with all parameters of the model. We can create multiple parameter groups by passing a list of collection/generator of parameters to the optimizer. We will see an example of this in the third article, for now, let’s find a good learning rate and train the model for one epoch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQ5LvMRBH8ZMqyeb9ssQmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VE41g91gaTY1lF2MapFToA.png" /></figure><p>A FastAI optimizer has 4 main attributes:</p><ol><li><strong>param_list:</strong> A list of list of parameters. Each of the inner list forms a parameter group (explained later). FastAI uses a customized list called an ‘L’.</li><li><strong>hypers:</strong> A list (an L) of dictionary of hyperparameters (learning rate, weight decay, momentum etc.) with one dictionary per parameter group.</li><li><strong>state:</strong> A dictionary containing the state variables, such as average gradient, average squared gradient etc. for all parameters of the model. The state for a parameter p can be accessed by opt.state[p]. The state variables are used to implement adaptive optimizers like Adam.</li><li><strong>Optimizer callbacks:</strong> FastAI optimizers use callback functions to update parameters &amp; state variables during the opt.step() operation. We will see how this works with an example below. Let’s examine the default optimizer that FastAI has added to our model.</li></ol><p><strong>param_list: </strong>Let’s checkout the param_list first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJPLdfRa2eitwxK71HQBMA.png" /></figure><p>We see that param_list is an L containing an L of parameters i.e. L(L(parameters), L(parameters), …). Each of the inner L corresponds to a parameter group. In our case, we have only a single L inside the outer L as FastAI creates only one parameter group by default. The inner L contains 116 items which is the number of parameter tensors in our xresnet34 model (checkout <a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-1-the-resnet-model-dd9270450bb8">the first article</a> to see the details).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*_HW75QbkTmwHer3L6FvLpw.png" /><figcaption>No. of parameter tensors in xresnet34 architecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hom4dkVjg1Wl8rc7YGq-SQ.png" /></figure><p>Let’s understand the first parameter “0.0.weight”. The first ‘0’ represents the nn.Sequential of the input stem, the second ‘0’ indicates the first layer of the input stem which is an nn.Conv2d(). We do not have a bias for this layer as we have passed bias=False to nn.Conv2d(). “0.0.weight” should be of shape [32, 3, 3, 3] corresponding to 32 output channels, 3 input channels, and 3x3 kernel. Let’s check this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3kHNSHuC-JsxlnDouwIaw.png" /></figure><p>Other parameters of the model can be identified in a similar way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrntfyQbFXts1p4O7YqjBg.png" /><figcaption>Partial output from named_children method on xresnet34 model</figcaption></figure><p><strong>hypers: </strong>The ‘hypers’<strong> </strong>attribute of the optimizer store the hyperparameter values. It is an L of dictionary of hyperparameters with 1 dictionary per parameter group. Thus it allows us to set different hyperparameter values (such as differential learning rates) for different layers (parameter groups) in our neural network model. Note that we have only 1 parameter group here. Let’s checkout the hyperparameter values after the training for 1 epoch above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMbwqH9dXwa3edChrNmWIQ.png" /><figcaption>hyperparameters of the Adam optimizer</figcaption></figure><p>‘mom’ and ‘sqr_mom’ above are beta1 &amp; beta2 in the Adam parameter update rule. Refer this post <a href="https://ruder.io/optimizing-gradient-descent/"><em>An overview of gradient descent optimization algorithms</em></a> if you want a refresher on different optimizers algorithms. We get as many hyperparameter dictionaries as there are parameter groups. Hyperparameter values are updated using the set_hypers() method of the optimizer object. set_hypers() method accepts hyperparameter name &amp; value pairs as its arguments. Hyperparameter values can be specified in one of the following formats:</p><ul><li>A single value: The hyperparameter will be set to the same value across all parameter groups.</li><li>A list like object: Length of the list must be equal to the number of parameter groups. Hyperparameter in each parameter group will be set to the corresponding values in the list.</li><li>A slice object: If both “start” and “stop” are specified, the hyperparameter in parameter groups will be set to even multiples between start &amp; stop with the first parameter group getting the start value &amp; the last parameter group getting the stop value. If “start” value is not specified (ex: slice(1e-3)), the hyperparameter in the last parameter group will get the “stop” value &amp; all other parameter groups will get a value “stop”/10.</li></ul><p><strong>state</strong>: The state attribute of the optimizer stores the state for each parameter. The state values are used to implement adaptive optimizers such as Adagrad, RMSprop, Adam etc. Let’s explore the state for a couple of parameters in our model after training for 1 epoch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZA9Mt6s308N4MK4sXf9Qw.png" /></figure><p>You can see that state is a dictionary of length 116 with parameters as the keys &amp; their state as the values.</p><p>The last layer in our model is a linear layer with 512 input activations and 10 output activations. Let’s checkout the bias parameter for this layer as it is just a 1 dimensional tensor of length 10. The <strong><em>all_params()</em></strong> method of the optimizer object returns an L((p, pg, state, hyper), …) for all parameters p in the model, where pg is the parameter group that p belongs to, state is the state for p, and hyper is the hyperparameter values (dictionary) for the parameter group pg. Let’s use this method to study the state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4QrI-dLige887sm0z-sDw.png" /></figure><p>Above, we can see that state tracks grad_avg &amp; sqr_avg required for Adam optimizer. ‘step’ stores the number of optimizer steps (i.e. parameter updates) made which is also required for the Adam update rule. Since we have just trained the model for 1 epoch and the size of our training dataset is 147 batches, the step value is 147.</p><p>The ‘do_wd’ variable decides whether weight decay is applied to this parameter. This is controlled by the argument ‘wd_bn_bias’ (default value: False) passed to the Learner constructor; the default value specifies that weight decay is not to be applied for all bias parameters and all parameters of batchnorm type (batchnorm/instance norm/layer norm). The create_opt() method of the learner object inserts the variable ‘do_wd ’ with a value = False into the state dictionary for these parameters. Weight decay is not applied during the step() operation if the parameter contains ‘do_wd’ in it’s state with a value = False. Note that create_opt() method creates the optimizer object by calling calls the ‘opt_func’ method passed to the learner constructor.</p><p>The create_opt() method also stores a variable called ‘force_train’ (with the value = True) in the state dictionary of batch norm type parameters if ‘train_bn’ argument to Learner constructor is set to True(default value). The variable causes the batch norm parameters to be trained even if they belong to frozen layers in a transfer learning setting. We will see this in action in the next article.</p><p>The third parameter from the last in our model is a weight tensor for a batchnorm layer. Lets checkout the state for this parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbQ6QvI-VSnCA2k64oTQIg.png" /></figure><p><strong>callbacks</strong>: FastAI optimizers use callback functions to update parameters &amp; state variables during the opt.step() operation. The step() method calls all callbacks one after other on every trainable parameters of the model. These callbacks may update the parameter value and/or may return new state values which will then be saved to the parameter’s state. Let’s implement a NAdam optimizer to complete our study of FastAI Optimizers. I have shamelessly copied most of the code below from the FastAI repo.</p><p>Also note that optimizer callbacks can have default hyperparameter values specified in .defaults attribute. These defaults will be used by the __init__() method of optimizer object to set hyperparameter values. However, if hyperparameters are also passed-in as arguments to the __init__() method, the passed-in values take precedence over the callback defaults.</p><p><strong>Nadam Optimizer</strong></p><p>Nadam (Nesterov-accelerated Adaptive Moment Estimation) is a combination of Adam and NAG. The parameter update rule for Nadam optimizer is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*LPtMMZOTSwqbfYawrbcZrw.png" /><figcaption>Nadam parameter update rule</figcaption></figure><p>where,</p><ul><li>θt+1 and θt are the parameter values for time steps t+1 and t.</li><li>η is the learning rate.</li><li>νt is the exponentially decaying average of past squared gradients and νt-hat is it’s bias corrected estimate.</li><li>mt is the exponential decaying average of past gradients and mt-hat is it’s bias corrected estimate.</li><li>gt is the current graidient</li><li>ϵ is a smoothing term to avoid division by 0</li><li>β1 and β2 are mom and sqr_mom in FastAI parlance</li></ul><p>Let’s create callbacks to implement the Nadam parameter update rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6BUNwD2szFx90wtINtQ5Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Yg9YZLdvRaBekXHWb6GIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g3oCLWb19UiHgrQtbIYxBg.png" /></figure><p>Note that debias() function just returns (1- mom**step) when damp = (1-mom). So, debias1 = (1-mom**step) and debias2 = (1-sqr_mom**step). We have added set_trace() in the nadam_step() to check our optimizer.</p><p>‘<em>num</em>’ above computes <em>mom*grad_avg + (1-mom)*p.grad</em> (i.e. β1*mt + (1-β1)*gt in Nadam parameter update rule). Note that bias correction for grad_avg (debias1) is not applied in the calculation of ‘<em>num</em>’ here.</p><p>Next, let’s create a function to return a Nadam optimizer after adding the required callbacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-58F_qbGRqbFUvW-Rhc-Rg.png" /></figure><p>Let’s validate the Nadam parameter rule using a test parameter the FastAI way (check the Optimizer notebook in FastAI repo). An excel implementation of this test can be found <a href="https://github.com/Rakeshsuku/Medium-Blog/tree/master/Understanding%20FastAI%20v2%20Training">here</a> (File name: Nadam step test example.xlsx).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTAUSaKK5GEh3o-HrPRWDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ws69YTvJTZ3AwpOVrqcKw.png" /></figure><p>Note that weight decay is already applied (p has values [0.99, 1.98, 2.97]). Both grad_avg and sqr_avg are initialized with 0s and has values (1-mom)*p.grad and (1-sqr_mom)*p.grad for the first time step. debias1 and debias2 has value 0.1 ( = 1-mom**1) and 0.01 ( = 1-sqr_mom**1) respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjgoTA-5p07HwhG6v3ZxwQ.png" /></figure><p>‘<em>num</em>’ above computes <em>mom*grad_avg + (1-mom)*p.grad</em> (i.e. β1*mt + (1-β1)*gt in Nadam parameter update rule). Let’s check the parameter values after the opt.step() operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*60aYPkAiokuSn4lGu0S92g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sY9TUubQ0wnzUMjWUuBrlA.png" /></figure><p>Note that we did not zero the gradients after our step operation. Let’s go for one more round.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73S1eD9RT266tARWQtAC0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWu7nx7oymagdOKPbXJNcg.png" /></figure><p>Now, let’s fit our model with our own implementation of Nadam optimizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUjCPGLYvu73z9HZTQYZ2Q.png" /></figure><p>We redefine the nadam_step() function below to comment out the set_trace().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zboUXmkGD-ndhLJlh3I43A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_13W4ka_SYe4QzyA4X2Ndg.png" /></figure><p>We got 80.96% accuracy in 10 epochs with our Nadam optimizer.</p><p>In this article we have learned how to create a custom FastAI optimizer. However, if you want to use a standard Pytorch optimizer with FastAI, you can use the <strong>OptimWrapper</strong> class to wrap the Pytorch optimizer &amp; use it within your learner. Find a tutorial for the same <a href="https://docs.fast.ai/tutorial.imagenette#Changing-the-optimizer"><em>here</em></a>.</p><p>In the next article we will study FastAI learner &amp; callbacks &amp; build our own implementation of lr_find() method. You can find the code files for this series <a href="https://github.com/Rakeshsuku/Medium-Blog/tree/master/Understanding%20FastAI%20v2%20Training">here</a>.</p><p><strong>Links to other articles in this series:</strong></p><ul><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-1-the-resnet-model-dd9270450bb8"><em>Study the resnet34 model architecture and build it using plain Python &amp; PyTorch.</em></a></li><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-3-fastai-learner-and-a3ea85c6fe78"><em>Study FastAI Learner and Callbacks &amp; implement learning rate finder (lr_find method) with callbacks.</em></a></li></ul><p><strong>References:</strong></p><ol><li><a href="https://course.fast.ai/"><em>Practical Deep Learning for Coders</em></a></li><li><a href="https://github.com/fastai/fastai"><em>FastAI GitHub Repo</em></a></li><li><a href="https://github.com/fastai/fastbook"><em>FastAI Book</em></a></li><li><a href="https://docs.fast.ai/index.html">FastAI Documentation</a></li><li><a href="https://ruder.io/optimizing-gradient-descent/"><em>An overview of gradient descent optimization algorithms</em></a></li><li><a href="https://arxiv.org/abs/1412.6980"><em>Adam: A Method for Stochastic Optimization</em></a></li><li><a href="https://pytorch.org/docs/stable/index.html"><em>Pytorch Documentation</em></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df65cb018604" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/understanding-fastai-v2-training-with-a-computer-vision-example-part-2-fastai-optimizers-df65cb018604">Understanding FastAI v2 Training with a Computer Vision Example- Part 2: FastAI Optimizers</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding FastAI v2 Training with a Computer Vision Example- Part 1: The Resnet Model]]></title>
            <link>https://medium.com/analytics-vidhya/understanding-fastai-v2-training-with-a-computer-vision-example-part-1-the-resnet-model-dd9270450bb8?source=rss-6ca79b036138------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd9270450bb8</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[resnet]]></category>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Rakesh Sukumar]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 11:51:46 GMT</pubDate>
            <atom:updated>2020-10-21T12:27:00.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9D-F0RekA45wFYBX3ZVYw.png" /><figcaption>Image Source: <a href="https://wallpapercave.com/matrix-hd-wallpaper">https://wallpapercave.com/matrix-hd-wallpaper</a></figcaption></figure><p>In this series we will use a computer vision example to study the FastAI training loop. This series is aimed at those who are already familiar with FastAI and want to dig a little deeper and understand what is happening behind the scene. I will assume basic understanding of deep learning and CNNs and will not be providing explanation for all the jargons used. If you need more explanation on any of the topics I recommend the free online course from FastAI <a href="https://course.fast.ai/"><em>Practical Deep Learning for Coders</em></a><em> and the associated </em><a href="https://www.amazon.in/Deep-Learning-Coders-fastai-PyTorch-ebook/dp/B08C2KM7NR/ref=tmm_kin_swatch_0?_encoding=UTF8&amp;qid=1602254377&amp;sr=8-1"><em>book</em></a>.</p><p>The overall structure of this series is as below:</p><ol><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-1-the-resnet-model-dd9270450bb8">Study the resnet34 model architecture and build it using plain Python &amp; PyTorch.</a></li><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-2-fastai-optimizers-df65cb018604">Deep dive into FastAI optimizers &amp; implement a NAdam optimizer.</a></li><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-3-fastai-learner-and-a3ea85c6fe78">Study FastAI Learner and Callbacks &amp; implement a learning rate finder (lr_find method) with callbacks.</a></li></ol><p>This is the first article in the series, in this article we will study the fastai’s resnet34 model architecture and build it on our own in PyTorch. We will use the Imagenette data (provided by FastAI), which is a subset of the famous Imagenet dataset containing just 10 classes which are relatively easy to distinguish. You can read more about the dataset <a href="https://github.com/fastai/imagenette">here</a>.</p><p>First, we will use fastai convenience functions to quickly create and fit an optimized Resnet34 model and use this to study the model architecture. Armed with this understanding, we will build the model architecture from scratch using plain Python &amp; Pytorch. We will use Google Colab to run our codes. You can find the code file for this series <a href="https://github.com/Rakeshsuku/Medium-Blog/tree/master/Understanding%20FastAI%20v2%20Training">here</a>.</p><p>Let’s get started..!</p><p>Run the following code to install fastai v2 in Google Colab. You will need to provide authorization to your Google Drive account when you run the first cell below. See the instruction to run fastai v2 software in Google Colab <a href="https://course.fast.ai/start_colab">here</a> if you need more information. Remember to enable GPU for your Google Colab session before you run any code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3kFrgiVizxQIDUMoXfq0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8GbIyV5Io8lMqKdtYYWnQ.png" /></figure><p>untar_data() is a fastai convenience function to download the data. We will be using a lot of fastai function in this series, you use the doc() function to get help on these functions as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvO_I62Ueozqwc3-Bkf3Yw.png" /></figure><h4>Setting up dataloaders using DataBlock API</h4><p>We will use fastai DataBlock API to create dataloaders for our model. We will not delve deeper into the DataBlock API here as FastAI already has some fantastic tutorials on them. You can find the tutorials <a href="https://docs.fast.ai/data.block">here</a>.</p><p>Let’s create a label dictionary to provide English labels to our dataset and use it in our dataloaders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-7X8zYYWJx8-v4s5b2Q6w.png" /></figure><p>We use Imagenet stats to normalize our dataset. The aug_tranforms() function is used to apply data augmentation in our dataloaders. Let’s take a quick look at what these are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0k03ffpMjwD8uY-8HLbgg.png" /></figure><p>You can get a trace of all step in the creation of dataloaders using the summary() method. This method is extremely useful if you run into errors on dataloaders creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47-kgvWVeG2QxASm0lIb9g.png" /></figure><p>FastAI transformation pipeline enables us to easily visualize our dataset after applying the augmentation transformations. Let’s take one sample form our dataset and generate multiple copies of it after applying the augmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VnXh4fGVHVo-IypWTDp52Q.png" /></figure><p>You can also use the show_batch() method to get different images from the training set and visualize them after the augmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqwyQJkZmz1dT4Bggv5CCw.png" /></figure><p>Let’s get one batch of data from our training set &amp; check the shape. FastAI uses a default batchsize of 64. The dataloaders converts the input image to tensor of size [3, 224, 224] pixels for our neural network model to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLj0HmvI4pIgILTyY5VOHg.png" /></figure><p>Let’s use fastai’s improved resnet34 architecture to build our image classification model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWKS2vFQ2IM3RmHeNbfpww.png" /></figure><p>Now, create a Learner object to train our model. Learner is the basic class for handling the training loop in FastAI. A learner object binds together the dataloaders, the neural network model, an optimizer, and the loss function. FastAI adds an Adam optimizer by defaults &amp; can choose an appropriate loss function based on the type of our target variable. For a categorization problem, it adds CrossEntropyLoss() as the default loss function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vlLJf1r5G94VoSbiyPZfA.png" /></figure><p>Let’s use Learner method learn.lr_find() to find an appropriate learning rate and learn.fit_one_cycle() to fit the model using one-cycle learning for 10 epochs. We are training the model for a relatively high number of epochs here as we are not using transfer learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fwjXWESY9xy1QqakFpuoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bm5gLM2DBjV3kJ6r2-tskw.png" /></figure><p>Wow!!! We got an accuracy of 81.2% in 10 epochs.</p><p>We can use the learn.summary() method of the learner object to understand more about our model. The summary() method also displays the shape of the activations from each layer of the model. Note that we are just showing the<br>top and bottom part of the output from the summary method below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-DCpDK_4cn15Rh-cwJdgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6-oeLo7BhFb-PC0_PBa-g.png" /></figure><h4>xResnet34 Model Architecture</h4><p>Let understand the model architecture used. xResnet34 architecture consists of 5 stages of convolution layers: an input stem + 4 stage of resnet blocks (see the image below). Each Resnet block consists of 2 conv layers with a short circuit connection (identity path) from the input of the first conv layer to the output of the second conv layer. The original resnet34 architecture described in the paper “<a href="https://arxiv.org/abs/1512.03385"><em>Deep Residual Learning for Image Recognition</em></a>” had one 7x7 convolution layer in it’s input stem and hence had 34 neural network layers in it’s main path (1 conv layer in input stem + (2 conv layers/resnet block)*16 resnet blocks + 1 linear layer). FastAI’s xresnet34 model has 3 conv layers in it’s input stem. Deeper resnet architectures are built by adding more conv layers in each resnet block. I strongly recommend reading “<a href="https://arxiv.org/abs/1512.03385"><em>Deep Residual Learning for Image Recognition</em></a>” and “<a href="https://arxiv.org/abs/1812.01187"><em>Bag of Tricks for Image Classification with Convolutional Neural Networks</em></a>” for a better understanding of the resnet architecture &amp; it’s variations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwz1ZoEEUi8DW6ppG-Vypg.png" /><figcaption>Resnet Architecture</figcaption></figure><p>The complete architecture for the xresnet34 model is as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GAO8nOcSetyt5TTwASblVA.png" /><figcaption>xResnet34 Architecture. *BN: BatchNorm layer</figcaption></figure><p>“nn.Sequential([])” in the id path above indicates that no neural network layers are present in that path. The xresnet34 architecture has <strong>21.3 million</strong> trainable parameters in <strong>116 parameter tensors</strong> (nn.Parameter tensors representing weights and bias) as given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*_HW75QbkTmwHer3L6FvLpw.png" /><figcaption>No. of parameter tensors in xresnet34 architecture</figcaption></figure><p>The excel file containing the architecture with formulas to compute the number of parameters can be found <a href="https://github.com/Rakeshsuku/Medium-Blog/tree/master/Understanding%20FastAI%20v2%20Training"><em>here</em></a> (File name: Understanding xResNet.xlsx).</p><p>Let’s create our own xresnet34 model now. First, let’s create the input stem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQTXrcKUegCx0TW93r9IRg.png" /></figure><p>Next, we will create a resnet block and use it to create the resnet stages. The structure of the resnet block is as below. An AveragePooling layer with a stride 2, and a Conv2d layer with kernel size 1x1 and a BatchNorm layer are added to the identity path if the input and output shapes to the resnet block differs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C--AKh1w9aIzpNCU9MiTqg.png" /><figcaption>Resnet block in xresnet34</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6nQNliSWoTcsPFrHdda2g.png" /><figcaption>Resnet block in xresnet34</figcaption></figure><p>Let’s build the resnet stages and the complete xresnet34 model next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJwuJcujQAomexEM6NCKMQ.png" /><figcaption>resnet stages</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RO09Gk8AkNnUThTTzhF0yg.png" /><figcaption>xresnet34 model</figcaption></figure><p>Let’s move the model to GPU and initialize the weights &amp; biases using kaiming initialization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oDCRZidABaNlB_dQ5i276g.png" /></figure><p>We will now create a learner using our own neural network architecture and use it to fit the classification model as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TSK0b1OdGNEXaqbjIkcCDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3Tqjbw-w_lFfp5ozObYSA.png" /></figure><p>Eureka!!! We reached 80.38% accuracy in 10 epochs. In the next article we will study FastAI Optimizers and build our own NAdam optimizer.</p><p>You can find the code file for this series <a href="https://github.com/Rakeshsuku/Medium-Blog/tree/master/Understanding%20FastAI%20v2%20Training">here</a>.</p><p><strong>Links to other articles in this series:</strong></p><ul><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-2-fastai-optimizers-df65cb018604"><em>Deep dive into FastAI optimizers &amp; implement a NAdam optimizer.</em></a></li><li><a href="https://medium.com/@rakesh.melezhath/understanding-fastai-v2-training-with-a-computer-vision-example-part-3-fastai-learner-and-a3ea85c6fe78"><em>Study FastAI Learner and Callbacks &amp; implement learning rate finder (lr_find method) with callbacks.</em></a></li></ul><p><strong>References:</strong></p><ol><li><a href="https://course.fast.ai/"><em>Practical Deep Learning for Coders</em></a></li><li><a href="https://github.com/fastai/fastai"><em>FastAI GitHub Repo</em></a></li><li><a href="https://github.com/fastai/fastbook"><em>FastAI Book</em></a></li><li><a href="https://docs.fast.ai/index.html"><em>FastAI Documentation</em></a></li><li><a href="https://arxiv.org/abs/1512.03385"><em>Deep Residual Learning for Image Recognition</em></a></li><li><a href="https://arxiv.org/abs/1812.01187"><em>Bag of Tricks for Image Classification with Convolutional Neural Networks</em></a></li><li><a href="https://arxiv.org/abs/1502.01852"><em>Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification</em></a></li><li><a href="https://pytorch.org/docs/stable/index.html"><em>Pytorch Documentation</em></a></li></ol><p><a href="https://towardsdatascience.com/understanding-and-visualizing-resnets-442284831be8">Understanding and visualizing ResNets</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd9270450bb8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/understanding-fastai-v2-training-with-a-computer-vision-example-part-1-the-resnet-model-dd9270450bb8">Understanding FastAI v2 Training with a Computer Vision Example- Part 1: The Resnet Model</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SHAP Part 3: Tree SHAP]]></title>
            <link>https://medium.com/analytics-vidhya/shap-part-3-tree-shap-3af9bcd7cd9b?source=rss-6ca79b036138------2</link>
            <guid isPermaLink="false">https://medium.com/p/3af9bcd7cd9b</guid>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[model-interpretability]]></category>
            <dc:creator><![CDATA[Rakesh Sukumar]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 12:49:06 GMT</pubDate>
            <atom:updated>2024-02-28T06:07:12.125Z</atom:updated>
            <content:encoded><![CDATA[<p>Tree SHAP is an algorithm to compute exact SHAP values for Decision Trees based models. <a href="https://www.analyticsvidhya.com/blog/2019/11/shapley-value-machine-learning-interpretability-game-theory/?utm_source=Backlink&amp;utm_medium=SEO"><strong>SHAP</strong></a> (SHapley Additive exPlanation) is a game theoretic approach to explain the output of any machine learning model. <strong>The goal of SHAP is to explain the prediction for any instance xᵢ as a sum of contributions from it’s individual feature values.</strong> Refer to the part 1 of this series <a href="https://medium.com/@rakesh.melezhath/shap-part-1-an-introduction-to-shap-58aa087a460c">here</a> for brief theoretical introduction to SHAP.</p><p>As explained in the first article, SHAP values are obtained from the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*0gMGleWFLgVAD-5OMDllYg.png" /><figcaption>Notation: |M| is the total number of features. S represents any subset of features that doesn’t include the i-th feature and |S| is the size of that subset. fₛ() represents the prediction function for the model for the subset S.</figcaption></figure><p>Let’s workout the SHAP values for a simple <a href="https://www.analyticsvidhya.com/blog/2021/08/decision-tree-algorithm/?utm_source=Backlink&amp;utm_medium=SEO"><strong>regression tree</strong></a> to get a better understanding of the algorithm. Consider a hypothetical dataset of 10 samples with three numeric independent variables (namely: x, y, z) and a target variable t. We get the below tree structure on fitting a regression tree to this dataset. See the code file here: <a href="https://github.com/Rakeshsuku/Medium-Blog"><em>Tree_SHAP_Hypothetical_Example.ipynb</em></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEopgun4fxAR-i7WyOJDoQ.png" /><figcaption>n1, n2, n3, …, n7 represent the nodes of the tree. s values in each node represents the number of samples from the training set that fall into each node.</figcaption></figure><p>Let’s compute the SHAP values for an <strong>instance i given by [x=150, y=75, z=200].</strong> The prediction for this instance is <strong>t=20</strong>. Remember SHAP is a local feature attribution technique that explains every prediction from the model as a sum of individual feature contributions.</p><p>From the theoretical explanation of SHAP in <a href="https://medium.com/@rakesh.melezhath/shap-part-1-an-introduction-to-shap-58aa087a460c">part 1 of this series</a>, we understand that we can compute SHAP values by starting with a null model without any independent variables and then computing the average marginal contribution as each variable is added to this model in a sequence; averaged over all possible sequences. Since we have 3 independent variables here, we have to consider 3!=6 sequences. Let’s compute the marginal contributions for each sequence. Note that SHAP make the assumption that the model prediction for the model with any subset S of independent variables is the expected value of the prediction given the subset xₛ.</p><p>The prediction for the null model ϕ⁰ (also called base value)= mean prediction for the training set = (50*2 + 30*2 + 20*1 + 10*5)/10 = 23</p><p><strong><em>Consider the sequence: x &gt; y &gt; z:</em></strong></p><p>1)First, the feature x is added to the null model. Note that for the <strong>selected instance i</strong>, we can compute the exact prediction with just this information as only the variable x is used in the nodes (n1 &amp; n3) leading upto the leaf node n6. Thus the prediction of the model with just the feature x is 20. Therefore the marginal contribution of x in this sequence, ϕˣ¹= 20–23 = -3.</p><p>2)Now, let’s add the feature y to the above model (in step 1). Since adding y does not alter the prediction for the selected instance i, the marginal contribution for y in this sequence, ϕʸ¹ = 20–20 = 0.</p><p>3)Similarly, the marginal contribution for z in this sequence, ϕᶻ¹ = 0.</p><p><strong><em>Next, let’s consider the sequence y &gt; z &gt;x:</em></strong></p><p>1)First, the feature y is added to the null model. The first node n1 uses x as the split variable, since is x is not available yet, we compute the prediction as (4/10)*(prediction from left child node n2) + (6/10)*(prediction from right child n3); 100, 60 and 40 being number of training samples falling into nodes n1, n2 and n3 respectively.</p><p>i) Prediction from node n2: n2 uses y as the split variable, since y is available (yᵢ = 75 for instance i), the prediction from node n2 = 50.</p><p>ii) Prediction from node n3: Again, n3 uses x as the split variable. Therefore, by similar logic, prediction from n3 = (1/6)*20 + (5/6)*10= 70/6.</p><p>iii) Therefore, the prediction for the model with just the feature y is (4/10)*50 + (6/10)*(70/6) = 27. Hence, the marginal contribution for y in this sequence, ϕʸ² = 27–23 = 4.</p><p>2)Next, we add the feature z to the above model. Since z is not used as a split variable in any of the internal nodes of the tree, adding this feature does not alter the prediction in any way. Thus the marginal contribution for z in this sequence, ϕᶻ² = 0. You may validate this by following this same approach as in step 1.</p><p>3)Finally, we add the feature x to the model which gives the prediction as 20. Therefore the marginal contribution of x in this sequence is ϕˣ²=20–27 = -7.</p><p>Similarly, we compute the marginal contribution of each feature values for remaining sequences:</p><p><em>Sequence x &gt; z &gt; y:</em> ϕˣ³ = -3, ϕʸ³ = 0, ϕᶻ³ = 0</p><p><em>Sequence z &gt; x &gt; y:</em> ϕˣ⁴ = -3, ϕʸ⁴ = 0, ϕᶻ⁴ = 0</p><p><em>Sequence z &gt; y&gt; x:</em> ϕˣ⁵ = -7, ϕʸ⁵ = 4, ϕᶻ⁵ = 0</p><p><em>Sequence y &gt; x&gt; z:</em> ϕˣ⁶ = -7, ϕʸ⁶ = 4, ϕᶻ⁶ = 0</p><p>Hence, SHAP values for the instance i are given by:</p><p>ϕˣ = (ϕˣ¹ + ϕˣ² + ϕˣ³ + ϕˣ⁴ + ϕˣ⁵ + ϕˣ⁶)/6 = (-3–7–3–3–7–7)/6 = -5</p><p>ϕʸ = (ϕʸ¹ + ϕʸ² + ϕʸ³ + ϕʸ⁴ + ϕʸ⁵ + ϕʸ⁶)/6 = (0+4+0+0+4+4)/6 = 2</p><p>ϕᶻ = (ϕᶻ¹ + ϕᶻ² + ϕᶻ³ + ϕᶻ⁴ + ϕᶻ⁵ + ϕᶻ⁶)/6 = (0+0+0+0+0+0)/6 = 0</p><p>And explanation for the prediction for instance i (20) = ϕ⁰ + ϕˣ + ϕʸ + ϕᶻ = 23 + (-5) + 2 + 0 = 20; which can be explained as below:</p><p>“<em>The base value of the prediction in the absence of any information on independent variables is 23; knowing x=150 decreased the prediction by 5 and knowing y = 75 increased the prediction by 2 giving a final prediction of 20. Knowing z = 300 had no impact on the model prediction.</em>”</p><p>SHAP provides a good pictorial representation of this explanation as below. Blue color indicates that x value (=150) decreased the prediction and red color indicates that y value(=75) increased the prediction. The code file for this example is available here: <a href="https://github.com/Rakeshsuku/Medium-Blog"><em>Tree_SHAP_Hypothetical_Example.ipynb</em></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dR-opE7tvbdg0ZE8h-_kKw.png" /></figure><h4>Actual Tree SHAP Algorithm</h4><p>The computational complexity of the above algorithm is of the order O(LT2ᴹ), where T is the number of trees in the tree ensemble model, L is maximum number of leaves in any tree and M is the number of features. In the Tree SHAP paper², the authors propose a modified version of this algorithm that keeps track of the number of subsets S that flow into each node of the tree. The modified algorithm has a computational complexity of O(LTD²) where D is the max depth of the tree.</p><h4><strong>SHAP Interaction Values</strong></h4><p>SHAP allows us to compute interaction effect by considering pairwise feature attributions. This leads to a matrix of attribution values representing the impact of all pairs of features on a given model prediction. SHAP interaction effect is based on Shapley interaction index from game theory and is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*POFeBIuBT3JnvqxzPv_KqA.png" /></figure><p>where,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*6ml-b7cDDtFgJAyyk83TmA.png" /></figure><p>The above equation indicates that the SHAP interaction value of i-th feature w.r.t to j-th feature can be interpreted as the difference between SHAP values of i-th feature with &amp; without the j-th feature. This allows us to use the algorithm for computing SHAP values to compute SHAP interaction values.</p><p>SHAP interaction effect between the i-th and j-th is split equally (i.e. ϕᵢⱼ=ϕⱼᵢ) and the total interaction effect is ϕᵢⱼ + ϕⱼᵢ. The main effect for the prediction can then be obtained as the difference between SHAP value and sum of SHAP interaction values for a feature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*syk-MsFJBhoEtKDvgGQ0yg.png" /></figure><h4><strong>Tree SHAP On A Real Dataset</strong></h4><p>Now let’s explore the Tree SHAP algorithm further using the <a href="https://archive.ics.uci.edu/ml/datasets/default+of+credit+card+clients">UCI credit card default dataset</a>. A binary variable “<em>default payment next month</em>” with values {0: No, 1:Yes} which indicates whether a customer has defaulted on his/her credit card payment is the target variable (dependent variable) and 23 variables related to the customer such as age, education etc and his/her previous billing and payment history are available as explanatory variables (independent variables). Read more about the dataset from the UCI website. We will use google colab to run our codes. Find the code file uploaded here: <a href="https://github.com/Rakeshsuku/Medium-Blog">Tree_SHAP_UCI_Credit_Card_Default.ipynb</a>.</p><p>Let’s start by installing the shap library and loading all required libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brLgH2PsAlHV2724yC2Ibw.png" /></figure><p>Next, download the dataset from UCI website &amp; read the data into a pandas dataframe. Note that we have dropped the ID column in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HlOYJjE8Tk_HXP6z8YQ-EA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJ0T_8Wd2g2Kr4d_y8k3HQ.png" /></figure><p>Let’s visualize the explanatory variables in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oE0ug3RseTlJVAH5D_i4mA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g22CF4HqaCP-2cdHS3Ksmg.png" /><figcaption>x-axis label 0-No Default; 1-Default</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5RsEOCfyAOwT9mFDkPxkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ljmpak6u0mfevOCno3LyEQ.png" /><figcaption>legend: 0-No Default; 1-Default</figcaption></figure><p>Let’s look at the distribution of the target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-juA9UmVf5taTRgZHKo5Q.png" /></figure><p>We will train a lightgbm model on this dataset. We see that PAY_* columns have values ranging from -2 to 8. Since lightgbm considers all negative values as missing values, we add 3 to these values to make the range to 1 to 11.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ta9RMLularnHH3HGohyZfQ.png" /></figure><p>Let’s copy the target to a new variable y and split the data into training &amp; test sets stratified on the target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4omomFOBJ3nnz2TJpKYhQ.png" /></figure><p>We will now build a baseline lightgbm model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQ3LE-5EQ_4AE9jRKd_GyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dFssnAo9LpHoWD097CkJtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5enE_9ydgklEZWEWEE-uBg.png" /></figure><p>Let’s now tune the hyperparameters of this model using hyperopt. Refer to my blog post <a href="https://medium.com/analytics-vidhya/introduction-to-automatic-hyperparameter-optimization-with-hyperopt-e0b9c84d1059">here</a> if you need more information on using hyperopt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J854xshwGyLVR_2gfgOfng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42cLfNuh3wdaiBRE-V04VQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTLJZ1yoKSmhHO5QuMHf9A.png" /></figure><p>Tuned model gave a ROC AUC of 78.4%. Hyperparameter values that gave the best results are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBJFZChmwQX5H2Vc5D7aXg.png" /></figure><p>Let’s refit the model for the best hyperparameters found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5LKf1sq7rDTt4AfJ-F9qA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQ4npDWRB3BJGwGx2YZ3Zw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-yeUJhIPxMatDAa9NeOrg.png" /></figure><p>We will create new copy (X_test_disp) of our test dataset with the integer-coded categorical variables replaced with the corresponding category values so that SHAP plots will be more intuitive. We get the details of the category levels from <a href="https://archive.ics.uci.edu/ml/datasets/default+of+credit+card+clients">UCI website</a>. Remember that we added 3 to all PAY_* variables. Also, we use “Unk_*” for levels not defined in the UCI site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOj3z_y2c3xKDjEDqVh_wA.png" /></figure><h4>Computing SHAP Values</h4><p>Let’s compute the shap values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*erPSsnl-2-okO6o4LZ3xog.png" /></figure><p>Let me briefly explain the argument to shap.TreeExplainer() function.</p><ul><li>model: A tree based model. Following models are supported by Tree SHAP at present: XGBoost, LightGBM, CatBoost, Pyspark &amp; most tree-based models in scikit-learn.</li><li>data: Dataset to compute marginal contributions of feature variables in Tree SHAP algorithm. This is an optional argument with a default value of None. Unless provided, the training dataset will be used as explained in the algorithm section above.</li><li>feature_perturbation: Can take two values. ‘tree_path_dependent’ is the default value when the data argument is None. ‘interventional’ is the default value if a data argument is provided. Interventional approach uses the shared dataset to compute conditional expectations in the presence of correlated input features. “tree_path_dependent” approach on the other hand uses the training dataset and the number of samples that fall into each node as explained in the algorithm section.</li><li>model_output: With model_output=’raw’ (default), SHAP values explain the raw predictions from the leaf nodes of the trees. <strong>Since most gradient boosting classification models predict logit (log-odds) in their leaf nodes,</strong> <strong>SHAP values explain the logit prediction for GBM models by default</strong>. See the explanation <a href="https://github.com/slundberg/shap/issues/367#issuecomment-508575308">here</a>. Other possible values are “probability”, “log_loss”, or any model method name. With “log_loss” SHAP values explain the log of model’s loss function. See ?shap.TreeExplainer for more details.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fH62cOgELb2jr-lsOkFSRA.png" /></figure><p>For classification problems, explainer.shap_values() return a list of size n_classes. Since this is a binary classification model n_classes=2. Each object of this list is an array of size [n_samples, n_features] and corresponds to the SHAP values for the respective class. In this example, shap_values[1] is the SHAP values for the positive class (<em>default payment next month = Yes</em>) &amp; shap_values[0] is the SHAP values for the negative class. For regression models, we get a single set of shap values of size [n_samples, n_features].</p><p><strong>Explaining a Single Prediction</strong></p><p>Let’s explain the prediction for the first item in the testset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bc2OkmUcRyq6r7UKw82Uew.png" /></figure><p>The base logit value for the positive class over the training dataset is -1.538. The logit prediction for this sample is -0.27. <em>PAY_2</em> <em>= 2 months</em> (i.e. repayment status for the month of Aug/2005 = 2 months delay) contributed maximum to increase the logit; followed by <em>LIMIT_BAL = 5e+4.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0KLOsHqm__NNQblMohpjQ.png" /></figure><p><strong>Explaining Predictions for a More Than One Sample</strong></p><p>If we take the above plot for each sample, rotate them 90 degrees and stack them side-by-side, we can explain the predictions for multiple samples in a single plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Bblvnxp9ss3DVFJvZD4AQ.png" /></figure><p>Samples are ordered by similarity by default.However, we can change this ordering to be by output value, or by original sample order or by any numeric independent variable in the dataset. The color codes mean the same as in previous chart, with red colored features increasing the logit &amp; the blue colored feature decreasing the logit for each data point.</p><p><strong>SHAP Summary Plots</strong><br>shap.summary_plot() can plot the mean shap values for each class if provided with a list of shap values (the output of explainer.shap_values() for a classification problem) as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2W2PAed0qDltlCqvn21j9w.png" /></figure><p>Note that shap_values for the two classes are additive inverses for a binary classification problem. The above plot will be much more intuitive for a multi-class classification problem. We can also generate the above plot for just the class of our interest as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XbhZUWO8ufm4bde94HRl8Q.png" /></figure><p>If provided with a single set of SHAP values (shap values for a single class for a classification problem or shap values for a regression problem), shap.summary_plot() creates a density scatter plot of SHAP values for each feature to identify how much impact each feature has on the model output. Features are sorted by the sum of the SHAP value magnitudes across all samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTSvl63BLdgTSqRWOOGe-w.png" /></figure><p>Note that we get grey colored points for categorical data as the integer encoded values (for a categorical variable) cannot be always used to arrange it from low to high. However, for this dataset the PAY_* variables roughly corresponds to the number of months of payment delay and can therefore be used to sort the values. Let’s plot the same graph as above treating PAY_* variables as numeric variables (all we have to do is to replace X_test_disp with X_test above).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Y6odbK1V7dYYkv_M4osPw.png" /></figure><p>This plot is much more intuitive. We observe that the log-odds for default increases as payment delay increases for all PAY_* variables. Also note that the log-odds for default decreases as payment amount (PAY_AMT*)increases. A surprising observation from the above plot is that the log-odds of default decrease as the amount of given credit (LIMIT_BAL) increases. This may be because the credit card company must be offering higher credit to customer with less probability of default. So customers with high LIMIT_BAL must have high values for PAY_AMT* too. Let’s investigate this further with SHAP dependency plots.</p><p><strong>SHAP Dependence Plots</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5cApteU0VQf1XpIBfLgHQ.png" /></figure><p>We see that customer with high LIMIT_BAL also have high values for PAY_AMT1. The cluster of red-ish colored dots towards the bottom of the band for high LIMIT_BAL samples shows the interaction effect of LIMIT_BAL with PAY_AMT1.</p><p>We can also create a SHAP dependence plot with a categorical variables as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vt299gnjUsWCXtSOs3nkgA.png" /></figure><p>SHAP can also select the interaction variable that seems to have the strongest interaction with the main variable. Lets create a shap dependence plot for top 3 features with highest impact on the model (mean shap values).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-WyTlmUTnRjHu5R07LakA.png" /></figure><p><strong>SHAP Interaction Values and Interaction Summary Plot</strong></p><p>SHAP interaction values are currently not supported for LightGBM &amp; CatBoost models because of the special treatment these libraries give for categorical variables. See the comments on github issues <a href="https://github.com/slundberg/shap/issues/292#issuecomment-432835057">here</a> and <a href="https://github.com/slundberg/shap/issues/662#issuecomment-508577551">here</a>. See <a href="https://slundberg.github.io/shap/notebooks/NHANES%20I%20Survival%20Model.html"><em>NHANES survival model with XGBoost and SHAP interaction values</em></a> notebook in the SHAP GitHub page for an example usecase.</p><p>The code files for this article is uploaded here: <a href="https://github.com/Rakeshsuku/Medium-Blog">Tree_SHAP_UCI_Credit_Card_Default.ipynb</a>.</p><p><strong>Link to other articles in this series:</strong></p><p><a href="https://medium.com/@rakesh.melezhath/shap-part-1-an-introduction-to-shap-58aa087a460c">SHAP Part 1: An Introduction to SHAP</a></p><p><a href="https://medium.com/@rakesh.melezhath/shap-part-2-kernel-shap-3c11e7a971b1">SHAP Part 2: Kernel SHAP</a></p><p><strong>References</strong></p><ol><li>SHAP: A Unified Approach to Interpreting Model Predictions. arXiv:1705.07874</li><li>Consistent Individualized Feature Attribution for Tree Ensembles. arXiv:1802.03888 [cs.LG]</li><li><a href="https://christophm.github.io/interpretable-ml-book/">Interpretable Machine Learning — A Guide for Making Black Box Models Explainable.</a></li><li><a href="https://github.com/slundberg/shap">https://github.com/slundberg/shap</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3af9bcd7cd9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/shap-part-3-tree-shap-3af9bcd7cd9b">SHAP Part 3: Tree SHAP</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SHAP Part 2: Kernel SHAP]]></title>
            <link>https://medium.com/analytics-vidhya/shap-part-2-kernel-shap-3c11e7a971b1?source=rss-6ca79b036138------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c11e7a971b1</guid>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[model-interpretability]]></category>
            <dc:creator><![CDATA[Rakesh Sukumar]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 12:32:57 GMT</pubDate>
            <atom:updated>2020-04-01T12:56:03.953Z</atom:updated>
            <content:encoded><![CDATA[<p>Kernel SHAP is a model agnostic method to approximate SHAP values using ideas from LIME and Shapley values. This is my second article on SHAP. Refer to my previous post <a href="https://medium.com/@rakesh.melezhath/shap-part-1-an-introduction-to-shap-58aa087a460c">here</a> for a theoretical introduction to SHAP.</p><h4>What is LIME?</h4><p>Local Interpretable Model-agnostic Explanations (LIME) is a technique of explaining the predictions of a black box machine learning model by building a number of interpretable local surrogate models (like linear regression). Surrogate models are trained on the predictions of the underlying black box model. The recipe to train local surrogate models is:</p><ul><li>Select the instance of interest xᵢ for which you want to have an explanation for it’s black box model prediction.</li><li>Generate a new dataset by perturbing the feature values of xᵢ. We do not use the actual feature values of xᵢ for the surrogate models, but a simplified binary version (zᵢ) is constructed as follows: If x∈Rᴾ is the original representation of xᵢ, the simplified binary version (called interpretable representation²) is zᵢ∈{0, 1}ᴾ. For example if xᵢ = (x₁, x₂, x₃), the corresponding interpretable representation zᵢ is given by zᵢ = (z₁, z₂, z₃), where each of z₁, z₂ and z₃ may take values 0 or 1.</li><li>Note the predictions of the black box model for each perturbed sample zᵢ. The predictions are obtained by mapping zᵢ back to the original representation Rᴾ as follows: a ‘1’ in zᵢ is mapped to the actual feature value &amp; a ‘0’ is mapped to an appropriate non-informative value according to the type of the dataset. Refer to <a href="https://towardsdatascience.com/understanding-how-lime-explains-predictions-d404e5d1829c"><em>Understanding how LIME explains predictions</em></a> &amp; <a href="https://cran.r-project.org/web/packages/lime/vignettes/Understanding_lime.html"><em>Understanding lime</em></a> to understand the treatments for tabular, text and image datasets. The SHAP KernelExplainer() function (explained below) replaces a ‘0’ in the simplified representation zᵢ with a random sample value for the respective feature from a given background dataset. Thus, the independent variables for the local surrogate model are a bunch of ones and zeroes and the dependent variable is the prediction obtained. However, this process of computing feature contributions make additional assumptions of feature independence and model linearity, at-least locally around the proximity of xᵢ.</li><li>Weight the new samples according to their proximity to the instance of interest (xᵢ).</li><li>Train an interpretable model (like linear regression, lasso, decision tree etc.) on this new dataset.</li><li>Explain the prediction of the black box model by interpreting the local model (also called the explanation model).</li></ul><p>LIME requires the user to select the complexity of local surrogate model and an appropriate kernel function to assign weights to sample in the generated dataset. Below figure presents the intuition behind LIME.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*02osEZEsHs2KTQ3oLnoHbw.png" /><figcaption>Intuition behind LIME: The black box models decision function is represented by the blue/pink background. The bold red cross is the instance being explained. The grey dashed line represent the explanation model built².</figcaption></figure><h4>Kernel SHAP: Linear LIME + Shapley Values</h4><p>In the SHAP paper³ the authors show that with a weighted linear regression model as the local surrogate model and an appropriate weighting kernel, the regression coefficients of the LIME surrogate model estimates the SHAP values. The Shapley kernel that recovers SHAP values is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*YV87878GGpUJllRqMRAR7w.png" /></figure><p>Where M is the number of features &amp; |z’| is the number of non-zero features in the simplified input z’.</p><p>We will go through an example on iris dataset to understand the working of KernelExplainer. We will use google Colab to run our code. The code file is uploaded here: <a href="https://github.com/Rakeshsuku/Medium-Blog">Kernel_SHAP.ipynb</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEgvO3ecOQGham2sMhjKpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRByWhBN2Hf2BjNuM7lRwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2qZHEJy0AjjRfbkk7FrKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOE0bK-_tk0johkIrkLN5g.png" /></figure><p>We will use SHAP KernelExplainer to explain the SVM model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAGS-G-k3Qu6nLpF5owP_Q.png" /></figure><p>Arguments of KernelExplainer() function:</p><ul><li>model: The model to be explained. The output of the model can be a vector of size n_samples or a matrix of size [n_samples x n_output] (for a classification model).</li><li>data: Background dataset to generate the perturbed dataset required for training surrogate models. We simulate “missing” (‘0’s in zᵢ) by replacing the feature with the values it takes in the background dataset. So if the background dataset is a simple sample of all zeros, then we would approximate a feature being missing by setting it to zero. For small problems this background dataset can be the whole training set, but for larger problems consider using a single reference value or using the kmeans function to summarize the dataset.</li><li>link: A function to connect feature contribution values to the model output. For a classification model, we generally explain the logit of the predicted probability as a sum of feature contributions. Hence, if the output of the “model” (the first argument) is a probability, we set link = “logit” to get the feature contributions in logit form.</li></ul><p>Next, we compute the SHAP values as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YSlmvupce-ZnFhPFcHBtTg.png" /></figure><p>Arguments of explainer.shap_values() function:</p><ul><li>X: Dataset on which to explain the model output.</li><li>nsamples: No. of samples to draw to build the surrogate model for explaining each prediction.</li><li>l1_reg: The l1 regularization to use for selecting features to explain the model prediction. Possible values are: “num_features(&lt;int&gt;)”-Selects a fixed number of features to explain the model prediction; “aic”/”bic”-Uses AIC/BIC rules for regularization; &lt;float&gt;-Sets the alpha parameter for sklearn.linear_model.lasso; “auto”-Uses AIC when less than 20% of possible sample space is enumerated, otherwise uses no regularization.</li></ul><p>For classification problems, explainer.shap_values() return a list of size n_classes (number of classes). For a binary classification model n_classes=2 (negative &amp; positive class). Each object of this list is an array of size [n_samples, n_features] and corresponds to the SHAP values for the respective class. For regression models, we get a single set of shap values of size [n_samples, n_features]. Here, we have a 3-class classification problem, hence we get a list of length 3.</p><p><strong>Explaining a Single Prediction</strong></p><p>Let’s explain the prediction for the first item in the testset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OsuUOhl3AKBzR-lG02Ft0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hF4FD7-cY4Y3-ZvTYOsrKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPT56QQ-Vae_ffSId_RLpw.png" /></figure><p>link=”logit” argument converts the logit values to probability. Each plot displays the base probability value for the respective class over the training dataset. Blue color indicates that the feature decreased the probability and the red color indicates that the feature value increased the probability<em>.</em></p><p><strong>Explaining Predictions for a More Than One Sample</strong></p><p>If we take the above plot for any one class for each sample, rotate them 90 degrees and stack them side-by-side, we can explain the predictions for multiple samples in a single plot (note that the samples are ordered by similarity):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxSWFwenjHhoQ_T8bg669Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXGW_Atc7m2g7SmHXUKWrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIOy13hgQSUD4dBUIm2FlA.png" /></figure><p><strong>SHAP Summary Plots</strong><br>shap.summary_plot() can plot the mean shap values for each class if provided with a list of shap values (the output of explainer.shap_values() for a classification problem) as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6T1Z6I74rgZfyTXXXmWxdg.png" /></figure><p>The above plot indicates that <em>petal length (cm)</em> had the greatest influence on the predictions for all 3 classes followed by <em>petal width (cm).</em></p><p>If provided with a single set of SHAP values (shap values for a single class for a classification problem or shap values for a regression problem), shap.summary_plot() creates a density scatter plot of SHAP values for each feature to identify how much impact each feature has on the model output. Features are sorted by the sum of the SHAP value magnitudes across all samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-n0VQUlwfntjGO3lb-Krg.png" /></figure><p>For Setosa output, we see that the low values of <em>petal length (cm)</em> (indicated by blue colored dots) increases the probability that the sample is classified as Setosa (high shap values).</p><p><strong>SHAP Dependence Plots</strong></p><p>SHAP Depencence plots reveal interaction effects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_10e-wjeTOhoONnN-bjTLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnezRxzUZTrQeiO0faa7sA.png" /></figure><p>The Versicolor output depicts the interaction between <em>petal length (cm)</em> and <em>petal width (cm)</em>.</p><p>Find the code file uploaded here: <a href="https://github.com/Rakeshsuku/Medium-Blog">Kernel_SHAP.ipynb</a>.</p><p><strong>Link to other articles in this series:</strong></p><p><a href="https://medium.com/@rakesh.melezhath/shap-part-1-an-introduction-to-shap-58aa087a460c">SHAP Part 1: An Introduction to SHAP</a></p><p><a href="https://medium.com/@rakesh.melezhath/shap-part-3-tree-shap-3af9bcd7cd9b">SHAP Part 3: Tree SHAP</a></p><p><strong>References:</strong></p><ol><li><a href="https://christophm.github.io/interpretable-ml-book/">Interpretable Machine Learning — A Guide for Making Black Box Models Explainable.</a></li><li>“Why Should I Trust You?”: Explaining the Predictions of Any Classifier. arXiv:1602.04938</li><li>SHAP: A Unified Approach to Interpreting Model Predictions. arXiv:1705.07874</li><li><a href="https://towardsdatascience.com/understanding-how-lime-explains-predictions-d404e5d1829c">https://towardsdatascience.com/understanding-how-lime-explains-predictions-d404e5d1829c</a></li><li><a href="https://cran.r-project.org/web/packages/lime/vignettes/Understanding_lime.html">https://cran.r-project.org/web/packages/lime/vignettes/Understanding_lime.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c11e7a971b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/shap-part-2-kernel-shap-3c11e7a971b1">SHAP Part 2: Kernel SHAP</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SHAP Part 1: An Introduction to SHAP]]></title>
            <link>https://medium.com/analytics-vidhya/shap-part-1-an-introduction-to-shap-58aa087a460c?source=rss-6ca79b036138------2</link>
            <guid isPermaLink="false">https://medium.com/p/58aa087a460c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[model-interpretability]]></category>
            <dc:creator><![CDATA[Rakesh Sukumar]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 12:15:50 GMT</pubDate>
            <atom:updated>2020-03-31T12:55:08.265Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*jCfIMIDWHX86REAFpyr0RQ.png" /><figcaption>Image Credit: <a href="https://towardsdatascience.com/should-ai-explain-itself-or-should-we-design-explainable-ai-so-that-it-doesnt-have-to-90e75bb6089e">Should AI explain itself</a></figcaption></figure><h4><strong>Why do we need Model Interpretability ?</strong></h4><p>Before we get to the “why” part of the question, let’s understand what is meant by Interpretability. While there is no mathematical definition for interpretability, a heuristic definition like the one here: “<em>Interpretability is the degree to which a human can understand the cause of a decision³</em>”, or here: “<em>Interpretability is the degree to which a human can consistently predict the model’s result⁴</em>”can be found in machine learning literature. The higher the interpretability of a machine learning model, the easier it is for someone to comprehend why a certain prediction was made by the model.</p><p>Now, as we have defined model interpretability, let’s examine why interpretability is important for machine learning models.</p><ul><li><em>Trust Building</em>: Many organizations rely on machine learning models to take important decisions.A bank using a model to grant or deny loan to an applicant, a hospital evaluating a patient for the risk of a medical condition, or a credit card company predicting whether a transaction is fraudulent are a few examples. Users of machine learning models trust the predictions better if the model can also explain why it made the prediction.</li><li><em>Human Curiosity &amp; Learning</em>: Human beings have a mental model of their environment that is continuously updated by finding an explanation for events happening around them. A black box machine learning model may leave it’s users puzzled as it provides little explanations on the predictions made. On the other hand, an interpretable machine learning model can facilitate learning and help it’s users develop better understanding and intuition on the prediction problem.</li><li><em>Detect Biases and Edge Cases</em>: Consider the example of a machine learning model used to grant or deny loan in a bank. It is possible that model might pick up biases in the training data and may discriminate against certain minority groups. Interpretability can help in detecting biases at the time of model development. Interpretability can also help in identifying edge cases, where a model might fail. For example, if an ML model in self-driving cars is found to use the two wheels of a bicycle to detect a cyclist, it may prompt us to think how the model would behave if it sees a bicycle with side bags, where the wheels may not be clearly visible.</li><li><em>Regulatory Requirements</em>: Regulations such as GDPR in Europe or Equal Credit Opportunity Act in US provides individuals the right to be given an explanation on decisions made by a machine learning model that significantly affects them, particularly legally or financially.</li></ul><h4><strong>What is SHAP ?</strong></h4><p>SHAP (SHapley Additive exPlanation) is a game theoretic approach to explain the output of any machine learning model. <strong>The goal of SHAP is to explain the prediction for any instance xᵢ as a sum of contributions from it’s individual feature values.</strong> Individual feature values are assumed to be in a cooperative game whose payout is the prediction. In this setting, Shapley values provides a means to fairly distribute the payout among the feature values. Note that the “feature value” here refers to the numerical or categorical value of a feature for the instance xᵢ. We will explain the concept with a simple example below.</p><h4><strong>What are Shapley Values ?</strong></h4><p>Let’s assume that A, B, C, D are four players with different skillsets in a coalition game (i.e. A, B, C &amp; D are in the same team) with some payout. What is the fairest way to divide the payout among the players? One way to answer this question is to think that the players joined the group in a sequence (for example: A&gt;B&gt;C&gt;D), then, we can compute the marginal contribution of each player as the change in payout as the player joined the group. However , there could be interaction effects that might affect the payout calculation. For example, if A and B have diverse skillsets, then the total payout for a group with just A and B will be the sum of the following 3 components:</p><ul><li>payout with A alone,</li><li>payout with B alone,</li><li>additional payout for having both A &amp; B.</li></ul><p>However, if we assume that B joined after A, then the above algorithm fully attributes the “<em>additional payout for having both A &amp; B</em>” to player B, which is incorrect. We find that the marginal contributions would be dependent on the sequence in which we assume the players to join the group. Shapley values overcomes this shortcoming by computing the average marginal contribution for each player over all possible sequences. Thus if there are n players, then n-factorial possible sequences are considered. Here, we assume that the payouts can be calculated for any subset of players.</p><p>In the context of a machine learning model, individual feature values of the instance xᵢ are the players and “<em>the prediction yᵢ minus the average prediction for whole training data</em>” is the payout. It can be theoretically proved that Shapley values are the only attribution method that satisfies the following properties:</p><ol><li>Efficiency: The feature contributions must add up to the difference of prediction for xᵢ and the average prediction.</li><li>Symmetry: The contributions of two feature values j and k should be the same if they contribute equally to all possible coalitions.</li><li>Dummy: A feature j that does not change the predicted value — regardless of which coalition of feature values it is added to — should have a Shapley value of 0.</li><li>Additivity: For a game with combined payouts P₁ and P₂, the respective Shapley values should be ϕ₁ᵢ + ϕ₂ᵢ.</li></ol><p>For a model with a prediction function f(x) &amp; M features, we can obtain Shapley values as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*0gMGleWFLgVAD-5OMDllYg.png" /><figcaption>Notation: |M| is the total number of features. S represents any subset of features that doesn’t include the i-th feature and |S| is the size of that subset. fₓ() represents the prediction function for the model.</figcaption></figure><p>The above formula is a summation over all possible subsets (S) of feature values excluding the i-th feature value. Here, |S|! represents the number of permutations of feature values that appear before i-th feature value. Similarly, (|M|-|S|-1 )! represents the number of permutations of feature values that appear after the i-th feature value. The difference term in the above equation is the marginal contribution of adding i-th feature value to S. Also note that the above equation requires us to compute the model’s prediction for any subset of features, which may not be feasible for an ML model.</p><h4>SHAP from Shapley values</h4><p>SHAP values are the solutions to the above equation under the assumptions: <em>f(xₛ) = E[f(x|xₛ)]. i.e. the prediction for any subset S of feature values is the expected value of the prediction for f(x) given the subset xₛ.</em></p><p>The exact computation of SHAP values is computationally challenging. SHAP paper² describes two model-agnostic approximation methods, one that is already known (Shapley sampling values) and another that is novel &amp; is based on LIME (Kernel SHAP). SHAP paper also describes several model-type-specific approximation methods such as Linear SHAP, Tree SHAP, Deep SHAP etc. These methods assume feature independence and model linearity to simplify the computation of SHAP values. We will explore some of these methods in details in subsequent articles.</p><p><strong>Key contributions of the SHAP paper are</strong>:</p><ul><li>Identification of a new class of additive feature importance measures which unified six existing methods.</li><li>Theoretical results demonstrating that a unique solution exits for this class of methods with desirable properties.</li><li>New methods for computing feature importance values with improved computational performance and better consistency with human intuition.</li></ul><p><strong>Link to other articles in this series:</strong></p><p><a href="https://medium.com/@rakesh.melezhath/shap-part-2-kernel-shap-3c11e7a971b1">SHAP Part 2: Kernel SHAP</a></p><p><a href="https://medium.com/@rakesh.melezhath/shap-part-3-tree-shap-3af9bcd7cd9b">SHAP Part 3: Tree SHAP</a></p><p><strong>References:</strong></p><ol><li><a href="https://christophm.github.io/interpretable-ml-book/">Interpretable Machine Learning — A Guide for Making Black Box Models Explainable.</a></li><li>SHAP: A Unified Approach to Interpreting Model Predictions. arXiv:1705.07874</li><li>Miller, Tim. “Explanation in artificial intelligence: Insights from the social sciences.” arXiv Preprint arXiv:1706.07269. (2017)</li><li>Kim, Been, Rajiv Khanna, and Oluwasanmi O. Koyejo. “Examples are not enough, learn to criticize! Criticism for interpretability.” Advances in Neural Information Processing Systems (2016).</li><li><a href="https://www.youtube.com/watch?v=B-c8tIgchu0">Explainable AI for Science &amp; Medicine — Microsoft Research</a></li><li><a href="https://towardsdatascience.com/one-feature-attribution-method-to-supposedly-rule-them-all-shapley-values-f3e04534983d">https://towardsdatascience.com/one-feature-attribution-method-to-supposedly-rule-them-all-shapley-values-f3e04534983d</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58aa087a460c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/shap-part-1-an-introduction-to-shap-58aa087a460c">SHAP Part 1: An Introduction to SHAP</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Automatic Hyperparameter Optimization with Hyperopt]]></title>
            <link>https://medium.com/analytics-vidhya/introduction-to-automatic-hyperparameter-optimization-with-hyperopt-e0b9c84d1059?source=rss-6ca79b036138------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0b9c84d1059</guid>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[bayesian-optimization]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rakesh Sukumar]]></dc:creator>
            <pubDate>Thu, 19 Mar 2020 06:56:03 GMT</pubDate>
            <atom:updated>2020-03-24T12:38:08.993Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxHr_phzCyJfaU9UCvCyWw.png" /><figcaption>Image Credit: <a href="https://github.com/fmfn/BayesianOptimization">https://github.com/fmfn/BayesianOptimization</a></figcaption></figure><h4>What are parameters &amp; hyperparameters of machine learning model?</h4><p>Every machine learning model has a set of parameters &amp; hyperparameters that are set during the training process. Parameters are values that are learned directly from the training data such as coefficients in a linear/logistic regression model, split variables &amp; split values in a tree based model, weights in a neural network etc. Parameter values are estimated by the machine learning algorithm without any manual involvement.</p><p>Hyperparameters are values that determine the complexity of a machine learning model. An optimal choice of hyperparameters ensure that the model is neither too flexible where it picks up the noise in the training data (over-fitting), nor too rigid where it may loose important signals in the training data (under-fitting). Unlike parameters, hyperparameters cannot be learned directly from the training data and needs to be set by the machine learning practitioner. Number of predictors in a random forest/gradient boosting models, learning rate in neural networks, amount or regularization to use etc, are a few examples of hyperparameters. Hyperparameters are usually set by iteratively training the model for different sets of hyperparameter values and evaluating the model’s performance on a held out validation set or using cross validation.</p><p><strong>Methods of Hyperparameter Tuning</strong></p><p>Following are the common methods of hyperparameter tuning. Hyperparameter values that gives the best performance on a validation set will be chosen in all of these methods:</p><ul><li>Manual Tuning: Machine learning practitioner sets hyperparameter values based on his domain knowledge. He may try different sets of values before choosing the best one.</li><li>Grid Search: Models are tuned over a predefined grid of hyperparameter values set by the practitioner. All possible combinations of hyperparameter values defined by the grid are evaluated to select the best set.</li><li>Random Search: The machine learning practitioner provides a probability distribution of values to be evaluated for each hyperparameters. A specified number of samples are drawn from these distributions and the performance of the model is evaluated for each sample.</li><li>Bayesian Optimization: Bayesian optimization keeps track of the results of previous evaluations to choose the next set of hyperparameter values to be evaluated. We will discuss about Bayesian optimization in details in the following sections.</li></ul><h4>Bayesian Optimization</h4><p>Bayesian Optimization (also known as Sequential Model-Based Optimization (SMBO) ) uses the results of the past evaluations to form a probabilistic model of the objective function &amp; uses this model to choose the next set of hyperparameter values. The probabilistic model is called the “Surrogate model” and is represented by p(y|x); y being the performance metric for the model and x being the hyperparameter values. Here, the objective function is a function that maps the hyperparameter values to model’s chosen performance metric (such as RMSE, accuracy, ROC AUC etc) on a validation set (or using cross validation). The surrogate model is much easier to optimize compared to the actual objective function. The surrogate model approach can be used in scenarios where it is too expensive to evaluate the actual objective function in term of time or money (bayesian optimization techniques were originally developed for applications in oil exploration). Basic steps in bayesian optimization are:</p><ol><li>Build a surrogate model of the objective function using the results of past evaluations.</li><li>Find the hyperparameters that perform best on the surrogate model.</li><li>Evaluate the actual objective function (i.e. train the model &amp; evaluate the performance metric) with the hyperparameter values selected in step 2.</li><li>Update the surrogate model by adding the new results obtained in step 3.</li><li>Repeat 2 to 4 until a stopping criteria such as maximum iterations or time is reached.</li><li>Select the best performing hyperparameters from all the trials.</li></ol><p>A number of variants of bayesian optimization methods (hyperopt being one of them) are available for hyperparameter optimization for machine learning models. These methods differ by the type of surrogate model they build and the optimization criteria they use in step 2 of the algorithm above. Hyperopt uses Tree Parzen Estimator (TPE) as the surrogate model and Expected Improvement (EI) as the criteria to optimize the surrogate model.</p><p><strong>Tree-structured Parzen Estimators (TPE): </strong>Instead of directly modeling p(y|x), TPE model p(x|y) and p(y). TPE defines p(x|y) using two densities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*mmNH9LTV0I3cNbF-S58iuA.png" /></figure><p>where l(x) is the density formed by using observations xᵢ from past evaluations, such that the corresponding loss (i.e. the performance metric for the model) is less than some threshold y* and g(x) is the density formed by using the remaining observations. Here, we assume that we want to minimize the performance metric for the model (such as RMSE loss). In case we wish to use a metric that we need to maximize (such as accuracy, f1 score, ROC AUC etc), we just take the negative value of the metric and try to minimize the same. The TPE algorithm uses y* as some quantile γ of the observed values so that p(y &lt; y*) = γ.</p><p><strong>Expected Improvement (EI):</strong> Expected Improvement is the expectation under some model M of f(x) that f(x) will exceed (negatively) some threshold y*.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*UtqRSNCL_-2jepfxrgfalw.png" /></figure><p>Under TPE algorithm, it can be shown that maximizing EI amounts to choosing x values that minimizes g(x)/l(x). i.e. we would like points with high values under l(x) and low value under g(x). At each iteration, the algorithm draws several samples from l(x), evaluates them in terms of g(x)/l(x) and returns the candidate with highest EI¹.</p><h4>Hyperopt</h4><p>As explained above, Hyperopt uses Tree-Parzen Estimator to build the surrogate model and Expected Improvement as the optimization criteria. In addition, hyperopt requires the machine learning practitioner to define the following:</p><ol><li>Define the objective function that maps the hyperparameter values to model’s chosen performance metric.</li><li>Define a configuration space. A configuration space describes the domain (i.e. probability distribution for hyperparameters.) over which Hyperopt is allowed to search. This enables the machine learning practitioners to encode his domain expertise to assist hyperopt in identifying best hyperparameter values. A number of options are available in the hyperopt library for describing the probability distribution.</li><li>Choose a search algorithm. Hyperopt currently supports TPE algorithm and random search.</li><li>Specify a trials object to store intermediate results. This is optional.</li></ol><p>The hyperopt.hp module defines several hyperparameter distributions that can be used to specify the configuration space. Available options are:</p><ul><li>hp.choice(label, options): Returns one of the options. Options can be a list or a tuple or even a nested expression. Nested expression format allows us to specify conditional parameters which comes handy if we need to optimize between different types of machine learning models. Example: Between boosting or random forest or between different architectures of neural network models. We will see a code example that illustrates this option.</li><li>hp.pchoice(label, p_options): Similar to hp.choice() but with a probability specified for each option.</li><li>hp.uniform(label, low, high): A uniform distribution between low and high (both ends included).</li><li>hp.quniform(label, low, high, q): Distribution given by q*round(uniform(low, high)/q). Suitable for hyperparameters that take discrete values.</li><li>hp.loquniform(label, low, high): Distribution given by exp(uniform(low, high)). The hyperparameter will be constrained to the interval [eˡᵒʷ, eʰⁱᵍʰ]</li><li>hp.normal(label, mu, sigma): A normally distributed variable. While optimizing, this hyperparameter is unconstrained.</li><li>hp.qnormal(label, mu, sigma, q): Distribution given by q*round(uniform(mu, sigma)/q). This variable is also unconstrained.</li><li>hp.lognormal(label, mu, sigma): Distribution given by exp(normal(mu, sigma)). This variable is constrained to be positive.</li><li>hp.qlognormal(label, mu, sigma, q): Distribution given by q*round(exp(normal(mu, sigma))/q). This variable is constrained to be positive.</li><li>hp.randint(label, upper): Returns a random integer in the range [0, upper). This distribution assumes no correlation in loss function between nearby integer values (Eg. for random seed values).</li></ul><h4>Hyperopt in Action</h4><p>Let’s use the Bank marketing data from UCI Machine Learning Repository to demonstrate the working of hyperopt. The data is related with direct marketing campaigns of a Portuguese banking institution. The marketing campaigns were based on phone calls. The target variable is whether the client has subscribed for a term deposit from the bank. A number of variables related to the client, the marketing campaign, previous contact with the client, and socio economic indicators are available as explanatory variable. Four datasets are available in UCI site, we will use the file “ bank-additional-full.csv”. You can read more about the dataset <a href="https://archive.ics.uci.edu/ml/datasets/Bank+Marketing">here</a>. We will use Google colab to run our code. The code file is uploaded <a href="https://github.com/Rakeshsuku/Medium-Blog">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wp3_xOaBAuhNjBgmsXTzXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MuV-g_HtvdHhWZyZ3yR0Dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dYkzSggwr1RyMHUW1LKmA.png" /></figure><p>We see that the data set is unbalanced with just 4640 clients subscribing to the term deposit out of 41188 clients in the dataset. As per the dataset information in the UCI website the “duration” variable, which records the duration of the call with the client, is highly correlated with the target. Since this information is not available to the bank before making the call, we will discard this variable. Also note that the value “999” in “pdays” is actually a missing value indicator which indicates that the client was not contacted before by the bank. Let’s drop the “duration” variable and copy our target to a new variable y. We will also create a binary variable for “previously not contacted by the bank” and replace “999” in “pdays” with nan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPHiXotuWR6dANUjvsiUxA.png" /></figure><p>Next, we split the data into training and test sets and perform label encoding for categorical variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sw22QXsOP4o4naG9Z6Nhkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1q3b4K8cIDNpRmAIzX0Ow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cQH0MZP1MzOtxSi1o21_A.png" /></figure><p>Let’s fit an XGBoost model as a baseline model. We will use ROC AUC as the evaluation criteria as we have an unbalanced classification problem. Note that we haven’t used early stopping here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6M2EX-lmgE3J7CsLh51B3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZumbpQ6xz86M3IwkPhlRsA.png" /></figure><p>Next, we will use hyperopt to optimize the hyperparameters for this model. First we will define a function that computes ROC AUC on the test set for a given set of hyperparameter values. Note that we return a dictionary as output from this function. Hyperopt minimizes the ‘loss’ values in the output dictionary, hence we return -1 * ROC AUC as loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*peUd0q7fOZrUjJmfQzUxbQ.png" /></figure><p>default_params are hyperparameters that we do not wish to tune. The values in default_params will be ignored if we pass the same hyperparameter in the argument “params” to hyperopt_xgb_train() function. Note that we are not tuning for “num_round” here; we will rather use early stopping when we fit the final model. Let’s test this function with hyperparameter values we used before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTaqRp66VVvbxVTIkWiUQQ.png" /></figure><p>Next, we will define two function that will help us visualize the configuration space (i.e. the probability distribution) for the hyperparameters tuned. We will visualize both of the following:</p><ul><li>The probability distribution that we define and provide as input to hyperopt based on our domain knowledge (plot_params_space()).</li><li>The distribution of hyperparameter values that hyperopt actually tires based on previous evaluation history. (plot_params_tried()). This function also returns a dataframe with the results of all trials.</li></ul><p>This will help us get a clear understanding of the workings of hyperopt. Note that the plotting functions defined below does not work with nested configuration spaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgpvshmTXJIh-m9sM_mTaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfrhaKo1HudcRQogCvO0OQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zkgS8np6vMnbderYiaUkA.png" /></figure><p>Let’s define the configuration space for the xgb model and visualize the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kuQD75diT17E-aIMGARVAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JCMEpFvWmO1D3kEFoWn4g.png" /></figure><p>Note the use of pyll.scope.int() function to convert max_depth values to integers types. hyperopt.pyll.scope module allows us to use custom functions in the defining the probability space for hyperparameters. See the hyperopt paper² for more examples.</p><p>We will define a trials object to store the results of all evaluations that the hyperopt makes. We will also use this object to plot the results of the evaluation. If trials object is not provided, the fmin() function below will return only the best hyperparameter value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvmeIHzc_XdSeYaSNTzRtA.png" /></figure><p>The fmin() function is the workhorse that performs the hyperparameter optimization. The first argument to fmin is the objective function &amp; the second argument is the configuration space. Other argument to fmin() are:</p><ul><li>algo: specifies the optimization algorithm to use. Available option are ‘tpe.suggest’ (implements bayesian optimization with TPE algorithm); and ‘rand.suggest’ (implements random search).</li><li>max_evals: Number of evaluations to be carried out.</li><li>trials: Trials() object to save results of all evaluations carried out by hyperopt. The .trials attribute of the Trials object is a list with an element for every evaluation made by fmin.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AcblYXwiduQaiaabhInrbA.png" /></figure><p>We get the best auc roc score of about 0.82 for the above hyperparameter values. Note the use hyperopt’s space_eval() function to get the hyperparameter values from best. space_eval() is required as best will have integer indices for any hyperparameter that is defined by hp.choice(). Let’s plot the results of evaluations done by hyperopt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnAqRHxqT5Hn3K2M-LC1pg.png" /></figure><p>We can see that the distribution of values evaluated by hyperopt is very different from the distributions we defined. Let’s also plot a scatter plot of hyperparameter values against the loss (-ve of ROC AUC).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsiZsv2sYkZGxYpjJ-DeWQ.png" /></figure><p>The hyperparameter values that gave the best results are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26ALUWfH1ll1GFsuLVsZXw.png" /></figure><p>For the final model, we will increase num_round to 1000 and enable early stopping with 50 rounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VM0JBt8uKYjsfXxIp_gvMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYtKefJgM0ffxYuM409tYg.png" /></figure><p>Note that xgboost.train() will return a model from the last iteration (iteration 147 here), not the best one. We can get the best iteration as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLlM9oI2gzcGnIXYsZi2kQ.png" /></figure><h4>Nested Configuration Space</h4><p>Next, we will use a nested configuration space to simultaneously tune an xgboost model and a random forest model &amp; select the best performing model. We will also draw a few samples to see what we get from this nested configuration space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCK6etne4emG-lNPNTzMLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fv4ZWMTjdeyOcOKnG0ZOBA.png" /></figure><p>Next, we will create an objective function for this nested configuration space. We will replace the missing values in pdays column with median for the random forest model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxd5osPMvbGFHedqosIgyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgEZwSczG-nJB7jBzGkt7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrR6MC9x9oXvqHJCinftxw.png" /></figure><p>Find the code file uploaded <a href="https://github.com/Rakeshsuku/Medium-Blog">here</a>.</p><h4>References</h4><ol><li>Bergstra, James &amp; Bardenet, R. &amp; Kégl, Balázs &amp; Bengio, Y.. (2011). Algorithms for Hyper-Parameter Optimization.</li><li>Hyperopt: A Python Library for Optimizing the Hyperparameters of Machine Learning Algorithms by James Bergstra , Dan Yamins , David D. Cox</li><li><a href="https://towardsdatascience.com/a-conceptual-explanation-of-bayesian-model-based-hyperparameter-optimization-for-machine-learning-b8172278050f">A Conceptual Explanation of Bayesian Hyperparameter Optimization for Machine Learning by Will Koehrsen</a></li><li><a href="https://districtdatalabs.silvrback.com/parameter-tuning-with-hyperopt">Parameter Tuning with Hyperopt by Kris Wright</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0b9c84d1059" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/introduction-to-automatic-hyperparameter-optimization-with-hyperopt-e0b9c84d1059">Introduction to Automatic Hyperparameter Optimization with Hyperopt</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>