<?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 Anuj shah (Exploring Neurons) on Medium]]></title>
        <description><![CDATA[Stories by Anuj shah (Exploring Neurons) on Medium]]></description>
        <link>https://medium.com/@anuj_shah?source=rss-c7f54cd28926------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hjuszeYo1AcC168rlz1nIQ.jpeg</url>
            <title>Stories by Anuj shah (Exploring Neurons) on Medium</title>
            <link>https://medium.com/@anuj_shah?source=rss-c7f54cd28926------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:39:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anuj_shah/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[Artificial Intelligence will get Self-Aware (My View).]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">&#x201C;The intelligent alien species that we have been waiting for to come from outer space are in fact here itself on earth, and as a matter of&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@anuj_shah/artificial-intelligence-will-get-self-aware-my-view-f99ef9d71182?source=rss-c7f54cd28926------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@anuj_shah/artificial-intelligence-will-get-self-aware-my-view-f99ef9d71182?source=rss-c7f54cd28926------2</link>
            <guid isPermaLink="false">https://medium.com/p/f99ef9d71182</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[self-aware-ai]]></category>
            <category><![CDATA[agnetic-ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Anuj shah (Exploring Neurons)]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 10:35:26 GMT</pubDate>
            <atom:updated>2026-09-13T10:35:26.272Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why is Exact Bayesian Inference Intractable for Deep Networks?]]></title>
            <link>https://medium.com/@anuj_shah/why-is-exact-bayesian-inference-intractable-for-deep-networks-de6c668c6133?source=rss-c7f54cd28926------2</link>
            <guid isPermaLink="false">https://medium.com/p/de6c668c6133</guid>
            <category><![CDATA[bayesian-neural-network]]></category>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <category><![CDATA[bayesian-learning]]></category>
            <dc:creator><![CDATA[Anuj shah (Exploring Neurons)]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 13:02:22 GMT</pubDate>
            <atom:updated>2025-02-28T13:02:22.249Z</atom:updated>
            <content:encoded><![CDATA[<p>Bayesian inference aims to compute the <strong>posterior distribution</strong> over the model parameters <em>w</em> given the data <em>D</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*6LV9aYoI5COVBcCy3NStgw.png" /></figure><h3>Why is this Integral Intractable?</h3><p>For deep neural networks, this integral is <strong>computationally intractable</strong> due to:</p><h4>1️. High-Dimensional Parameter Space</h4><ul><li>Deep networks have <strong>millions</strong> of parameters <em>w</em>.</li><li>Computing the posterior requires integrating over all possible weight values.</li><li>This is exponentially complex and cannot be done analytically.</li></ul><h4>2️. No Closed-Form Solution</h4><ul><li>Bayesian inference in simple cases (like Gaussian conjugate priors) has closed-form solutions.</li><li>However, deep networks have <strong>nonlinear</strong> activations (ReLU, sigmoid, etc.), making the integral <strong>non-analytical</strong>.</li></ul><h4>3️. Dependence Between Parameters</h4><ul><li>In deep networks, weight updates are highly <strong>correlated</strong> across layers.</li><li>This correlation prevents factorizing the posterior into independent components, making exact inference harder.</li></ul><h4>4️. Expensive Marginalization Over All Parameters</h4><ul><li>Exact Bayesian inference requires evaluating <strong>every possible configuration</strong> of weights.</li><li>For a deep network, this means solving an <strong>integral over a high-dimensional space</strong> — which is practically impossible.</li></ul><h3>🚀 How Do We Approximate Bayesian Inference?</h3><p>Since exact inference is intractable, we approximate it using:</p><p>✅ <strong>Variational Inference (VI)</strong>: Approximate <em>P(w∣D)</em> with a simpler distribution <em>q(w∣θ)</em> and minimize KL divergence.<br>✅ <strong>Monte Carlo Sampling (MCMC, SGLD)</strong>: Estimate posterior using stochastic sampling methods.<br>✅ <strong>Laplace Approximation</strong>: Approximate posterior with a Gaussian around the MAP estimate.<br>✅ <strong>Bayesian Neural Networks (BNNs)</strong>: Use reparameterization and VI to learn an approximate posterior.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de6c668c6133" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Calibration for Regression]]></title>
            <link>https://medium.com/@anuj_shah/model-calibration-for-regression-c9633eab061d?source=rss-c7f54cd28926------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9633eab061d</guid>
            <category><![CDATA[model-calibration]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[uncertainty-estimation]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[responsible-ai]]></category>
            <dc:creator><![CDATA[Anuj shah (Exploring Neurons)]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 06:37:36 GMT</pubDate>
            <atom:updated>2025-07-01T07:24:15.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Requirements</h3><ol><li>One requirement to read this blog is that you understand the concept behind model calibration and how it is done for classification problem</li><li>I have a detailed blog for the same —<a href="https://medium.com/@anuj_shah/model-calibration-a-step-towards-trustworthy-and-reliable-ai-1181f2fef2c3"> Model Calibration: A Step Towards Trustworthy and Reliable AI</a></li></ol><h3>Let’s get Started</h3><p>Besides the accuracy of the model, it is equally important to ensure its reliability to use in real-time. Model calibration ensures that the models are reliable and their predictions can be trusted.</p><p>In classification problems, the predicted confidence can be used as a measure of uncertainty provided they are well-calibrated, and well-calibrated means if the confidence is 90% then it should be correct 90% of the time.</p><p>However, in regression tasks, we don&#39;t have such confidence scores, the real values are predicted directly. We can use the notion of <a href="https://www.investopedia.com/terms/c/confidenceinterval.asp#:~:text=A%20confidence%20interval%20displays%20the,hypothesis%20testing%20and%20regression%20analysis.">confidence interval</a> but for that, we need the distribution rather than a single real-valued output.</p><p>Most of the implementations just predict the single output and not the entire distribution. One way to measure the uncertainty for regression would be to make the network predict the output distribution and not just single output, and then the predicted variance can be used as an uncertainty measure. The most easily understood distribution to imagine is the <a href="https://en.wikipedia.org/wiki/Normal_distribution">gaussian distribution</a> defined by two parameters — the mean and variance</p><p>Further, like in classification the way we ensure the model is calibrated, and if not then we calibrate the predicted confidence before using it as an uncertainty/ reliability measure, in regression as well we need to ensure our model is calibrated which means that the predicted variance reflects the actual residual error and if not we need to calibrate this variance before we can use it as uncertainty/reliability measure.</p><p>With the above arguments, the steps we need to follow for model calibration in the regression problem</p><ol><li>Modify the regression network to give probabilistic output, i.e. predicting the output distribution and not just the single output value. The variance of the predicted output distribution can be used as an uncertainty measure (similar to confidence in classification can be used as an uncertainty measure)</li><li>Modifying the loss to learn the variance. please note that we don’t need a separate ground truth to learn the variance. just a slight modification in the loss can help to learn the variance</li><li>Before we use the variance as our uncertainty measure, we need to ensure the model is calibrated. so we need to measure the calibration error (like we measured in classification with ECE, ACE, etc.,.)</li><li>Calibrate the model with methods like Platt scaling, isotonic regression</li></ol><h3>Modifying the regression network to output distribution rather than a single output (going from deterministic to probabilistic)</h3><p>One of the most common distributions to model our output would be the Gaussian distribution.</p><p>A Gaussian distribution is defined by two parameters — the mean and variance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*3eLtAPFHyAIi6t2wi7Cquw.png" /></figure><p>so to emulate this we need to have an additional output from our network. The good part is that we do not need a ground truth for the variance to learn from. below is the diagram showing how we can convert a deterministic network that predicts point estimate to a probabilistic network that predicts the output distribution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kiyBLIffT-sIt2FDAoWXMA.png" /></figure><p>In practice, the model is made to learn log(variance) for numerical stability</p><h3>Modifying the loss to learn the variance</h3><p>Usually, for learning regression problems, the loss function we use is MSE or MAE.</p><p>The MSE is actually derived from the Gaussian function and the mae is derived from the Laplacian distribution</p><p>Let&#39;s see how we define Negative Log Likelihood assuming the Gaussian distribution and then how it boils down to Mean Square Error when we learn the point estimate</p><p>Assuming the above Gaussian density estimation, the output likelihood will take the same for,</p><p>Let&#39;s say the ground truth is represented by y_i and the prediction from the model is represented by f(x_i)=<strong>μ</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*jAs3thdmKDr-gEZCndyZEw.png" /></figure><p>Now taking the log of likelihood</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHyzunSbnZ5TFdfgMpMU_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*beA8LyuSkgJKjfTlGyHtww.png" /></figure><p>For optimization either we maximize the likelihood or we minimize the likelihood. We mostly consider minimizing so we will take negative log-likelihood as our loss function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rh9ydWGPo_YEDj3rt926uA.png" /></figure><p>For the network where we learn point estimate the sigma is either 1 or constant so the term that will be optimized is only the right-hand side term. so for point estimate, the NLL (loss functions) becomes the mean square error between ground truth and the predicted value from the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*opG80-f7zdGc-C74ecktfg.png" /></figure><p>Whereas for the model that predicts the entire distribution, both the terms are optimized. so the NLL (Loss function) for the probabilistic output will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*MprJUKLRmMNV_9nflslPHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5J05UoxlRlImn1x_YiU4Wg.png" /></figure><p>Similarly, if we are using MAE, we can modify the network to give Laplacian distribution and modify the loss accordingly. we will take the topic of Laplacian distribution at the end. Now let&#39;s continue once we have modified the network to predict the probabilistic output</p><h3>Measuring Calibration</h3><blockquote>For regression tasks the calibration can be defined such that predicted confidence intervals should match the confidence intervals empirically computed from the data set (Kuleshov et al. 2018), i.e.</blockquote><p>To measure the calibration of classification we used the predicted confidence and the true confidence in different bins, where each bin measured a range of confidence. Also as confidence is used as an uncertainty measure we calibrated the confidence.</p><p>The below table shows the ECE computation for the classification problem,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*8rfv1swW9_n0nvDR.png" /></figure><p>In regression problems we don’t have any confidence in the prediction, the prediction is a real number. Also, in regression problems, since the predicted variance is a measure of uncertainty, we need to make sure that the predicted variance is calibrated. This can be done by making sure that the predicted error (variance/std) is equal to the actual error (Predicted mean — ground truth = residuals)</p><h4>Confidence Interval Revision</h4><p>Before moving ahead let&#39;s revise one more concept of the confidence interval, as we can use the confidence interval of the predicted variance for plotting against the residuals</p><p><strong>Confidence Interval</strong></p><p>In the context of a regression problem, a confidence interval provides a range of values that is likely to contain the true value with a certain confidence level</p><p>For example, based on various environmental data sensor measurements the ML model estimated a rainfall of 45 inches with a 95% confidence interval of [43, 47] inches. This means you’re 95% confident that the amount of rainfall you will receive falls within the interval [43, 47].</p><p><strong>Interpretation:</strong> Here’s how you typically interpret a confidence interval:</p><p>If you were to observe the amount of rainfall many times, let&#39;s say 100 days, it will not always be 45, it may be 46, 44.5, or even, 41 but 95% of the time it will be in the range of 43 to 47, that is among 100 days 95 days would have rainfall in the range of 43 to 47.</p><p><em>thus confidence intervals give the notion of uncertainty in your predictions</em></p><p><strong>Significance Level:</strong> The choice of the confidence level (e.g., 95%) is often referred to as the significance level or alpha (α). Common choices include 90%, 95%, and 99%, but you can choose a level that fits the requirements of your analysis.</p><p>Now the question is how to identify the values for this 95% CI, in the above examples, given our predicted distribution of certain mean and std, how to find the range of value which will contain the 95% of the predictions, how to get the number 43 and 47.</p><p>To understand that let&#39;s compare a simple Gaussian function with mean 0 and std 1. We can compute the confidence interval using Scipy norm.stats.</p><p>So we can compute the confidence interval by computing the percentile. I have discussed the percentile in detail here — <a href="https://medium.com/@anuj_shah/quantile-percentile-one-tail-and-two-tail-distribution-confidence-interval-box-plot-ce80b1b6db37">Quantile, Percentile (one tail and two tail distribution), Confidence Interval, Box Plot</a></p><p>So basically the 50th percentile means the value in the data below which you have 50% of the data.</p><p>for a two-tail distribution (which is our case) we compute the 50% data about the mean so 25% to the left of the mean and 25 % to the right of the mean.</p><p>Below is the figure for one-tail and two-tail distribution for the 50th percentile or computing values in the data which will have 50% of the data. The distribution is a standard normal Gaussian with mean 0 and std 1.</p><pre>from scipy import stats as stats<br>norm = stats.norm(loc=0, scale=1)<br>data_percent = 0.5<br># Significance level (alpha) for a two-tailed test<br>alpha = data_perecent ==&gt; 0.5<br># Calculate the critical values for the tails<br>critical_value = norm.ppf(alpha) ==&gt; norm.ppf(0.5)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gs59Q3nnc7jccgbr9VRlrw.png" /><figcaption>For one tail distribution the 50th percentile, the value below which 50% of the data will be q=0.0</figcaption></figure><pre>from scipy import stats as stats<br>norm = stats.norm(loc=0, scale=1)<br>data_percent = 0.5<br># Significance level (alpha) for a two-tailed test<br>alpha = 1-data_perecent ==&gt; 0.5<br># Calculate the critical values for the tails<br>critical_value_left = norm.ppf(alpha / 2) ==&gt; norm.ppf(0.25)<br>critical_value_right = norm.ppf(1 - alpha / 2) ==&gt; norm.ppf(0.75)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UD0cTE0Ej6xZA8pnlSsdg.png" /><figcaption>For two-tail distribution, the 50th percentile, the value of lower alpha is 0.25 and upper alpha is 0.75, and computing its ppf gives the value which contains 50% of data about the mean is -0.67 and 0.67 respectively</figcaption></figure><p>Now coming back to the rainfall example where the predicted value was 45,. Let&#39;s say the predicted distribution was a Gaussian with a mean of 45 and a standard deviation of 2. Now let&#39;s compute the 95% confidence interval for this</p><pre>from scipy import stats as stats<br># define the gaussian function<br>norm = stats.norm(loc=45, scale=1<br>data_percent = 0.95<br># Significance level (alpha) for a two-tailed test<br>alpha = 1-data_perecent ==&gt; 0.05<br># Calculate the critical values for the tails<br>critical_value_left = norm.ppf(alpha / 2) ==&gt; norm.ppf(0.025) ==&gt; 43.05<br>critical_value_right = norm.ppf(1 - alpha / 2) ==&gt; norm.ppf(0.975) ==&gt; 46.96</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBN7gAEjokxv0azB4e3NHQ.png" /></figure><p>so the 95% confidence interval is [43,47].</p><p>one more trick before we go back to calibration is that suppose you want to compute the ppf for a normal function with mean and mean other than 0 and, we can do it in two ways</p><pre><br>Example-1<br><br>Gausian Distribution ==&gt; N(0,5)<br>Mean = 0 ; std = 5<br><br>Method-1<br>norm1 = stats.norm(loc=0, scale=1)<br>norm1.ppf(0.8) ==&gt; 0.84162<br>final value = norm1.ppf(0.8)*std + Mean<br>            = 0.84162*5 ==&gt; 4.2081<br><br>Method-2<br>norm2 = stats.norm(loc=0, scale=5)<br>final value = norm2.ppf(0.8) ==&gt; 4.2081<br><br>Example-2<br><br>Gausian Distribution ==&gt; N(10,5)<br>Mean = 10 ; std = 5<br><br>Method-1<br>norm1 = stats.norm(loc=0, scale=1)<br>norm1.ppf(0.8) ==&gt; 0.84162<br>final value = norm1.ppf(0.8)*std + Mean<br>            = 0.84162*5 + 10 <br>            = 4.2081 + 10 ==&gt; 14.2081<br><br>Method-2<br>norm2 = stats.norm(loc=10, scale=5)<br>final value = norm2.ppf(0.8) ==&gt; 14.2081</pre><p><strong><em>Please note we are going to use method -1, that is compute the std multiplier for N(0,1) and multiply with the std of the predicted distribution</em></strong></p><h4>Coming back to measuring calibration</h4><p><em>For the classification task, the calibration can be defined as such that the predicted confidence should match the observed confidence (accuracy)</em></p><p><em>For regression tasks the calibration can be defined such that predicted confidence intervals should match the confidence intervals empirically computed from the data set (observed confidence interval)</em></p><p>let&#39;s bring back the reliability plot of the classification</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*qe0rytVuZH3JjWWZ.png" /></figure><p>For the regression problem let&#39;s take the example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdkApT3dUqfc-gcNSxpptw.png" /></figure><p>now I will show how to compute the confidence interval of 20% and 95% for the third sample X3 with mean 50 and std 3</p><pre>from scipy import stats as stats<br># define the gaussian function<br>norm = stats.norm(loc=50, scale=3)<br>### for 20% confidence interval<br>data_percent = 0.2<br># Significance level (alpha) for a two-tailed test<br>alpha = 1-data_perecent ==&gt; 0.8<br># Calculate the critical values for the tails<br>critical_value_left = norm.ppf(alpha / 2) ==&gt; norm.ppf(0.4)<br>critical_value_right = norm.ppf(1 - alpha / 2) ==&gt; norm.ppf(0.6)<br>print(critical_value_left,critical_value_right)<br><br>49.2399586905926 50.7600413094074<br><br>### for 95% confidence interval<br>data_percent = 0.95<br># Significance level (alpha) for a two-tailed test<br>alpha = 1-data_perecent ==&gt; 0.05<br># Calculate the critical values for the tails<br>critical_value_left = norm.ppf(alpha / 2) ==&gt; norm.ppf(0.025)<br>critical_value_right = norm.ppf(1 - alpha / 2) ==&gt; norm.ppf(0.975)<br>print(critical_value_left,critical_value_right)<br><br>44.12010804637984 55.87989195362016</pre><p>Similarly for all other samples</p><p>let&#39;s take the above example that our model predicted the amount of rainfall</p><p>predicted mean = 45, predicted_std =1</p><p>from the above distribution, we computed the different confidence interval values</p><p><strong>For a 95% confidence interval</strong></p><p>the predicted range is between 43 and 47 so the allowed error is within -2 to +2 or we take the absolute value the allowed error is 2 as per the prediction</p><p>Predicted Error = +-2</p><p>now let&#39;s compute the actual error</p><p>case 1: if GT value = 48</p><p>Actual Error = abs(45–48) = 3, which is higher than the predicted error of 2, so the model is miscalibrated</p><p>case 2: if GT value = 44</p><p>Actual Error = abs(45–44) = 1, which is less than equal to the allowed error of 2 so, the model is uncalibrated for a 95% confidence interval</p><p>Now let&#39;s plot a reliability plot for the regression problem same as the classification problem.</p><p>References</p><ol><li><a href="https://stackoverflow.com/questions/60699836/how-to-use-norm-ppf">https://stackoverflow.com/questions/60699836/how-to-use-norm-ppf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9633eab061d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Calibration — A step towards trustworthy and reliable AI]]></title>
            <link>https://medium.com/@anuj_shah/model-calibration-a-step-towards-trustworthy-and-reliable-ai-1181f2fef2c3?source=rss-c7f54cd28926------2</link>
            <guid isPermaLink="false">https://medium.com/p/1181f2fef2c3</guid>
            <category><![CDATA[deeplearing]]></category>
            <category><![CDATA[probabilistic-learning]]></category>
            <category><![CDATA[uncertainty-estimation]]></category>
            <category><![CDATA[model-calibration]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Anuj shah (Exploring Neurons)]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 05:28:06 GMT</pubDate>
            <atom:updated>2024-03-30T16:19:20.900Z</atom:updated>
            <content:encoded><![CDATA[<h3>Model Calibration — A step towards trustworthy and reliable AI</h3><p>Before I start the topic I would like to thank the people who introduced me to this very important topic - My colleague <strong>Dr. Christian Wirth</strong> and this <a href="https://www.youtube.com/watch?v=FkfDlOnQVvQ">talk</a> by<strong> Inbar Naor</strong> from PyCon Israel 2018.</p><p>And in this blog post, I would like to share my learnings on the same</p><p>As AI models are being widely used in our day-to-day lives, it becomes very crucial that these models can be trusted, especially for high-risk applications like automotive, healthcare, manufacturing, etc.</p><p>We will try to answer the following questions in this blog</p><ol><li>What do we mean by model calibration? How does a well-calibrated model differ from an ill-calibrated model?</li><li>Why do we need a calibrated model?</li><li>Why calibration is required in modern deep neural networks</li><li>How to measure the model’s calibration?</li><li>How to calibrate a model? (Incomplete)</li><li>Can we use the same approaches discussed above for a regression problem? (To Do)</li></ol><h3><strong>Question 1: What do we mean by model calibration? How does a well-calibrated model differ from an ill-calibrated model?</strong></h3><p>I would like to start with a picture from Inbar’s talk</p><p><strong><em>Note:</em></strong><em> in classification problems, we can consider the predicted probabilities as their confidence.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kbyqx-VkuI-gNz-pww_Llw.png" /><figcaption>image credit: <a href="https://www.youtube.com/watch?v=FkfDlOnQVvQ">Inbar Naor</a></figcaption></figure><p>Well, Model A is better because if a model is 90% accurate in its prediction(correctly predicting 9 out of 10 samples) then its confidence should be 90% too.</p><p>Model B is overconfident, as its confidence is 99% but the accuracy is 90%</p><p>If there was a Model C with an accuracy of 90% and 0.8 confidence in each prediction it would have been an underconfident model</p><p>so a <strong>model with an accuracy of 90% and 0.9 confidence</strong> is considered a <strong>well-calibrated model.</strong></p><p>The model with an <strong>accuracy of 90%, 0.99 confidence</strong> (overconfident), and the model with an <strong>accuracy of 90%, 0.8 confidence</strong> (under-confident) are <strong>ill-calibrated</strong>.</p><blockquote>By definition, <strong>We say that a model is well calibrated when a prediction of a class with confidence p is correct 100p % of the time.</strong></blockquote><p>Thus model calibration refers to approaches (mostly post-processing) that render a well-calibrated model.</p><p>Below is the reliability plot (discussed further section) of an ill-calibrated and well-calibrated model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7BFn7-Ks0ZYMdy18_s2BQ.png" /><figcaption>Right: For a well-calibrated model the predicted confidence and observed confidence are the same for each confidence value. whereas Left: for a miscalibrated model the observed confidence is less than the predicted confidence (over-confidence) or the observed confidence is higher than the predicted confidence (under-confidence)</figcaption></figure><h3>Question 2: Why is Model Calibration Important?</h3><p>Let’s take an example of covid scenario where the load on the healthcare system and doctors were immense. An AI algorithm for COVID-19 detection has been developed to reduce the workload on doctors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSBEm60_R7XjC3JXKNPNKw.png" /><figcaption>covid test cartoon ref: <a href="https://www.horizonhealthnews.com/covid-19-testing-is-it-still-free-for-me/">https://www.horizonhealthnews.com/covid-19-testing-is-it-still-free-for-me/</a></figcaption></figure><p>Only if the predicted probability of covid-19 is greater than 90%, the patient is sent to the doctor for further check-up. Now in this scenario, if the model is not calibrated then it could be fatal. Say, if the model is overconfident, most of the patients will be sent to doctors, further increasing the workload, and if the model is underconfident, then there are chances that the COVID-19 patient does not get the required treatment as it was underconfident with a probability less than 90%.</p><p>In both scenarios, it will have an impact (although the false negative will have a higher impact).</p><p>Hence a well-calibrated model is always desirable.</p><p>As Inbar says in her talk— “Calibration is important if probabilities are important”</p><p>Model calibration is very important when you rely on the probability score to make decisions such as in health care, automotive, and manufacturing industries where you may use some threshold to make decisions based on the probability score.</p><p>So for the above example, the covid detection AI model will be calibrated when the confidence of the model is 90% and it detected 9/10 covid patients accurately</p><p>This is also very important in active learning scenarios where you need to use the probability score to estimate the uncertainties by approaches like Least confidence sampling, Marginal sampling, and Entropy sampling.</p><p>Based on the uncertainty score the samples are selected for labeling or the next iteration of training</p><p>One more scenario as described by Inbar is for analyzing and debugging the model as to why the mistakes were made with high probabilities or the true prediction had a low probability</p><p>To summarize as to why we need model calibration</p><ul><li>If we rely on the model’s prediction (say the probability score for the classification model) to make the decision, they need to be calibrated</li><li>As more and more neural networks are getting deployed in the real world, we need to make sure that the predictions made by those models are reliable.</li><li>It was observed that the shallow networks were well calibrated but the modern deep neural networks albeit very powerful in learning myriad of complex problems tend to be ill-calibrated.</li><li>This becomes also important for uncertainty estimation as we treat the predicted probability as our confidence and make decisions around this probability score, we need to be sure about this, say for instance in the medical domain when the predicted score of the model is 80% you don’t consider visiting doctor but if it’s below 80 you consider visiting doctor</li><li>For analyzing and debugging the model as to why the mistakes were made with high probabilities or the true prediction had a low probability</li></ul><p><strong>The predicted probability score should reflect the true nature of the model.</strong></p><p><strong>Things to care about, Model calibration!=Accuracy</strong></p><p>A well-calibrated model may have low accuracy whereas a model with high accuracy can be ill-calibrated (Model B in the above example).</p><p>We need to consider both. Sometimes calibrating the model may hurt its accuracy.</p><p>Coming to choice, a well-calibrated model is better than a high-accuracy model as it will reflect the true nature of the model’s predictions</p><p><a href="https://wttech.blog/blog/2021/a-guide-to-model-calibration/">A guide to model calibration</a></p><p><a href="https://deepchecks.com/glossary/model-calibration/">https://deepchecks.com/glossary/model-calibration/</a></p><h3>Question 3: Why calibration is required in modern deep neural networks?</h3><p>Modern deep neural networks have often been observed to be overconfident as first discussed by the 2017 paper from Chuan Guo, Geoff Pleiss, Yu Sun, Kilian Q. Weinberger: <a href="https://arxiv.org/pdf/1706.04599.pdf">On calibration of modern neural networks</a>. From the paper</p><blockquote>We discover that modern neural networks, unlike those from a decade ago, are poorly calibrated. Through extensive experiments, we observe that depth, width, weight decay, and Batch Normalization are important factors influencing calibration.</blockquote><p>This is mostly due to an increase in the number of parameters in modern neural networks</p><p>We can see from the below image that for ResNet, the average confidence is much higher than the average accuracy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*3ydjnnW5FNQKOqyUhreoWQ.png" /><figcaption>Image credit: <a href="https://arxiv.org/pdf/1706.04599.pdf">On calibration of modern neural networks</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTpw8nrqGlohQzXCyfSusA.png" /><figcaption>Image credit: <a href="https://arxiv.org/pdf/1706.04599.pdf">On calibration of modern neural networks</a></figcaption></figure><p>The ECE denotes the calibration error. Lower ECE denotes a well-calibrated model</p><p>It was observed that although the above techniques of increasing depth, filters per layer, Batch normalization, and weight decay are quite important to improve the learning of the models and solve the task, these features tend to miscalibrate the models and hence calibrating the models becomes important. But before we can calibrate the model we need to measure how much miscalibrated the model is ?</p><h3><strong>Question 4: How to measure the model Calibration?</strong></h3><p>1. <strong>Proper Scoring Rules</strong></p><ul><li>Negative Likelihood</li><li>Brier Score</li></ul><p>2. Visually using <strong>Model calibration curves/Reliability Diagram.</strong></p><p>3. Quantitatively using <strong>Calibration Error Metrics</strong></p><ul><li>Expected Calibration Error and Maximum Calibration Error.</li><li>Static Calibration Error</li><li>Adaptive Calibration Error</li><li>Thresholded Adaptive calibration error</li></ul><h4>Proper Scoring Rules</h4><blockquote>From the paper : <a href="https://arxiv.org/pdf/2011.10671.pdf">https://arxiv.org/pdf/2011.10671.pdf</a></blockquote><blockquote>In the context of machine learning, good predicted probability distributions need to be sharp, but ideal predicted probability distributions should be both sharp and well-calibrated</blockquote><blockquote>we can evaluate both the calibration and sharpness of probability distributions by using proper scoring rules. A scoring rule 𝑆(𝑝(y|x,D),y𝑛) is a function that maps a predicted probability distribution and the correct ground truth target to a single scalar value.</blockquote><p>A <strong>scoring rule</strong> provides a summary measure for the evaluation of <a href="https://en.wikipedia.org/wiki/Probabilistic_forecasting">probabilistic predictions</a>. It applies to tasks in which predictions assign probabilities to events, i.e. one issues a probability distribution as its predictions.</p><p>if <em>F</em> is the predicted probability and <em>Q</em> is the true probability. the scoring function S will measure a score to measure the error <em>S(Q, F). The S(Q, F) </em>are negatively (positively) oriented if smaller (larger) values mean better. Here we adhere to a negative orientation.</p><p>A scoring rule S is proper if <em>S(Q, Q) ≤ S(Q, F).</em></p><p>It is <strong>strictly proper</strong> if the above equation holds with equality if and only if <em>F=Q. Brier score is strictly proper</em></p><p><strong>Brier Score</strong></p><p>This is very similar to the mean squared error but only applied for prediction probability scores, whose values range between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*IOKz7MHR7OjQC7d9LDPu2Q.png" /></figure><p>where, f_t is the predicted value and o_t is observed. N is the number of observations. Brier score calculates the mean squared error between predicted probabilities and the observed values (actuals).</p><p><strong>NLL</strong></p><p>Each predicted probability is compared to the actual class output value (0 or 1) and a score is calculated that penalizes the probability based on the distance from the expected value. The penalty is logarithmic, offering a small score for small differences (0.1 or 0.2) and an enormous score for a large difference (0.9 or 1.0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*zKRlypWgyx9rE2UXrB-ltA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*dqloSFTOP_OW0KvRvGbDPA.png" /></figure><p>Proper scoring rules like the Brier score and negative log-likelihood provide a measure of the calibration and accuracy of probabilistic predictions, The lower values of such metrics encourage well-calibrated and accurate probabilistic predictions.</p><p>However, we cannot rely on these values alone for measuring calibration. In practice, training against this proper scoring rule, like training against log-likelihood, does not guarantee a well-calibrated model.</p><h4>Reliability Diagram</h4><p>Reliability diagrams are a visual tool for evaluating calibration. These diagrams plot expected sample accuracy as a function of confidence. Since perfect calibration yields the identity, any deviation represents miscalibration.</p><p>The reliability diagram for a classification problem is shown below</p><ul><li>Reliability plots provide a visual representation of the prediction calibration by plotting the expected sample accuracy as a function of predicted confidence.</li><li>The ideal curve is the identity curve where the predicted confidence and the observed accuracy (number of samples correctly predicted for that confidence, i.e. the fraction of positives) are the same</li><li>The region above the ideal curve tells that it is under-confident in this region and the region below tells that the model is over-confident</li><li>In deep learning, however, the problem of over confidence is more prominent</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7BFn7-Ks0ZYMdy18_s2BQ.png" /><figcaption>Right: For a well-calibrated model the predicted confidence and observed confidence are the same for each confidence value. whereas Left: for a miscalibrated model the observed confidence is less than the predicted confidence (over-confidence) or the observed confidence is higher than the predicted confidence (under-confidence)</figcaption></figure><p>There is a nice <a href="https://towardsdatascience.com/introduction-to-reliability-diagrams-for-probability-calibration-ed785b3f5d44">blog by Xianj J</a> elucidating how the reliability diagram is plotted.</p><p>Not going into the formula let&#39;s say we have a binary classification problem and 15 samples whose predicted probabilities, predicted class, and true class are mentioned below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*buZeEy7DT_UG7VbaNUrG8A.png" /></figure><p>Let&#39;s say we are taking 5 bins with a 20% interval. The X-axis will have the avg. predicted confidence and the Y-axis will have average observed confidence (accuracy).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulmhPHwRoAPObrVOmCdmMw.png" /></figure><p>We are going to plot this as our reliability plot with the diagonal line being the desired ideal plot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*OyOnt0XInCt8mB7I-uM4ig.png" /><figcaption>The reliability plot of NN1</figcaption></figure><p>Now let&#39;s take the prediction from another neural network</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8xgj5LYZd8gaguRIYcmow.png" /></figure><p>Let&#39;s compute the average confidence and accuracy bin-wise</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8psXj7-ElVT15gBZBeCMw.png" /></figure><p>Now let&#39;s plot the reliability diagram for Neural Network 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*Lvu3IPqPGqYSsWsLco7mzg.png" /><figcaption>Reliability plot of NN2</figcaption></figure><p>Now let&#39;s plot the calibration plot for both the NN. The average accuracy of NN1 is 8/15=0.533 and avg accuracy of NN2 is 7/15=0.4667</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*nhOXvxyIY2hpWT2PmZu3QQ.png" /><figcaption>Comparing the calibration plot</figcaption></figure><p>Visually we can see that both NN1 and NN2 are miscalibrated. However, NN2 is better than NN1 albeit NN1 has higher accuracy.</p><p>In this example, it&#39;s visually prominent that NN2 is better calibrated but when we have multiple models and when the difference is subtle we will not be able to visually decide which model is better. So we need to quantitatively measure the model calibration. We can do that using calibration error metrics like ECE (Expected Calibration Error), ACE (Adaptive Calibration Error), etc.</p><h4>Calibration Error Metrics</h4><p>Calibration error metrics give a scalar value that quantifies the miscalibration by computing the difference between true confidence and predicted confidence. Depending on the way this difference is computed there are different error metrics.</p><p><strong>a. Expected Calibration Error and Maximum Calibration error</strong></p><p>ECE measures the difference in expected accuracy and expected confidence. In practice, it is computed as the weighted average of the bin’s accuracy/confidence difference, where the weight is the proportion of samples in that bin. ECE gives a scalar summary, a quantitative value. The mathematical formula is stated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*SZ8YXqCvxypFJeqbzM2KaA.png" /><figcaption>Formula of ECE; Ref: <a href="https://openaccess.thecvf.com/content_CVPRW_2019/papers/Uncertainty%20and%20Robustness%20in%20Deep%20Visual%20Learning/Nixon_Measuring_Calibration_in_Deep_Learning_CVPRW_2019_paper.pdf">Measuring Calibration in Deep Learning</a></figcaption></figure><p>B = Number of bins, in our above example we have 5 bins</p><p>b = the bin number, for our example we have B1, B2, B3, B4 and B5</p><p>acc(b) = the accuracy in the bth bin</p><p>conf(b) = avg predicted confidence in the bth bin</p><p>nb = set of predictions falling in the bth bin</p><p>Perfect calibration is achieved when ECE=0 i.e. acc(b)=conf(b) for all bins m. The larger the ECE, the more uncalibrated the model.</p><p>Let&#39;s take the example from above and compute ECE for NN1 and NN2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_U7y4kIO765qFp6GLTPYuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XkVyHfYJB7dJIDaD51APEA.png" /></figure><p>The ECE of NN2 (0.1171) is much lower than the ECE of NN1 (0.257). Hence NN2 is well calibrated as compared to NN1 and should be chosen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*SiVV0GsqJM6P6cNViPFS7g.png" /><figcaption>Both visually as well as quantitatively NN2 is well calibrated as compared to NN1</figcaption></figure><p>Here MCE stands for Maximum Calibration Error. MCE is appropriate for high-risk applications, where the goal is to minimize the worst-case deviation between confidence and accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*sSEK1chBzZclvO2Nb1K_YA.png" /></figure><p>Although the idea of ECE is very intuitive, the mathematical formulation is a direct realization of the reliability diagram, which was designed for binary classification. when we use multi-class classification there are multiple drawbacks to using ECE, I strongly request the readers to refer to this paper — <a href="https://openaccess.thecvf.com/content_CVPRW_2019/papers/Uncertainty%20and%20Robustness%20in%20Deep%20Visual%20Learning/Nixon_Measuring_Calibration_in_Deep_Learning_CVPRW_2019_paper.pdf">Measuring Calibration in Deep Learning</a>. Here the authors have very neatly defined all the issues in ECE and proposed new metrics like SCE, ACE, and TACE to overcome them.</p><p>Issues with Expected Calibration Error (points taken from <a href="https://openaccess.thecvf.com/content_CVPRW_2019/papers/Uncertainty%20and%20Robustness%20in%20Deep%20Visual%20Learning/Nixon_Measuring_Calibration_in_Deep_Learning_CVPRW_2019_paper.pdf">Measuring Calibration in Deep Learning</a> )</p><ol><li><strong><em>Not computing calibration across all predictions:</em></strong> ECE is computed using only the predicted class probability (for 3-class prediction [0.1,0.75,0.05], the ECE will be computed for prob of class 1 which is 0.75) The metrics do not assess how accurate the model is for other K-1 class’s prediction. <strong>Solution: Static Calibration Error (SCE)</strong></li><li><strong><em>Fixed Calibration ranges:</em></strong> ECE is computed over evenly spaced bins. As the model will predict with higher confidence, for binary classification the bins close to 0 or 1 will be densely populated. for multiclass classification, as we take the max probability the bins at the right side will be densely populated, and a rightward skew is observed. This will cause only a few bins to contribute to the ECE. <strong>Solution: Adaptive Calibration Error (ACE)</strong></li><li><strong><em>Bias-Variance Tradeoff:</em></strong> A bias-variance tradeoff is created depending on the number of bins we select. The number of data points falling in each bin will depend on the number of bins selected. A larger number of bins causes more granular measures of calibration error (low bias) but also a high variance of each bin’s measurement as bins become sparsely populated. This tradeoff compounds particularly with the problem of fixed calibration ranges, as due to sharpness certain bins have many more data points than others. <strong>Solution: Adaptive Calibration Error (ACE)</strong></li><li><strong><em>Pathologies in Static Binning Scheme:</em></strong> Static binning schemes like ECE suffer from one more issue where we can get near 0 calibration error due to positive and negative predictions overlapping in the same bin. For example, assuming the dataset is 45% positive we could simply output a prediction in the range of (0.41, 0.43) for the negative examples and (0.47, 0.49) for the positive examples to create a set of predictions that has 1.0 AUC, 0 ECE and yet be uncalibrated.</li><li><strong><em>Washing Out of calibration score:</em></strong> For multi-class predictions, especially in the case where there are many classes, the majority of softmax predictions correspond to an incorrect class becomes infinitesimal. These tiny predictions can wash out the calibration score, One solution to that challenge is thresholding — only including predictions above some epsilon (ex., .01 or .001) in the calibration score. <strong>Solution: Thresholded Adaptive Calibration Error (TACE)</strong></li></ol><blockquote>One recommended metric would be to use ACE (Adaptive Calibration Error)</blockquote><p><strong>b. Static Calibration Error (SCE)</strong></p><p>Static Calibration Error (SCE), is a simple extension of Expected Calibration Error to every probability in the multiclass setting. SCE bins predictions separately for each class probability computes the calibration error within the bin, and averages across bins:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*51EoiMM1BO0_il4AclFdtA.png" /><figcaption>Formula of SCE; Ref: <a href="https://openaccess.thecvf.com/content_CVPRW_2019/papers/Uncertainty%20and%20Robustness%20in%20Deep%20Visual%20Learning/Nixon_Measuring_Calibration_in_Deep_Learning_CVPRW_2019_paper.pdf">Measuring Calibration in Deep Learning</a></figcaption></figure><p>Here, acc(b, k) and conf(b, k) are the accuracy and confidence of bin b for class label k, respectively; nbk is the number of predictions in bin b for class label k; and N is the total number of data points.</p><p>Let&#39;s take an example to show how SCE is computed and how it differs from ECE for a 3-class classification</p><p>Computing ECE (Max prob)</p><p><strong>c. Adaptive Calibration Error (ACE)</strong></p><p>In the above approaches, the bins were evenly spaced. One disadvantage of using evenly spaced bins is that there will be many bins without any predictions. The bins at the right end will be densely populated.</p><p>To get the best estimate of the overall calibration error the metric should focus on the regions where the predictions are made (and focus less on regions with few predictions). This leads us to introduce Adaptive Calibration Error (ACE). uses an adaptive scheme that spaces the bin intervals so that each contains an equal number of predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*twESrBqc_3RPehcWnHm1Ag.png" /></figure><p>In this formula, adaptive ranges are defined and the error metric is computing error for each class (as in SCE)</p><h3>5. How to Calibrate a model?</h3><p>One common approach to calibration is to apply post-processing methods to the output of any classifier without Retraining.</p><p>The two most popular post-processing methods are the parametric approach of <strong>Platt scaling</strong> (Platt et al., 1999) and the non-parametric approach of <strong>isotonic regression</strong> (Zadrozny &amp; Elkan, 2002). <a href="https://openreview.net/pdf?id=r1la7krKPS">Source Link</a></p><p>Before We start, one point to highlight</p><blockquote>The common calibration approaches in Neural Network nowadays are Temperature scaling (parametric) and Isotonic Regression (non-parametric)</blockquote><p>The below explanations are taken from the paper <a href="https://arxiv.org/pdf/1706.04599.pdf">On calibration of modern neural networks</a>.</p><p><strong>Non-parametric approaches</strong></p><ul><li>Histogram binning</li><li>Isotonic regression</li><li>Bayesian Binning into Quantiles (BBQ)</li></ul><p><strong>Parametric approaches</strong></p><ul><li>Platt Scaling</li><li>Matrix and Vector Scaling</li><li>Temperature Scaling</li><li>Dirichlet Calibration</li><li>Beta Calibration</li></ul><h4>Non-parametric approaches</h4><ol><li><strong>Isotonic Regression</strong></li></ol><p>Isotonic regression (Zadrozny &amp; Elkan, 2002), is a non-parametric method used to calibrate predicted probabilities, especially when you want to ensure that the predicted probabilities align with the true probabilities or outcomes in a monotonic fashion.</p><p>An image of isotonic regression vs linear regression is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*0naHWC7iiADkbzT5.png" /><figcaption>img source <a href="https://fastml.com/classifier-calibration-with-platts-scaling-and-isotonic-regression/">https://fastml.com/classifier-calibration-with-platts-scaling-and-isotonic-regression/</a></figcaption></figure><p>Isotonic regression finds a constant step-wise non-decreasing function that best fits a set of data points while minimizing a loss function. In the context of calibration, the goal is to find a function that maps the predicted probabilities (or scores) produced by a model to calibrate probabilities in such a way that higher predicted probabilities correspond to higher true probabilities of an event.</p><p>It learns a piecewise constant function <em>f</em> to transform uncalibrated outputs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/106/1*THLv2x330oaze5gH_zMfFQ.png" /></figure><p>Specifically, isotonic regression produces <em>f</em> to minimize the square loss between the calibrated output and ground truth</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*igcTl0zbj-ne4JgffDUw4Q.png" /></figure><p>yi s is the true label of the sample i and f(p^i) is the output of the calibrated classifier for sample i (i.e., the calibrated probability).</p><blockquote>Let’s illustrate isotonic regression with a simple example. Suppose you have a binary classification model that predicts the probability of an email being spam. You have a validation dataset with the following data:</blockquote><blockquote>Predicted Probabilities: [0.1, 0.3, 0.4, 0.6, 0.8]</blockquote><blockquote>True Outcomes (0 for not spam, 1 for spam): [0, 0, 1, 1, 1]</blockquote><blockquote>You want to calibrate the predicted probabilities using isotonic regression. After sorting the data, you have:</blockquote><blockquote>Sorted Predicted Probabilities: [0.1, 0.3, 0.4, 0.6, 0.8]</blockquote><blockquote>Sorted True Outcomes: [0, 0, 1, 1, 1]</blockquote><blockquote>Isotonic regression finds the piecewise constant function that minimizes the loss (e.g., mean squared error) between the true outcomes and the function’s values. In this case, the calibrated probabilities might look like this:</blockquote><blockquote>Calibrated Probabilities: [0.2, 0.2, 0.6, 0.6, 0.6]</blockquote><p>We can directly use scikit-learn to implement isotonic regression</p><p>Let&#39;s take our previous example where the model had an ECE of 0.257 and calibrate it with isotonic regression</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJ_yjLJL9_aseUYJwsOVQA.png" /></figure><blockquote>pred_prob = [0.7,0.67,0.23,0.19,0.9,0.97,0.54,0.77,0.15,0.3,0.85,0.69,0.34,0.45,0.53]</blockquote><blockquote>true_class = [1,0,1,0,1,0,0,0,1,0,1,1,0,1,1]</blockquote><blockquote>we will fit an isotonic regression on this predicted probability to produce calibrated probability</blockquote><blockquote>from sklearn.isotonic import IsotonicRegression<br>ir = IsotonicRegression() # create an instance of the IsotonicRegression class<br># Fit isotonic regression model<br>ir.fit(pred_prob, true_class) # fit the model</blockquote><blockquote>pred_prob_cl = ir.transform(pred_prob) # transform the data</blockquote><blockquote>pred_prob_cl = [0.6667, 0.5, 0.4, 0.4, 0.6667,0.6667, 0.5, 0.6667, 0.4, 0.4 ,<br> 0.6667, 0.6667, 0.4, 0.5, 0.5])</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_hc9ikBjIQoqhQ8DhyHqFg.png" /></figure><p>The standard approach for extending isotonic regression to the multiclass setting is to break the problem into many binary classification problems (e.g. one-versus-all problems), calibrate each problem separately, and then combine the calibrated probabilities</p><p><em>A learning curve analysis shows that Isotonic Regression is more prone to overfitting, and thus performs worse than Platt Scaling when data is scarce.</em></p><h4>Platt Scaling</h4><p>Platt scaling is a simple but effective method to calibrate the output of a binary classification model. You <strong>train a logistic regression model on the predicted scores or logits produced by your original model</strong>. This logistic regression model maps the raw scores to calibrated probabilities. You typically use a validation set to train this calibration model.</p><p>Platt scaling learns scalar parameters <em>a, b ∈ R</em> and outputs <em>qˆi = σ(azi + b)</em> as the calibrated probability. Parameters <em>a</em> and <em>b</em> can be optimized using the NLL loss over the validation set. It is important to note that the neural network’s parameters are fixed during this stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*QXBCPheazpCS_xa-J8KH0w.png" /><figcaption>source: ChatGPT-3.5</figcaption></figure><p><strong>1. Matrix and Vector Scaling</strong></p><p>Matrix and vector scaling are two multi-class extensions of Platt scaling. The softmax function <em>σSM</em> for multiclass classification is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*BEUz4dkl0KeV_yp2OaMgpg.png" /></figure><p>Let <em>zi</em> be the logits vector produced before the softmax layer for input <em>xi</em>.In matrix scaling <em>a</em> is replaced with <em>W ∈ R K∗K </em>while we consider <em>b ∈ R K</em> Matrix scaling applies a linear transformation <em>Wzi + b</em> to the logits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*_8o7mdwIHfrRnthWYcDDsA.png" /></figure><p>The parameters <em>W and b </em>are optimized with respect to NLL on the validation set. As the number of parameters for matrix scaling grows quadratically with the number of classes K, we define vector scaling as a variant where <em>W</em> is restricted to be a diagonal matrix. As for vector scaling; <em>W ∈ R K</em>.</p><p><strong>2. Temperature Scaling</strong></p><p>Temperature scaling, the simplest extension of Platt scaling, uses a single scalar parameter <em>T &gt; 0</em> for all classes. Given the logit vector <em>zi</em>, the new confidence prediction is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*B0v7gGc-HnEyuLvSbt7XqQ.png" /></figure><p>The mathematical representation changes from</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yo2UOQHXySDGGEBoOOXrKw.png" /></figure><p><em>T</em> is called the temperature, and it “softens” the softmax (i.e. raises the output entropy) <em>with T &gt; 1</em>.</p><p>As T → ∞, the probability qˆi approaches 1/K, which represents maximum uncertainty</p><p>With T = 1, we recover the original probability pˆi.</p><p>As T → 0, the probability collapses to a point mass (i.e. qˆi = 1).</p><p><em>T</em> is optimized with respect to NLL on the validation set. Because the parameter T does not change the maximum of the softmax function, the class prediction yˆ i remains unchanged. <strong>In other words, temperature scaling does not affect the model’s accuracy.</strong></p><blockquote>Platt Scaling is most effective when the distortion in the predicted probabilities is sigmoid-shaped.</blockquote><blockquote>Isotonic Regression is a more powerful calibration method that can correct any monotonic distortion. But, Isotonic Regression is prone to over-fitting.</blockquote><h4>==========================================================</h4><p><strong>To Dos</strong></p><ol><li>Spline calibration:<a href="https://arxiv.org/pdf/1809.07751.pdf">https://arxiv.org/pdf/1809.07751.pdf</a></li><li>Drichilet and Beta Calibration: <a href="https://arxiv.org/pdf/1910.12656.pdf">https://arxiv.org/pdf/1910.12656.pdf</a></li></ol><h3>6. Can we use the same approaches discussed above for a regression problem?</h3><p>In classification, we get the output as a confidence percentage which can be compared with the actual accuracy percentage to measure whether the model is calibrated or not. However, in regression, the output we get is a real number and not a confidence percentage. So how can we use the predicted real number and the ground truth real value to know whether the regression model is calibrated or not?</p><p><a href="https://www.investopedia.com/terms/c/confidenceinterval.asp#:~:text=A%20confidence%20interval%20displays%20the,hypothesis%20testing%20and%20regression%20analysis.">Confidence interval</a> to our rescue. We don&#39;t have confidence but we can use the concept of confidence or prediction interval to measure the confidence</p><p>In the context of a regression problem, a confidence interval provides a range of values that is likely to contain the true value with a certain confidence level.</p><p>For example, based on various environmental data sensor measurements the ML model estimated a rainfall of 45 inches with a 95% confidence interval of [43, 47] inches. This means you’re 95% confident that the amount of rainfall you will receive falls within the interval [43, 47].</p><p><strong>Interpretation:</strong> Here’s how you typically interpret a confidence interval:</p><p>If you were to observe the amount of rainfall many times, let’s say 100 days, it will not always be 45, it may be 46, 44.5, or even, 41 but 95% of the time it will be in the range of 43 to 47, that is among 100 days 95 days would have rainfall in the range of 43 to 47.</p><p><em>thus confidence intervals give the notion of uncertainty in your predictions</em></p><p>so in regression problems, you can use the notion of confidence interval to plot the reliability curve and compute ECE as we did for the classification problem above.</p><p>But if you see as we need to get the range along with the prediction we also need the standard deviation of that prediction to define the range for a specific confidence interval which may require modification of the model to predict a standard deviation along with lots of current prediction, This will be covered in the next blog — <a href="https://medium.com/@anuj_shah/model-calibration-for-regression-c9633eab061d">Model Calibration for regression</a></p><p>==============================================================================================================================</p><h4><strong><em>Additional Notes 1: Computing ECE f</em>or binary classification</strong></h4><blockquote>Be mindful of various implementations of ECE available online</blockquote><blockquote>Lets take an example of predicted probability for binary classification</blockquote><blockquote>pred_prob = [0.7,0.67,0.23,0.19,0.9,0.97,0.54,0.77,0.15,0.3,0.85,0.69,0.34,0.45,0.53]</blockquote><blockquote>so the predicted class will be</blockquote><blockquote>pred_class = [1,1,0,0,1,1,1,1,0,0,1,1,0,0,1]</blockquote><blockquote>However in the multiclass setting the pred probability can also be represented as</blockquote><blockquote>pred_prob_mult = [[0.3,0.7],[0.3,0.67],[0.77,0.23],[0.81,0.19],[0.1,0.9],[0.03,0.97],[0.46,0.54],[0.23,0.77],[0.85,0.15],[0.7,0.3],[0.15,0.85],[0.31,0.69],[0.64,0.34],[0.55,0.45],[0.47,0.53]]</blockquote><blockquote>This will again have the same predicted class</blockquote><blockquote>pred_class_mult = [1,1,0,0,1,1,1,1,0,0,1,1,0,0,1]</blockquote><blockquote>When computing ECE, in the multiclass setting it will take the predicted probability as the maximum probability</blockquote><blockquote>so the predicted probability for multiclass setting for computing ECE will become</blockquote><blockquote>pred_prob_mult = [0.7,0.67,0.77,0.81,0.9,0.97,0.54,0.77,0.85,0.7,0.85,0.69,0.64,0.55,0.53]</blockquote><blockquote>Which is quite different than pred_prob in the binary setting</blockquote><blockquote>pred_prob = [0.7,0.67,0.23,0.19,0.9,0.97,0.54,0.77,0.15,0.3,0.85,0.69,0.34,0.45,0.53]</blockquote><blockquote>so the computed ECE will also vary</blockquote><blockquote>Let&#39;s compute the ECE for both settings to see the difference</blockquote><blockquote>For binary setting computed ECE = 0.257</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzO89YAuZK-pykhooNDdww.png" /></figure><blockquote>For multiclass setting, computed ECE = 0.1906</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*craaq7LpJVujTm6SC6_Dug.png" /></figure><blockquote>So be mindful of the implementation depending in which setting of ECE you want for your binary classification</blockquote><blockquote>for instance for implementation here — <a href="https://github.com/JeremyNixon/uncertainty-metrics-1/tree/master">https://github.com/JeremyNixon/uncertainty-metrics-1/tree/master</a></blockquote><blockquote>They will always consider multiclass setting, even if you give</blockquote><blockquote>pred_prob = [0.7,0.67,0.23,0.19,0.9,0.97,0.54,0.77,0.15,0.3,0.85,0.69,0.34,0.45,0.53]</blockquote><blockquote>The code converts it to a multiclass setting</blockquote><blockquote>pred_prob_mult = [0.7,0.67,0.77,0.81,0.9,0.97,0.54,0.77,0.85,0.7,0.85,0.69,0.64,0.55,0.53]</blockquote><blockquote>and then compute the ECE</blockquote><h4>Additional Notes 2: Taking care of confidence at bin boundaries while computing ECE</h4><blockquote>Let&#39;s take an example for the following predicted probability</blockquote><blockquote>pred_prob = [0.6,0.67,0.82,0.9,0.97,0.54,0.77,0.75,0.6,0.4]</blockquote><blockquote>Now let&#39;s say we have 5 bins</blockquote><blockquote>B1 [0–0.2], B2 [0.2–0.4], B3 [0.4–0.6], B4 [0.6–0.8], B5 [0.6–0.8]</blockquote><blockquote>Now depending on which logic you choose, the samples with predicted confidence at the bin boundary will fall in different bins which then also changes the computed ECE</blockquote><blockquote>approach 1- in_bin: lower_bin &gt; conf ≤ higher_bin</blockquote><blockquote>approach 2- in_bin: lower_bin ≥ conf &lt; higher_bin</blockquote><blockquote>If you choose approach 1, the first sample <strong>0.6 will fall in B3</strong> and the last sample <strong>0.4 will fall in B2</strong></blockquote><blockquote>If you choose approach 2, then the first sample 0.6 will fall in B4 and the last sample <strong>0.4 will fall in B3</strong></blockquote><blockquote>for instance for implementation here — <a href="https://github.com/JeremyNixon/uncertainty-metrics-1/tree/master">https://github.com/JeremyNixon/uncertainty-metrics-1/tree/master</a></blockquote><blockquote>They follow the approach 2 for handling Bin Boundaries</blockquote><h4>Additional Notes 3: The data type of the predicted probability may vary the computed calibration metrics (float32, float64)</h4><blockquote>pred_prob_mult_1 = np.array([[0.7,0.2,0.1],[0.1,0.67,0.23],[0.82,0.13,0.05],[0.82,0.03,0.15],\<br> [0.05,0.05,0.9],[0.97,0.01,0.02],[0.3,0.54,0.16],[0.2,0.77,0.03],\<br> [0.15,0.1,0.75],[0.6,0.1,0.3],[0.05,0.85,0.1],[0.25,0.06, 0.69],\<br> [0.4,0.34,0.26],[0.42,0.45,0.13],[0.3,0.17,0.53]],np.float64)</blockquote><blockquote>pred_prob_mult_2 = np.array([[0.7,0.2,0.1],[0.1,0.67,0.23],[0.82,0.13,0.05],[0.82,0.03,0.15],<br> [0.05,0.05,0.9],[0.97,0.01,0.02],[0.3,0.54,0.16],[0.2,0.77,0.03],<br> [0.15,0.1,0.75],[0.6,0.1,0.3],[0.05,0.85,0.1],[0.25,0.06,0.69],<br> [0.4,0.34,0.26],[0.42,0.45,0.13],[0.3,0.17,0.53]],np.float32)</blockquote><blockquote>pred_prob_mult_3 = np.array([[0.7,0.2,0.1],[0.1,0.67,0.23],[0.82,0.13,0.05],[0.82,0.03,0.15],<br> [0.05,0.05,0.9],[0.97,0.01,0.02],[0.3,0.54,0.16],[0.2,0.77,0.03],<br> [0.15,0.1,0.75],[0.6,0.1,0.3],[0.05,0.85,0.1],[0.25,0.06,0.69],<br> [0.4,0.34,0.26],[0.42,0.45,0.13],[0.3,0.17,0.53]])</blockquote><blockquote>ece1 = umnp.ece(true_class, pred_prob_mult_1, num_bins=5) — float64<br>ece2 = umnp.ece(true_class, pred_prob_mult_2, num_bins=5) — float32<br>ece3 = umnp.ece(true_class, pred_prob_mult_3, num_bins=5) — default</blockquote><blockquote>print(ece1,ece2,ece3) — [0.36133333], [0.308], [0.36133333]</blockquote><blockquote>sce1 = umnp.sce(true_class, pred_prob_mult_1, num_bins=5) — float64<br>sce2 = umnp.sce(true_class, pred_prob_mult_2, num_bins=5) — float32<br>sce3 = umnp.sce(true_class, pred_prob_mult_3, num_bins=5) — default</blockquote><blockquote>print(sce1,sce2,sce3) —[ 0.2675555], [0.249777], [0.2675555]</blockquote><h4>Additional Notes 4: Sharpness and calibration</h4><p>Calibration is a joint property of the estimated predicted distribution as well as the correct ground truth events or values that materialize and reflect their statistical consistency. In simple terms, if a well-calibrated distribution assigns a 0.8 probability to an event (e.g. recognizing cars in object detection), the event should occur around 80% of the time. Sharpness on the other hand quantifies the concentration of the predictive distribution around the true materialized ground truth target and is a property of the predictive distribution only. As an example, if the correct ground truth class is “car”, the predicted probability distribution should ideally assign a probability of 1 to the car category. In the context of machine learning, good predicted probability distributions need to be sharp, but ideal predicted probability distributions should be both sharp and well-calibrated.</p><p>Unfortunately, measuring calibration is not enough to determine the quality of output probability distributions; we are required to also evaluate its sharpness, which we have described as the concentration of probability mass assigned by output probability distributions around the correct ground truth targets. We can evaluate both the calibration and sharpness of probability distributions by using proper scoring rules. A scoring rule 𝑆(𝑝(y|x,D),y𝑛) is a function that maps a predicted probability distribution and the correct ground truth target to a single scalar value. A lower value of a scoring rule usually signifies predicted probability distributions that are closer to the data-generating distribution from which the ground truth target is sampled. A proper scoring rule is a scoring rule that is only minimized if the predicted probability distribution is exactly equal to the distribution that generated the correct ground truth target.</p><h3>References</h3><ol><li>Measuring calibration in deep learning: <a href="https://arxiv.org/pdf/1904.01685.pdf">https://arxiv.org/pdf/1904.01685.pdf</a></li><li>Measuring calibration in deep learning: <a href="https://openaccess.thecvf.com/content_CVPRW_2019/papers/Uncertainty%20and%20Robustness%20in%20Deep%20Visual%20Learning/Nixon_Measuring_Calibration_in_Deep_Learning_CVPRW_2019_paper.pdf">https://openaccess.thecvf.com/content_CVPRW_2019/papers/Uncertainty%20and%20Robustness%20in%20Deep%20Visual%20Learning/Nixon_Measuring_Calibration_in_Deep_Learning_CVPRW_2019_paper.pdf</a></li><li>On calibration of modern deep neural networks: <a href="https://arxiv.org/pdf/1706.04599.pdf">https://arxiv.org/pdf/1706.04599.pdf</a></li><li><a href="http://www.cs.utsa.edu/~jha/class2023/Lecture8/Slides/2017TemperatureScaling.pdf">http://www.cs.utsa.edu/~jha/class2023/Lecture8/Slides/2017TemperatureScaling.pdf</a></li><li><a href="https://www.eng.biu.ac.il/goldbej/files/2022/01/Lior_Frenkel_Eusipco_2021.pdf">https://www.eng.biu.ac.il/goldbej/files/2022/01/Lior_Frenkel_Eusipco_2021.pdf</a></li><li><a href="https://eurasip.org/Proceedings/Eusipco/Eusipco2022/pdfs/0001586.pdf">https://eurasip.org/Proceedings/Eusipco/Eusipco2022/pdfs/0001586.pdf</a></li><li><a href="https://arxiv.org/pdf/1910.12656.pdf">https://arxiv.org/pdf/1910.12656.pdf</a></li><li><a href="https://proceedings.neurips.cc/paper/2019/file/8ca01ea920679a0fe3728441494041b9-Paper.pdf">https://proceedings.neurips.cc/paper/2019/file/8ca01ea920679a0fe3728441494041b9-Paper.pdf</a></li><li><a href="https://pub.aimind.so/measure-the-accuracy-of-probabilistic-predictions-using-the-brier-score-c67c5ebeeaa5">https://pub.aimind.so/measure-the-accuracy-of-probabilistic-predictions-using-the-brier-score-c67c5ebeeaa5</a></li><li>Proper scoring rule- log-loss and brier score: <a href="https://machinelearningmastery.com/how-to-score-probability-predictions-in-python/">https://machinelearningmastery.com/how-to-score-probability-predictions-in-python/</a></li><li>Why is log loss preferred for other scoring rules: <a href="https://stats.stackexchange.com/questions/274088/why-is-logloss-preferred-over-other-proper-scoring-rules">https://stats.stackexchange.com/questions/274088/why-is-logloss-preferred-over-other-proper-scoring-rules</a></li><li><a href="https://github.com/JeremyNixon/uncertainty-metrics-1">GitHub — JeremyNixon/uncertainty-metrics-1: An easy-to-use interface for measuring uncertainty and robustness.</a></li><li><a href="https://arxiv.org/pdf/2011.10671.pdf">https://arxiv.org/pdf/2011.10671.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1181f2fef2c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantile, Percentile (one tail and two tail distribution), Confidence Interval, Box Plot]]></title>
            <link>https://medium.com/@anuj_shah/quantile-percentile-one-tail-and-two-tail-distribution-confidence-interval-box-plot-ce80b1b6db37?source=rss-c7f54cd28926------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce80b1b6db37</guid>
            <category><![CDATA[confidence-interval]]></category>
            <category><![CDATA[perecntiles]]></category>
            <category><![CDATA[two-tail-distribution]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Anuj shah (Exploring Neurons)]]></dc:creator>
            <pubDate>Sat, 23 Sep 2023 13:55:11 GMT</pubDate>
            <atom:updated>2024-03-16T19:26:29.161Z</atom:updated>
            <content:encoded><![CDATA[<p>Well the more I read about probabilistic models in deep learning, I realize how important and confusing this basic topic could be, so here I am trying to decipher it.</p><h3><strong>Quantiles, Quartiles and Percentile</strong></h3><p>Quantiles are values that split sorted data into equal parts. In general terms, a <em>q</em>-quantile divides sorted data into <em>q </em>parts. The most commonly used quantiles have special names:</p><ul><li><strong>Quartiles (4-quantiles)</strong>: Three quartiles split the data into four parts.</li><li><strong>Deciles (10-quantiles)</strong>: Nine deciles split the data into 10 parts.</li><li><strong>Percentiles (100-quantiles): </strong>99 percentiles split the data into 100 parts</li></ul><p>We are going to use <strong>Quartiles and Percentile.</strong></p><p>We will see later that quartiles are the special cases of percentile</p><p>Let&#39;s take a data distribution of 15 samples</p><p>data = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150]</p><p>When we say what is the 20th percentile, it means what is the value in the above data below which we will have 20% of the data</p><p>Since we have 15 samples 20% of 15 is 3. So what is the value below which we will have 3 samples, In our case that value is 40</p><p>So the 20th percentile (value below which we have 20% of data) for the above dataset is 40</p><p>The quartiles are the three special percentile values that will divide data into 4 parts</p><p>Q1 — First quartile or Lower Quartile (25th percentile)</p><p>Q2 — SecondQuartile or Median (50th percentile)</p><p>Q3 — Third Quartile or Upper Quartile (75th percentile)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*Ec8aykASwPP_umnk3lOpTw.png" /></figure><p>To compute the percentile value we can use the Pandas quantile function</p><blockquote>import pandas as pd<br>data = pd.DataFrame([10,20,30,40,50,60,70,80,90,100,110,120,130,140,150])</blockquote><blockquote>To get Q1, Q2 and Q3</blockquote><blockquote>data.quantile(0.25) ==&gt; 45</blockquote><blockquote>data.quantile(0.5) ==&gt; 80</blockquote><blockquote>data.quantile(0.25) ==&gt; 115</blockquote><blockquote>you can use various other parameters in the quantile function: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.quantile.html">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.quantile.html</a></blockquote><blockquote>To get any random percentile say 40th perecntile or 60th percentile</blockquote><blockquote>data.quantile(0.4) ==&gt; 66</blockquote><blockquote>data.quantile(0.6) ==&gt; 94</blockquote><ul><li>In a <a href="https://www.scribbr.com/methodology/population-vs-sample/"><strong>sample</strong></a> or dataset, the quartiles divide the data into four groups with equal numbers of observations.</li><li>In a <a href="https://www.scribbr.com/statistics/probability-distributions/"><strong>probability distribution</strong></a>, the quartiles divide the distribution’s range into four intervals with equal probability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*Sd27w4KSZP4NwucNiqG5wg.png" /><figcaption>img ref: <a href="https://www.scribbr.com/statistics/quartiles-quantiles/#:~:text=Quantiles%20are%20values%20that%20split,the%20data%20into%20four%20parts.">Quartiles &amp; Quantiles | Calculation, Definition &amp; Interpretation</a> — shaun Turney</figcaption></figure><p>For a Gaussian distribution, we can compute the percentile value using scipy norm.stats.ppf function</p><blockquote>from scipy import stats as stats<br>norm = stats.norm(loc=0, scale=1)</blockquote><blockquote><em>PPF — Percent point function (inverse of cdf= percentiles)</em></blockquote><blockquote>To get the quantiles value Q1, Q2, Q3</blockquote><blockquote>norm.ppf(0.25) → -0.67448<br>norm.ppf(0.5) → 0.0<br>norm.ppf(0.75) → 0.67448</blockquote><blockquote>To get any other percentile<br>norm.ppf(.95) → 1.644853<br>norm.ppf(0.99) → 2.32634</blockquote><h3>Percentile for one-tail and two-tail distribution</h3><p>The value going in the ppf function is called as significance level and is represented by alpha (α)</p><p>There is one more thing to understand — the one-tail distribution and the two-tail distribution.</p><p>For one tail distribution, it is pretty straightforward as can be seen from the plots below for the 25th, 50th, or 80th percentiles. To compute the value for all these percentiles we will be using the norm.ppf</p><p>the 25th percentile is the value below which 25% of data will lie, we will use alpha=0.25 ==&gt; norm.ppf(0.25) → -0.67448</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1n7ebBaSr34_Eco_WEfTQ.png" /><figcaption>For one tail distribution the 25th and 50th percentile, the value is -0.67 and 0.0 respectively</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1WfmQ7KtdRlJhT2NfMFHQ.png" /><figcaption>For one tail distribution the 80th and 95th percentile, the value is 0.84 and 1.64 respectively</figcaption></figure><p>For a two-tail distribution, the data is taken about the mean, so when we compute the 50th percentile we compute the value for 50% of data about the mean. it means 25% from the left of the mean and 25% from the right of the mean. so the significance level will be divided to compute values of two-tail the lower and upper</p><blockquote>data_percent = 0.5</blockquote><blockquote># Significance level (alpha) for a two-tailed test<br>alpha = 1-data_perecent ==&gt; 0.5</blockquote><blockquote># Calculate the critical values for the tails<br>critical_value_left = norm.ppf(alpha / 2) ==&gt; norm.ppf(0.25)<br>critical_value_right = norm.ppf(1 — alpha / 2) ==&gt; norm.ppf(0.75)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UD0cTE0Ej6xZA8pnlSsdg.png" /><figcaption>For two-tail distribution, the 50th percentile, the value of lower alpha is 0.25 and upper alpha is 0.75, and computing its ppf gives the value of -0.67 and 0.67 respectively</figcaption></figure><p>, and for 95% data the remaining 5% is divided into the left(2.5%) and right(2.5%)</p><blockquote>data_percent = 0.95</blockquote><blockquote># Significance level (alpha) for a two-tailed test<br>alpha = 1-data_perecent ==&gt; 0.05</blockquote><blockquote># Calculate the critical values for the tails<br>critical_value_left = norm.ppf(alpha / 2) ==&gt; norm.ppf(0.025)<br>critical_value_right = norm.ppf(1 — alpha / 2) ==&gt; norm.ppf(0.975)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVqoBjLf0bEFQihfagQ63w.png" /><figcaption>For two-tail distribution, the 50th percentile, the value of lower alpha is 0.25 and upper alpha is 0.75, and computing its ppf gives the value of -1.96 and 1.96 respectively</figcaption></figure><p>To Dos</p><p>Confidence Interval &amp; Box Plot</p><p>References</p><ol><li><a href="https://www.scribbr.com/statistics/quartiles-quantiles/#:~:text=Quantiles%20are%20values%20that%20split,the%20data%20into%20four%20parts.">Quartiles &amp; Quantiles | Calculation, Definition &amp; Interpretation</a> — shaun Turney</li><li><a href="https://stackoverflow.com/questions/60699836/how-to-use-norm-ppf">https://stackoverflow.com/questions/60699836/how-to-use-norm-ppf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce80b1b6db37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-driving Cars: An introduction]]></title>
            <link>https://medium.com/@anuj_shah/self-driving-cars-an-introduction-270b010021dd?source=rss-c7f54cd28926------2</link>
            <guid isPermaLink="false">https://medium.com/p/270b010021dd</guid>
            <category><![CDATA[sesnors]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[autonomous-cars]]></category>
            <category><![CDATA[self-driving-cars]]></category>
            <dc:creator><![CDATA[Anuj shah (Exploring Neurons)]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 07:04:12 GMT</pubDate>
            <atom:updated>2023-04-23T07:20:13.344Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Self-Driving cars, as the name says are cars that drive by themselves without any driver (it would be more appropriate to say without any human driver).</p><p>Before we delve into this topic and peel off the surface of this amazing technology that has fascinated us for decades let’s read out a formal definition from Wikipedia.</p><p><em>“A </em><strong><em>self-driving car</em></strong><em>, also known as an </em><strong><em>autonomous car</em></strong><em>, </em><strong><em>driver-less car</em></strong><em>, or </em><strong><em>robotic car</em></strong><em> (</em><strong><em>robo-car</em></strong><em>), is a car that is capable of traveling without human input “</em></p><p>It would be more appropriate to use the word autonomous and categorize the cars into three major categories:</p><p>· Non-autonomous car</p><p>· Semi-Autonomous car</p><p>· Full autonomous/self-driving cars.</p><p>The task of driving a car requires intelligence and, in the car, the intelligence is achieved through AI (Artificial intelligence). In the figure, this intelligence is represented by a robot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8dbimuqELmLMQdwVsPiPQ.png" /><figcaption>Figure 1: Different types of autonomous vehicles.</figcaption></figure><p><strong>Non-autonomous car:</strong> The traditional car where we have no additional assistance from any robots/AI. The human performs all the tasks (acceleration, braking, driving, etc.) This is represented by Fig a.</p><p><strong>Semi-autonomous car:</strong> The human driver is still required to be on the wheels; however, you have some assistance from AI/robots. E.g., the car can understand its environment and assist in various tasks but most of the decision-making is still with human control. It can assist in tasks like parking, driving by itself in a certain region, identifying, and changing lanes by itself It can be on a lane by itself, alerting the driver when not attentive, etc. In the illustration, I am representing this assistance through a robot helping you like assistance. This is represented by Fig b.</p><p><strong>Autonomous car:</strong> Here the driver is off the wheel and the car does all the tasks by itself. The figure is represented by the robots sitting on the wheel. This is represented by Fig c. The actual representation of self-driving cars is Fig d.</p><h3>Enabling Technologies</h3><p>Be it a self-driving car or a human being the basic working fundamental of any system remains the same, which is acquiring input or getting stimulated from the environment, processing the input to churn out knowledge/information, and then acting based on that knowledge by performing some action in the environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*euaPEN6CDVnRRwFKv2ICSQ.png" /><figcaption>Figure 2: Working of a general system in an environment</figcaption></figure><h4>Human System</h4><p>Let’s start by imaging ourselves and see how we function in this world</p><p><strong>Acquiring input (sensors):</strong> To gather input from the environment we would need some sensors that convey the information inside our system. That sensor for us is our famous five: eyes, ears, nose, tongue, and skin.</p><p><strong>Processing input (brain):</strong> The inputs from various senses either in the form of vision, sound, touch, smell, feel or a combination of all reaches our brain which further processes it and provides a suitable action.</p><p><strong>Taking actions (actuators):</strong> Based on the decision made by your brain you take a certain action that could be physical, verbal, or through expressions.</p><p>Imagine driving a car, you are seeing the scene through your eyes (sensor getting info from the environment), and when the traffic signal turns red that information is processed by your brain which then instructs you to stop. This is done slowly by pressing the brakes through your legs (action being performed in the environment).</p><p>Let’s take this explanation and make an analogy with the self-driving car</p><h4>Self-Driving Cars</h4><blockquote><strong>Input (Sensors)</strong></blockquote><p>Numerous sensors in the car help to acquire the physics input from the environment. A diagram representing various sensors is shown below. However, the positions, types, and quantity of this sensor may vary `based on the design of the car manufacturer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*J2m4c_Fl0vcDyz-CpOvk2Q.png" /><figcaption>Figure 3: Left: cartoon of a self-driving car with various sensors. Right: An actual self-driving car from Waymo showing 3 major sensors — the camera, radar, and lidar. Image source-Left: <a href="https://www.engineering.com/story/how-sensors-empower-autonomous-driving">how-sensors-empower-autonomous-driving</a>. Right: <a href="https://www.businessinsider.in/transportation/heres-how-waymos-brand-new-self-driving-cars-see-the-world/articleshow/56648715.cms">Waymo; Business Insider</a></figcaption></figure><p>The three most important sensors that are enabling automated driving are the <strong>Camera, Lidar, and Radar.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*kFqks46AxKS_VdCSHnAfEg.png" /><figcaption>Figure 4: Three major automotive sensors. Image source-<a href="https://community.cadence.com/cadence_blogs_8/b/breakfast-bytes/posts/autos182">Cadence; automotive sensors</a></figcaption></figure><ol><li><strong>Camera: </strong>The camera sensor captures images and videos in visible light or even in the infrared domain depending on the camera you use. The camera sensor serves as the eye of the car and helps to get a lot of information about the environment like what objects are present in the scene and where they are located so that appropriate decisions can be made.</li><li><strong>LiDAR: </strong>Light Detection and Ranging are widely used in self-driving cars as they provide a full 360-degree 3D image of the environment. This works by collecting the bounced laser beams from the objects. The emitted laser beams are safe and not visible to the human eye. The advantage of LiDAR over a camera is that it can work in any weather condition as it has its light source and does not depend on visible light.</li><li><strong>RADAR: </strong>Radio Detection and Ranging sensor works by emitting the pulse of a radio frequency signal which bounces back from the object back to the sensor. The time difference between the emitted and received signal helps to estimate the distance and location of an object relative to other vehicles. This complements the vision sensor in low visibility scenarios like night driving or bad weather conditions It is more reliable for distance and speed and range measurement even in bad weather conditions.</li></ol><p>Usually, a combination of the above three and many other sensors are used to get the perception of the environment, a term popularly called <strong>Sensor Fusion.</strong></p><p>A sample scene captured by camera and Lidar is shown along with detected objects by an AI algorithm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*oaHQKzik62YVmb_gv1Yq7Q.png" /><figcaption>Figure 5: A scene from an actual driving scenario showing what a camera and LiDAR see along with detected objects of interest by an AI algorithm. Image source-<a href="https://leddartech.com/solutions/leddar-pixset-dataset/">Leddar PixSet dataset</a></figcaption></figure><blockquote><strong>Processing (AI &amp; Hardware):</strong></blockquote><p><strong>AI (Artificial Intelligence)</strong></p><p>Once the data is acquired, there are processed by AI algorithms on different powerful hardware components. Although there are various AI algorithms, the most popular AI algorithm in recent time which has accelerated the field are Deep Learning Algorithms.</p><p><strong>Deep Learning Algorithms</strong> are artificial neural networks inspired by biological neurons and are capable of learning from the data directly (this work like the way you teach a baby what a cat and a dog are, by showing them the cats and dogs or their pictures.). These algorithms work by intelligent use of various mathematical concepts in the domain of Linear Algebra, Probability, Statistics, and Calculus.</p><p>One example of neural networks and what it learns is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Pe2-KCQ0Fv-XvYFYHx-51w.png" /><figcaption>Figure 6: A deep neural network showing the features learned at different layers and the predicted output. Image source- <a href="https://www.jneurosci.org/content/38/34/7365">JNeurosci Deep(er) Learning</a></figcaption></figure><p>The popular deep-learning algorithms being used are</p><p>· Multi-Layer Perceptron (Fully Connected Neural Networks).</p><p>· Convolution Neural Networks.</p><p>· Recurrent Neural Networks.</p><p>· Reinforcement learning.</p><blockquote><strong>Hardware (GPUs)</strong></blockquote><p>We cannot bring out any product unless we have the proper hardware. The development of powerful GPUs (Graphical Processing Units) for AI has catapulted the rise of such complex algorithms.</p><p>The GPUs were previously used in gaming for processing images. As opposed to CPU (Central Processing Unit), they are capable of parallel processing which helps in meeting the computing need of complex AI algorithms.</p><p>Watch this amazing demo of <a href="https://www.youtube.com/watch?v=-P28LKWTzrI&amp;embeds_euri=https%3A%2F%2Fblogs.nvidia.com%2F&amp;feature=emb_logo">CPU vs GPU</a></p><p>One of the GPUs from Nvidia is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*miLghtcnndyoe2wBPR4HJw.png" /><figcaption>Figure 7: A RTX2080 GPU from Nvidia used for training AI algorithms. Image source- <a href="https://www.nvidia.com/en-us/geforce/news/geforce-rtx-founders-graphics-card-breakdown/">Nvidia GeForce RTX</a></figcaption></figure><blockquote><strong>Actuators</strong></blockquote><p>Before various control actions can be taken there is also one more component called Route Planning which plans the route and trajectory of the car. We are not discussing that here.</p><p>Once the knowledge is acquired from the sensor data, the AI algorithms then learn about the environment and define the correct action which could be the correct acceleration, brake, or steering wheel direction.</p><h3>Benefits of self-driving cars</h3><p>Some of the benefits that self-driving cars could render</p><p>· The accidents happening due to human errors (distracted driving, drunk driving, etc.) will be alleviated.</p><p>· It could provide a safe and reliable commute for the elderly, sick, or disabled.</p><p>· It will provide better traffic regulation.</p><p>· It will optimize energy consumption and reduce emissions.</p><p>· It will save a lot of driving time.</p><h3>Challenges</h3><p>This benefit of a self-driving car is promising and exciting, but it has a myriad of challenges that need to be overcome before we can see fully autonomous cars on roads. Some challenges are listed below</p><p>· As the technology will be driven by complex algorithms it will have many software and millions of codes which poses security risk from hackers.</p><p>· Another big challenge is going to be ethical and philosophical. For e.g., in case of accidents (although it will be less the possibility can’t be eliminated) who will be blamed?</p><p>· There are various behavioral decisions and communication through expression done by humans while driving, will the self-driving car be considering those aspects?</p><p>· Further, the cost of this technology is still high.</p><p>· Various demographic regions will have different challenges. For instance, the driving scenario of India and America is different.</p><p>· Developing an ecosystem where umpteen numbers of self-driving cars are running and communicating with each other, and the environment will also be a challenge.</p><h3>Conclusion</h3><p>This was just a brief overview of this magical technology which rests upon the shoulder of some amazing and interesting science and engineering. There is a lot of real-life testing for semi-autonomous and fully autonomous vehicles being done by multiple companies that are determined to bring them on the roads.</p><p>If you find my articles helpful and wish to support them — <a href="https://www.buymeacoffee.com/anujshah645">Buy me a Coffee</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=270b010021dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computing carbon footprint of training AI Models]]></title>
            <link>https://medium.com/@anuj_shah/computing-carbon-footprint-of-training-ai-models-7b0311ec056b?source=rss-c7f54cd28926------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b0311ec056b</guid>
            <category><![CDATA[ai-for-climate-change]]></category>
            <category><![CDATA[ai-climate-change]]></category>
            <category><![CDATA[mlco2-calculator]]></category>
            <category><![CDATA[carbon-footprint]]></category>
            <category><![CDATA[carbon-emission-with-ai]]></category>
            <dc:creator><![CDATA[Anuj shah (Exploring Neurons)]]></dc:creator>
            <pubDate>Sat, 01 Jan 2022 10:09:35 GMT</pubDate>
            <atom:updated>2023-04-23T07:23:52.831Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The term climate change is ubiquitous, especially after the release of the Sixth <a href="https://www.ipcc.ch/assessment-report/ar6/">IPCC Assessment report</a> which declared “code red for Humanity”.</p><p>The impact associated with a global temperature increase of just 1.5°C will be severe and this mark will be reached very soon(somewhere by 2040). A temperature increase of 2°C will be reached by 2100 unless effective and decisive actions are taken right now.</p><p>Currently, the net CO2eq (Carbon dioxide Equivalent) emission per year is 51 billion tons. At this point, simply reducing the emission won’t help much. We need to get to “Net Zero” (zero greenhouse gases emission) because this will be our only chance to avoid climate disasters. (<a href="https://en.wikipedia.org/wiki/How_to_Avoid_a_Climate_Disaster">How to avoid climate disaster — Bill Gates</a>).</p><p>AI, being one of the most powerful tools for handling myriads of problems, can play a big role in combating climate change as well.</p><p>For instance, AI can help to use energy resources efficiently. One such popular implementation is <a href="https://deepmind.com/blog/article/deepmind-ai-reduces-google-data-centre-cooling-bill-40">Deepminds’ ML</a> system which was able to consistently achieve a 40 percent reduction in the amount of energy needed for cooling.</p><p>AI can even help to better anticipate and prepare for extreme weather events. Start-ups like <a href="https://oneconcern.com/en/">one concern</a> and <a href="https://jupiterintel.com/">Jupiter</a> are working towards such approaches. other start-ups like <a href="https://www.nomad-go.com/energy-solution">nomad go</a> are working towards optimizing the energy use in buildings and reducing emissions. You can find more information about various startups using AI for climate intelligence in this <a href="https://www.forbes.com/sites/robtoews/2021/06/20/these-are-the-startups-applying-ai-to-tackle-climate-change/?sh=3d6ad1bf7b26">blog from Rob Toews</a>. Another interesting read about the role of AI in climate change is the <a href="https://arxiv.org/pdf/1906.05433.pdf">paper</a> from Climate Change AI <a href="https://www.climatechange.ai/events/neurips2019">workshop</a>.</p><p>Hopefully, AI is going to help fight climate change. As “torchbearers” of the new technology, we are endowed to not only develop efficient approaches at the same time ensure our work will not cause any additional harm to the environment.</p><p>However, one aspect that we may often overlook is how much greenhouse gases are generated while developing AI algorithms. With the rise of deep learning, the hunger for compute has increased significantly. Researchers and engineers are training big AI models for days, weeks, and even months. And to develop a single application we usually don’t just train one or two models but lots of them, to perform ablation studies that help us to improve our KPI. Unfortunately, this adds significantly to the carbon footprint of AI technology.</p><p>Well, now that we have laid out some context let’s get into the main agenda of this blog post which is how we can compute the Carbon footprint of AI models.</p><h4>Computing Carbon Footprint</h4><p>Although we usually refer to the term carbon, it also includes other greenhouse gases like methane and nitrous oxide. Emission from other gases is converted in terms of carbon and the measurement is done w.r.t carbon, usually termed as CO2 Eq. (Carbon dioxide equivalent). For instance, 1 Kg of methane emissions equals the warming potential of 28 Kg of Carbon dioxide.</p><p>Have you ever wondered how much CO2 Eq. (carbon dioxide equivalent) can training of an AI model generates?</p><p>We recently came across this paper from MIT Amherst — <a href="https://arxiv.org/pdf/1906.02243.pdf">Energy and policy Consideration for deep learning in NLP </a>which highlights that training a large deep-learning model produces 626,000 pounds of co2e (carbon dioxide equivalent) which is approximately 56 times more than produced by an average human in one year and equals to the lifetime emission of five cars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxRBps3JmiuFC0ch1--oAA.png" /><figcaption>a) Ref: <a href="https://arxiv.org/pdf/1906.02243.pdf">Energy and Policy Consideration for Deep Learnings in NLP</a>. b) Ref: <a href="https://www.technologyreview.com/2019/06/06/239031/training-a-single-ai-model-can-emit-as-much-carbon-as-five-cars-in-their-lifetimes/">MIT Technology Review — Karen Hao</a></figcaption></figure><p>There are movements like “<a href="https://arxiv.org/pdf/1907.10597.pdf">Green AI</a>” which aim to make machine learning cleaner and greener. Touching on the topic of Green AI is out of scope for this post.</p><p>However, one thing to note is, to improve we should be able to measure how much CO2 is emitted when we train our models and that’s where frameworks like <a href="https://github.com/Breakend/experiment-impact-tracker">experiment-impact-tracker</a>, python package <a href="https://github.com/mlco2/codecarbon">CodeCarbon</a> and tools like <a href="https://mlco2.github.io/impact/#co2eq">Machine Learning Emission Calculator</a>(mlco2 calculator) can help.</p><p>In this post let’s see how we can calculate the emission of training an ML model in our local HPC using the mlco2 Calculator.</p><p>This tool can help estimate the carbon emission for different cloud providers (GCP, AWS, Azure) as well as private infrastructure. It also accounts for different regions (Asia, Australia, Europe, etc.) different regions, and Hardware types (AMD, Titan, Quadro, Tesla, etc.)</p><p>Let’s have a look at one of the examples of the mlco2 calculator tool and compute the Kg of co2e emissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7xvsDIuKf4iuXABaE4oPg.png" /></figure><p>With the above settings (RTX 3080 Ti GPU on a GCP located in asia-east1 for 100 hours) you would generate 19.6 kgc02 eq. The tool also suggests, that if you had been using the compute from the europe-west6 region you would only have generated just 0.56 kg co2 eq because the electricity there is generated more from green sources. This tool also tells you what your emission is equivalent to in terms of driving a car or burning coal.</p><p>The good part is that Google (and even Amazon and Microsoft) is trying to offset the generated carbon, so the net emission might be lower. <a href="https://www.offsetguide.org/understanding-carbon-offsets/what-is-a-carbon-offset/#:~:text=A%20carbon%20offset%20broadly%20refers,for%20emissions%20that%20occur%20elsewhere.">Carbon offsetting</a> can be viewed as compensation for the generated emissions by funding renewable and green energy projects.</p><p>Now. Let’s learn to calculate the co2eq for any machine using the formula used in the above tool.</p><p>For our demo, we will consider our local HPC with GTX 1080 TI GPU drawing power from the local power grid in the Karnataka state</p><p>We need two things-</p><p>1. Power consumed in kWh and</p><p>2. carbon produced per kWh</p><p>To get the carbon emission of Karnataka state we are using the live <a href="https://app.electricitymap.org/zone/IN-KA?solar=false&amp;remote=true&amp;wind=false">electricityMap</a> Application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCumeSKLKaZiUgvSLbvmXg.png" /></figure><p>So, the carbon emission is 448 gCO2eq/kWh which is 0.448 kgco2eq/kWh.</p><p>The power consumption of a 1080 TI is 250 W (we have reduced it to 200 W but for the calculation let’s keep the default 250 W).</p><p>For training an ensemble of EfficientNet-B0, which took around 36 hours to finish, the emission can be calculated as</p><p><strong>Power consumption x Time x Carbon Produced Based on the Local Power Grid:</strong></p><p>250 W X 36h = 9 kWh X 0.448 kgCO2eq/kWh = <strong>4.032 kg eq. CO2</strong></p><p>Let’s assume we are not is not buying any carbon offset, so it’s 0</p><p>So, the net emission becomes —</p><p>4.0323–0 = <strong>4.0323 kg eq. CO2</strong></p><p>The point to note here is that this is just for one training. And we know, to optimize the model, we have to do multiple trainings. So, you can get an idea of the carbon footprint of developing the entire application.</p><p>Now let’s do the same calculation using the mlco2 calculator tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7hM0nySoPmW_xmR4Y5iNg.png" /></figure><h3>What can we do to reduce the carbon footprint of our AI Training?</h3><p>1. Keep track of the carbon footprint for your AI training using the discussed mlco2 calculator and any other tracker.Based on this measurement try to reduce it as much as possible.</p><p>2. While using the cloud, select the regions with lower carbon footprints. For instance, use the <strong>EU-Stockholm region</strong> (if possible) when using AWS. This region has a very low carbon emission footprint (almost 12 times lower than the EU-Frankfurt region.</p><p>3. Did you know that you can set a <strong>power limit</strong> for your GPUs during training?</p><p>a) This can be done with the <strong>nvidia-smi</strong> command. First, enable ‘persistence mode’ for your GPUs: <strong>nvidia-smi -pm 1</strong>. Then, you can set the power limit for a specific GPU by using the <strong>-pl</strong> option, for example: <strong>nvidia-smi -i 0 -pl 200</strong> (this limits the power consumption of GPU 0 to 200 Watts).</p><p>b) The number after parameter <strong>-i</strong> is the GPU number. Further, you can see the current power limit of a GPU using <strong>nvidia-smi -q -d POWER -i 2 -l 1 | grep “Power Limit”</strong> and the amount of power being drawn using<strong> nvidia-smi -q -d POWER -i 2 -l 1 | grep “Power Draw” (for GPU 2)</strong></p><p>c) If you are worried about how power limitation might affect your training performance, you can find a very good analysis here: <a href="https://www.pugetsystems.com/labs/hpc/Quad-RTX3090-GPU-Wattage-Limited-MaxQ-TensorFlow-Performance-1974/">https://www.pugetsystems.com/labs/hpc/Quad-RTX3090-GPU-Wattage-Limited-MaxQ-TensorFlow-Performance-1974/</a></p><p>4. Use <strong>mixed-precision</strong> mode whenever possible.</p><p>a) Mixed precision is an exciting new feature to make your training run faster and use less memory. It also needs less power. Better efficiency plays an important role in lowering the carbon footprint of AI. See this article to learn more about mixed-precision training: <a href="https://www.tensorflow.org/guide/mixed_precision">https://www.tensorflow.org/guide/mixed_precision</a></p><p>5. Use pre-trained models wherever possible. It will reduce the training time and hence the energy consumption.</p><p>If you find my articles helpful and wish to support them — <a href="https://www.buymeacoffee.com/anujshah645">Buy me a Coffee</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b0311ec056b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating custom data generator for training Deep Learning Models-Part 3]]></title>
            <link>https://medium.com/@anuj_shah/creating-custom-data-generator-for-training-deep-learning-models-part-3-c239297cd5d6?source=rss-c7f54cd28926------2</link>
            <guid isPermaLink="false">https://medium.com/p/c239297cd5d6</guid>
            <category><![CDATA[activity-recognition]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[custom-data-generator]]></category>
            <category><![CDATA[3d-cnn]]></category>
            <dc:creator><![CDATA[Anuj shah (Exploring Neurons)]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 20:19:28 GMT</pubDate>
            <atom:updated>2023-04-23T07:30:35.316Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@anuj_shah/creating-custom-data-generator-for-training-deep-learning-models-part-1-5c62b20cff26"><strong>Chapter -1 : What is a generator function in python and the difference between yield and return</strong></a></p><p><a href="https://medium.com/@anuj_shah/creating-custom-data-generator-for-training-deep-learning-models-part-2-be9ad08f3f0e"><strong>Chapter-2: Writing a generator function to read your data that can be fed for training an image classifier in Keras.</strong></a></p><p><strong>Chapter-3: Writing generator function for different kinds of inputs — multiple input or sequence of input.</strong></p><p>In the previous post, we started writing a data generator for training deep learning models. Albeit, we used this data generator for training model in Keras, you can use the same with other libraries as well. For this tutorial we are considering 3 different scenarios of training as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*iGHh0D1ucq3BpF6r.png" /><figcaption>Scenario-1: when a single input is to be fed to network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*dYAKNTd0-ZSMr-aU.png" /><figcaption>Scenario-2: when a sequence of input (e.g, video) is to be fed to the network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*2jR325Uk0yM_5b_n.png" /><figcaption>Scenario-3: When you have multiple inputs that need to be fed to an ensemble of model</figcaption></figure><p>In the previous post, we discussed how to write a data generator for the first scenario and if you haven’t been through the previous post, I would suggest that you go through that first — <a href="https://medium.com/@anuj_shah/creating-custom-data-generator-for-training-deep-learning-models-part-2-be9ad08f3f0e"><strong>Chapter-2: Writing a generator function to read your data that can be fed for training an image classifier in Keras.</strong></a></p><p>In this post, we will write a data generator for the second and third scenarios. Let’s consider the second scenario first, we need to train a model which takes a sequence input. To elucidate this, I am going to consider the problem of activity recognition from videos using 3D CNN which takes volume data (besides the spatial 2D data of the image, the third dimension is the number of frames).</p><h4><strong>Preparing the dataset</strong></h4><p>I will be using 3 categories — Archery, Basketball, and Biking from <a href="https://www.crcv.ucf.edu/data/UCF101.php">UCF-101 dataset</a>. Let’s prepare the dataset for making a clean data generator for this dataset</p><ol><li>I will divide the dataset into train and test by approximately keeping 80% of the videos in each category in the train section and the remaining 20% in the test section.</li><li>The next step is to convert the video frames and save them as image frames. this will help us to load the data frame by frame. And video data sets are usually saved in this format. we will create a new directory called ‘activity_data’ where all the videos will be saved as frames. This will be our working directory from here</li></ol><p>Before step 2 the structure was</p><pre>activity_recognition<br>    UCF-101<br>        train<br>            Archery<br>                v_Archery_g01_c01.avi<br>                v_Archery_g01_c02.avi<br>                ............<br>            Basketball<br>                v_Basketball_g01_c01.avi<br>                .........<br>            Biking<br>                v_Biking_g01_c01.avi<br>                ............<br>        test<br>            ........<br>            ........</pre><p>After step the structure becomes</p><pre>activity_recognition<br>    UCF-101<br>        ......<br>    activity_data<br>        train<br>            Archery<br>                v_Archery_g01_c01<br>                    img_000000.png<br>                    img_000001.png<br>                    .........<br>                v_Archery_g01_c02<br>                    img_000000.png<br>                    img_000001.png<br>                    .........                <br>                ............<br>            Basketball<br>                v_Basketball_g01_c01<br>                    img_000000.png<br>                    img_000001.png<br>                    .........<br>                ..........<br>            Biking<br>                v_Biking_g01_c01<br>                    img_000000.png<br>                    img_000001.png<br>                    .........<br>                ..........<br>        test<br>            ........<br>            ........</pre><p>The code to do this is pretty straightforward</p><pre>root_dir = ‘UCF-101’      # source dir<br>dest_dir = ‘activity_data’ # destination directory</pre><pre># create the destination dir if it does not exists<br>if not os.path.exists(dest_dir): <br> os.mkdir(dest_dir)</pre><pre># To list what are the directories — train, test<br>data_dir_list = os.listdir(root_dir) </pre><pre>for data_dir in data_dir_list: # loop over train and test dir<br>    data_path = os.path.join(root_dir,data_dir)<br>    #Read all the folders in each of the train and test dir<br>    dest_data_path = os.path.join(dest_dir,data_dir)<br>    if not os.path.exists(dest_data_path):<br>        os.mkdir(dest_data_path)<br>     # for each of the activity - Archery, Basketball and Biking #read all the videos in the activity list  <br>    activity_list = os.listdir(data_path)<br>    <br># for each of the video in video list, read the video and save #every frame <br>    for activity in activity_list:<br>        activity_path = os.path.join(data_path,activity)<br>        dest_activity_path = os.path.join(dest_data_path,activity)<br>        if not os.path.exists(dest_activity_path):<br>            os.mkdir(dest_activity_path)<br>        write_frames(activity_path,dest_activity_path)</pre><p>The full code at —</p><p>3. The next step is to write the paths and labels of each frame in a CSV file as shown in the figure below-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awDqv8s8xL5yxES7ZsOEUg.png" /><figcaption>saving the data in CSV file in the above format</figcaption></figure><p>Assign labels to each class as shown in the dictionary labels_name. Then create a train and test directory to store the respective files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*0khxg4ptsjtn5tlg3arz9Q.png" /></figure><p>For writing the CSV files for each video in the train directory — you need to loop over all the activity folders (Archery, Basketball, and Biking) in the train directory, for each activity loop over every video, and for every video you create a data frame in which you will each of the frames of the video. The code snippet is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brV3UW2Mis7hua1zXXW-Xg.png" /></figure><p>Now we are done with preparing our data set and can proceed towards creating the data generator. Now our working directory has 3 folders — UCF-101, activity_data, and data_files. We are going to use data_files to read the path and activity_data to read the data.</p><pre>activity_recognition<br>    UCF-101<br>    activity_data<br>        train<br>        test<br>    data_files<br>        train<br>        test</pre><h4><strong>Writing the Data Generator</strong></h4><p>For spatial dimension, we can mention its’s spatial size(say 224 x 224). We also need to incorporate the temporal dimension i.e. the number of frames you wish to feed once. One more term that we need to understand is the temporal stride. Let’s understand this with an example- say we have a video with 50 frames.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*aMGcKx3nOVvzVcguaNt0nw.png" /></figure><p>say you chose a temporal dimension of 16 and a temporal stride of 1.</p><p>How many data samples can be prepared from this video? The first sample will be from frame 1 to frame 16, the next from frame 2 to frame 17, and the next from 3 to 18. the formula is</p><pre>total_images = 50 ; temporal_length = 16 ; temporal_stride = 1<br>num_samples = int((total_images-temporal_length)/temporal_stride)+1<br>num_samples = int((50-16)/1) + 1 = int(34)+1 = 35</pre><pre>if temporal_stride = 4<br>num_samples = int((50-16)/4) + 1 = int(34/4)+1 = int(8.5)+1 = 9</pre><p>If you choose a temporal stride of 4 then the number of data samples that we can get is 9. The first sample will be from frame 1 to frame 16, the next will be from frame 5 to frame 21, the nest from frame 9 to 25, and so on.</p><p>For now, we will not consider temporal padding i.e if the number of frames in a video is less than the temporal_length we will drop that video from our data-set. For instance, if temporal_length was 16 and the number of frames in the video is less than 16 (say even 15), we will drop this video.</p><p>As discussed in part -2 of this tutorial series, the template which we will be following for creating a custom data generator is taken from this amazing blog — <a href="http://www.jessicayung.com/using-generators-in-python-to-train-machine-learning-models/">www.jessicayung.com/using-generators-in-python-to-train-machine-learning-models/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/0*lfYrM6qCLJ0x-Z7a.png" /></figure><p>First, we need to create the samples which consist of the sequence of filenames along with the label of that sequence. For a temporal dimension of 16 our samples list should be in the format as</p><blockquote><em>samples — [[[frame1_filename,frame2_filename,…frame16_filename],label1], [[frame1_filename,frame2_filename,…frame16_filename],label2],……….].</em></blockquote><p>we will have two major functions —</p><ul><li>a load_samples function which loads the file names in proper sequence from the CSV files and returns us the samples list</li><li>a data_generator function to read the sequence loaded in the samples and yield an array of data for training.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*6QDWOeW3kcglT2MrJoPOqw.png" /></figure><p>In the load_sample function, we call a generator function — file_generator(), that actually reads the file name and prepares it in the correct format. Let&#39;s have a look at the file_generator()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MTyHRH94iqiBm1nHqoufmw.png" /></figure><p>Now you can call the load samples to load the train or test data. Below is a snippet from jupyter notebook for loading the samples of train data with a temporal_length of 16 and a temporal stride of 4 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*EV1rQgJjsF3EgzBk195Fnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*RBqv5Q_vDczQCbbr38vd9g.png" /></figure><p>Let’s see some of the samples from train data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mIXoFVALg_ZS3sxgZAGhMA.png" /></figure><p>As we can see here each of the samples has 16 frame sequences and a label corresponding to that sequence. Now how will the samples look with a temporal_length of 8</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSD3KZNbS4c0k45lyVX23g.png" /></figure><p>Now we have loaded our sample, we will feed this loaded sample into the data generator.</p><pre>def data_generator(data,batch_size=10,shuffle=True):              <br>    &quot;&quot;&quot;<br>    Yields the next training batch.<br>    data is an array <em> [[[frame1_filename,frame2_filename,…frame16_filename],label1], [[frame1_filename,frame2_filename,…frame16_filename],label2],……….].</em><br>    &quot;&quot;&quot;<br>    num_samples = len(data)<br>    if shuffle:<br>        data = shuffle_data(data)<br>    while True:   <br>        for offset in range(0, num_samples, batch_size):<br>            print (&#39;startring index: &#39;, offset) <br>            # Get the samples you&#39;ll use in this batch<br>            batch_samples = data[offset:offset+batch_size]<br>            # Initialise X_train and y_train arrays for this batch<br>            X_train = []<br>            y_train = []<br>            # For each example<br>            for batch_sample in batch_samples:<br>                # Load image (X)<br>                x = batch_sample[0]<br>                # Read label (y)<br>                y = batch_sample[1]<br>                temp_data_list = []<br>                for img in x:<br>                    try:<br>                        img = cv2.imread(img)<br>                        #apply any kind of preprocessing here<br>                        img = cv2.resize(img,(224,224))<br>                        temp_data_list.append(img)</pre><pre>                    except Exception as e:<br>                        print (e)<br>                        print (&#39;error reading file: &#39;,img)                      <br>                # Add example to arrays<br>                X_train.append(temp_data_list)<br>                y_train.append(y)<br>    <br>            # Make sure they&#39;re numpy arrays (as opposed to lists)<br>            X_train = np.array(X_train)<br>            #X_train = np.rollaxis(X_train,1,4)<br>            y_train = np.array(y_train)<br>            # create one hot encoding for training in keras<br>            y_train = np_utils.to_categorical(y_train, 3)<br>    <br>            # yield the next training batch            <br>            yield X_train, y_train</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*aiKks4tKNffKP9HrRu8PFw.png" /></figure><pre>num_of_images=16<br>fig=plt.figure(figsize=(8,8)) <br>plt.title(&quot;one sample with {} frames ; activity:{}&quot;.format(num_of_images,activity))<br>subplot_num = int(np.ceil(np.sqrt(num_of_images)))<br>for i in range(int(num_of_images)):<br>    ax = fig.add_subplot(subplot_num, subplot_num, i+1)<br>    #ax.imshow(output_image[0,:,:,i],interpolation=&#39;nearest&#39; ) #to see the first filter<br>    ax.imshow(x_0[i,:,:,::-1])<br>    plt.xticks([])<br>    plt.yticks([])<br>    plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*8bNprr7YnWHgNRAT0ECE0g.png" /></figure><h4><strong>Training the Keras model with a prepared data generator</strong></h4><p>Now you can use the data generator to train a 3D CNN model. I will be defining a 3D CNN model in keras and training it with a data generator with a temporal length of 16 and an image size of 64.</p><pre>def get_model(num_classes=Config.num_classes):<br>    # Define model<br>    model = Sequential()<br>    model.add(Conv3D(32, kernel_size=(3, 3, 3), input_shape=(<br>        16,64,64,3), padding=&#39;same&#39;))<br>    model.add(Activation(&#39;relu&#39;))<br>    model.add(Conv3D(32, kernel_size=(3, 3, 3), padding=&#39;same&#39;))<br>    model.add(Activation(&#39;relu&#39;))<br>    model.add(MaxPooling3D(pool_size=(3, 3, 3), padding=&#39;same&#39;))<br>    model.add(Dropout(0.25))</pre><pre>    model.add(Conv3D(64, kernel_size=(3, 3, 3), padding=&#39;same&#39;))<br>    model.add(Activation(&#39;relu&#39;))<br>    model.add(Conv3D(64, kernel_size=(3, 3, 3), padding=&#39;same&#39;))<br>    model.add(Activation(&#39;relu&#39;))<br>    model.add(MaxPooling3D(pool_size=(3, 3, 3), padding=&#39;same&#39;))<br>    model.add(Dropout(0.25))</pre><pre>    model.add(Flatten())<br>    model.add(Dense(512, activation=&#39;relu&#39;))<br>    model.add(Dropout(0.5))<br>    model.add(Dense(num_classes))<br>    model.add(Activation(&quot;softmax&quot;))<br>    model.compile(loss=categorical_crossentropy,<br>                  optimizer=Adam(), metrics=[&#39;accuracy&#39;])<br>    model.summary()<br>    #plot_model(model, show_shapes=True,<br>    #           to_file=&#39;model.png&#39;)<br>    return model</pre><pre>model = get_model()</pre><p>The model starts training and I can see the improvement already!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdCjCFUWpYdg5sgT9_J3vQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJ0G_LgDHnOKKs53-EzM4A.png" /></figure><p>The link to the data generator for sequence inputs — <a href="https://github.com/anujshah1003/custom_data_generator/tree/master/activity_recognition">https://github.com/anujshah1003/custom_data_generator/tree/master/activity_recognition</a></p><p>In this post, we wrote a data generator for the second scenario in which we trained a model which takes a sequence input.</p><p>This post is already getting long so we will cover the third scenario in the next post.</p><p>Till then, Keep Learning!! Keep Exploring Neurons!!!!</p><p>If you find my articles helpful and wish to support them — <a href="https://www.buymeacoffee.com/anujshah645">Buy me a Coffee</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c239297cd5d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating Keras like model summary in PyTorch]]></title>
            <link>https://medium.com/analytics-vidhya/generating-keras-like-model-summary-in-pytorch-110cb37c2cc1?source=rss-c7f54cd28926------2</link>
            <guid isPermaLink="false">https://medium.com/p/110cb37c2cc1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[torchsummary]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Anuj shah (Exploring Neurons)]]></dc:creator>
            <pubDate>Fri, 25 Oct 2019 12:11:09 GMT</pubDate>
            <atom:updated>2023-04-23T07:32:03.718Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generating Keras-like model summary in PyTorch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ddbrRRMUIt2OI8ro" /><figcaption>Photo by <a href="https://unsplash.com/@webaroo?utm_source=medium&amp;utm_medium=referral">Webaroo.com.au</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are an ardent Keras user and are recently moving to PyTorch, I am pretty sure you would be missing so many awesome features of keras. Salute to<a href="https://www.google.com/search?safe=strict&amp;client=ubuntu&amp;hs=eGg&amp;channel=fs&amp;sxsrf=ACYBGNSBLhLecE1T_PCvNeejWDadspbuow:1572002688856&amp;q=Fran%C3%A7ois+Chollet&amp;stick=H4sIAAAAAAAAAONgVuLVT9c3NMwwSk_Lys4oXMQq6FaUmHd4eX5msYJzRn5OTmoJAEyaoxIlAAAA&amp;sa=X&amp;ved=2ahUKEwjCo-uuprflAhUNUI8KHV6bCVgQmxMoATAkegQIDRAL"> Francois Chollet</a> for <a href="https://keras.io/">Keras</a>.</p><p>One such amazing feature is quickly getting the model summary and making the sense of your developed architecture at once using the Keras model.summary()</p><pre>from keras.datasets import mnist<br>from keras.models import Sequential<br>from keras.layers import Dense, Dropout, Flatten<br>from keras.layers import Conv2D, MaxPooling2D</pre><pre>model = Sequential()<br>model.add(Conv2D(32, kernel_size=(3, 3),<br>                 activation=&#39;relu&#39;,<br>                 input_shape=input_shape))<br>model.add(Conv2D(64, (3, 3), activation=&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=(2, 2)))<br>model.add(Dropout(0.25))<br>model.add(Flatten())<br>model.add(Dense(128, activation=&#39;relu&#39;))<br>model.add(Dropout(0.5))<br>model.add(Dense(num_classes,activation=&#39;softmax&#39;))</pre><pre>model.summary()</pre><pre>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>conv2d_4 (Conv2D)            (None, 222, 222, 32)      896       <br>_________________________________________________________________<br>conv2d_5 (Conv2D)            (None, 220, 220, 64)      18496     <br>_________________________________________________________________<br>max_pooling2d_1 (MaxPooling2 (None, 110, 110, 64)      0         <br>_________________________________________________________________<br>dropout_1 (Dropout)          (None, 110, 110, 64)      0         <br>_________________________________________________________________<br>flatten_1 (Flatten)          (None, 774400)            0         <br>_________________________________________________________________<br>dense_10 (Dense)             (None, 128)               99123328  <br>_________________________________________________________________<br>dropout_2 (Dropout)          (None, 128)               0         <br>_________________________________________________________________<br>dense_11 (Dense)             (None, 10)                1290      <br>=================================================================<br>Total params: 99,144,010<br>Trainable params: 99,144,010<br>Non-trainable params: 0<br>_________________________________________________________________</pre><p>The above snippet is from Keras and we can see how easily we can see the entire model summary with output shape and the number of parameters.</p><p>Is there some similar function in PyTorch??? Yess!!!</p><p>It’s the <a href="https://pypi.org/project/torchsummary/">torchsummary</a> library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoS83em16SEbTQDPvIPYGQ.png" /></figure><p><strong>Installation</strong></p><p>Installation is pretty straightforward</p><pre>pip install torchsummary</pre><p><strong>Using torchsummary</strong></p><pre>summary(model,input_shape)</pre><p>Let me show through an example and for this elucidation I will import a pretrained <a href="https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf">Alexnet</a> model trained on <a href="http://www.image-net.org/">ImageNet</a> dataset</p><pre>from torchvision import models<br>from torchsummary import summary</pre><pre># import the pretrained alexnet<br>model = models.alexnet(pretrained=True)<br>summary(model,(3,224,224))</pre><pre># And you should see something like this<br>----------------------------------------------------------------<br>        Layer (type)               Output Shape         Param #<br>================================================================<br>            Conv2d-1           [-1, 64, 55, 55]          23,296<br>              ReLU-2           [-1, 64, 55, 55]               0<br>         MaxPool2d-3           [-1, 64, 27, 27]               0<br>            Conv2d-4          [-1, 192, 27, 27]         307,392<br>              ReLU-5          [-1, 192, 27, 27]               0<br>         MaxPool2d-6          [-1, 192, 13, 13]               0<br>            Conv2d-7          [-1, 384, 13, 13]         663,936<br>              ReLU-8          [-1, 384, 13, 13]               0<br>            Conv2d-9          [-1, 256, 13, 13]         884,992<br>             ReLU-10          [-1, 256, 13, 13]               0<br>           Conv2d-11          [-1, 256, 13, 13]         590,080<br>             ReLU-12          [-1, 256, 13, 13]               0<br>        MaxPool2d-13            [-1, 256, 6, 6]               0<br>          Dropout-14                 [-1, 9216]               0<br>           Linear-15                 [-1, 4096]      37,752,832<br>             ReLU-16                 [-1, 4096]               0<br>          Dropout-17                 [-1, 4096]               0<br>           Linear-18                 [-1, 4096]      16,781,312<br>             ReLU-19                 [-1, 4096]               0<br>           Linear-20                 [-1, 1000]       4,097,000<br>================================================================<br>Total params: 61,100,840<br>Trainable params: 61,100,840<br>Non-trainable params: 0<br>----------------------------------------------------------------<br>Input size (MB): 0.57<br>Forward/backward pass size (MB): 8.31<br>Params size (MB): 233.08<br>Estimated Total Size (MB): 241.96<br>----------------------------------------------------------------</pre><p><strong>with Cuda</strong></p><p>If you have cuda you may need to export your model to cuda if you get a run time error as shown below</p><pre>model = models.alexnet(pretrained=True)<br>summary(model,(3,224,224))</pre><pre>RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same</pre><pre>#instead do this</pre><pre>model = models.alexnet(pretrained=True)<br>model.cuda()<br>summary(model,(3,224,224))</pre><pre>----------------------------------------------------------------<br>        Layer (type)               Output Shape         Param #<br>================================================================<br>            Conv2d-1           [-1, 64, 55, 55]          23,296<br>              ReLU-2           [-1, 64, 55, 55]               0<br>         MaxPool2d-3           [-1, 64, 27, 27]               0<br>            Conv2d-4          [-1, 192, 27, 27]         307,392<br>              ReLU-5          [-1, 192, 27, 27]               0<br>         MaxPool2d-6          [-1, 192, 13, 13]               0<br>            Conv2d-7          [-1, 384, 13, 13]         663,936<br>              ReLU-8          [-1, 384, 13, 13]               0<br>            Conv2d-9          [-1, 256, 13, 13]         884,992<br>             ReLU-10          [-1, 256, 13, 13]               0<br>           Conv2d-11          [-1, 256, 13, 13]         590,080<br>             ReLU-12          [-1, 256, 13, 13]               0<br>        MaxPool2d-13            [-1, 256, 6, 6]               0<br>AdaptiveAvgPool2d-14            [-1, 256, 6, 6]               0<br>          Dropout-15                 [-1, 9216]               0<br>           Linear-16                 [-1, 4096]      37,752,832<br>             ReLU-17                 [-1, 4096]               0<br>          Dropout-18                 [-1, 4096]               0<br>           Linear-19                 [-1, 4096]      16,781,312<br>             ReLU-20                 [-1, 4096]               0<br>           Linear-21                 [-1, 1000]       4,097,000<br>================================================================<br>Total params: 61,100,840<br>Trainable params: 61,100,840<br>Non-trainable params: 0<br>----------------------------------------------------------------<br>Input size (MB): 0.57<br>Forward/backward pass size (MB): 8.38<br>Params size (MB): 233.08<br>Estimated Total Size (MB): 242.03<br>----------------------------------------------------------------</pre><p><strong>Summary of a 3DCNN Model</strong></p><p>Here the input shape will have an additional dimension of number of frames. I am using 3D CNN ResNet for video classification from Kensho Hara-<a href="https://github.com/kenshohara/video-classification-3d-cnn-pytorch">https://github.com/kenshohara/video-classification-3d-cnn-pytorch</a></p><p>It is a 3D ResNet-18 architecture with input shape of (3,16,112,112)</p><pre>model = generate_model(opt)<br>summary(model,(3,16,112,112))</pre><pre>----------------------------------------------------------------<br>        Layer (type)               Output Shape         Param #<br>================================================================<br>            Conv3d-1       [-1, 64, 16, 56, 56]          65,856<br>       BatchNorm3d-2       [-1, 64, 16, 56, 56]             128<br>              ReLU-3       [-1, 64, 16, 56, 56]               0<br>         MaxPool3d-4        [-1, 64, 8, 28, 28]               0<br>            Conv3d-5        [-1, 64, 8, 28, 28]         110,592<br>       BatchNorm3d-6        [-1, 64, 8, 28, 28]             128<br>              ReLU-7        [-1, 64, 8, 28, 28]               0<br>            Conv3d-8        [-1, 64, 8, 28, 28]         110,592<br>       BatchNorm3d-9        [-1, 64, 8, 28, 28]             128<br>             ReLU-10        [-1, 64, 8, 28, 28]               0<br>       BasicBlock-11        [-1, 64, 8, 28, 28]               0<br>           Conv3d-12        [-1, 64, 8, 28, 28]         110,592<br>      BatchNorm3d-13        [-1, 64, 8, 28, 28]             128<br>             ReLU-14        [-1, 64, 8, 28, 28]               0<br>           Conv3d-15        [-1, 64, 8, 28, 28]         110,592<br>      BatchNorm3d-16        [-1, 64, 8, 28, 28]             128<br>             ReLU-17        [-1, 64, 8, 28, 28]               0<br>       BasicBlock-18        [-1, 64, 8, 28, 28]               0<br>           Conv3d-19       [-1, 128, 4, 14, 14]         221,184<br>      BatchNorm3d-20       [-1, 128, 4, 14, 14]             256<br>             ReLU-21       [-1, 128, 4, 14, 14]               0<br>           Conv3d-22       [-1, 128, 4, 14, 14]         442,368<br>      BatchNorm3d-23       [-1, 128, 4, 14, 14]             256<br>             ReLU-24       [-1, 128, 4, 14, 14]               0<br>       BasicBlock-25       [-1, 128, 4, 14, 14]               0<br>           Conv3d-26       [-1, 128, 4, 14, 14]         442,368<br>      BatchNorm3d-27       [-1, 128, 4, 14, 14]             256<br>             ReLU-28       [-1, 128, 4, 14, 14]               0<br>           Conv3d-29       [-1, 128, 4, 14, 14]         442,368<br>      BatchNorm3d-30       [-1, 128, 4, 14, 14]             256<br>             ReLU-31       [-1, 128, 4, 14, 14]               0<br>       BasicBlock-32       [-1, 128, 4, 14, 14]               0<br>           Conv3d-33         [-1, 256, 2, 7, 7]         884,736<br>      BatchNorm3d-34         [-1, 256, 2, 7, 7]             512<br>             ReLU-35         [-1, 256, 2, 7, 7]               0<br>           Conv3d-36         [-1, 256, 2, 7, 7]       1,769,472<br>      BatchNorm3d-37         [-1, 256, 2, 7, 7]             512<br>             ReLU-38         [-1, 256, 2, 7, 7]               0<br>       BasicBlock-39         [-1, 256, 2, 7, 7]               0<br>           Conv3d-40         [-1, 256, 2, 7, 7]       1,769,472<br>      BatchNorm3d-41         [-1, 256, 2, 7, 7]             512<br>             ReLU-42         [-1, 256, 2, 7, 7]               0<br>           Conv3d-43         [-1, 256, 2, 7, 7]       1,769,472<br>      BatchNorm3d-44         [-1, 256, 2, 7, 7]             512<br>             ReLU-45         [-1, 256, 2, 7, 7]               0<br>       BasicBlock-46         [-1, 256, 2, 7, 7]               0<br>           Conv3d-47         [-1, 512, 1, 4, 4]       3,538,944<br>      BatchNorm3d-48         [-1, 512, 1, 4, 4]           1,024<br>             ReLU-49         [-1, 512, 1, 4, 4]               0<br>           Conv3d-50         [-1, 512, 1, 4, 4]       7,077,888<br>      BatchNorm3d-51         [-1, 512, 1, 4, 4]           1,024<br>             ReLU-52         [-1, 512, 1, 4, 4]               0<br>       BasicBlock-53         [-1, 512, 1, 4, 4]               0<br>           Conv3d-54         [-1, 512, 1, 4, 4]       7,077,888<br>      BatchNorm3d-55         [-1, 512, 1, 4, 4]           1,024<br>             ReLU-56         [-1, 512, 1, 4, 4]               0<br>           Conv3d-57         [-1, 512, 1, 4, 4]       7,077,888<br>      BatchNorm3d-58         [-1, 512, 1, 4, 4]           1,024<br>             ReLU-59         [-1, 512, 1, 4, 4]               0<br>       BasicBlock-60         [-1, 512, 1, 4, 4]               0<br>        AvgPool3d-61         [-1, 512, 1, 1, 1]               0<br>           Linear-62                  [-1, 400]         205,200<br>           ResNet-63                  [-1, 400]               0<br>================================================================<br>Total params: 33,235,280<br>Trainable params: 33,235,280<br>Non-trainable params: 0<br>----------------------------------------------------------------<br>Input size (MB): 2.30<br>Forward/backward pass size (MB): 133.72<br>Params size (MB): 126.78<br>Estimated Total Size (MB): 262.80<br>----------------------------------------------------------------</pre><p>I hope this post was useful!!</p><p>Till then, Keep Learning! Keep Exploring Neurons!</p><p>If you find my articles helpful and wish to support them — <a href="https://www.buymeacoffee.com/anujshah645">Buy me a Coffee</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=110cb37c2cc1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/generating-keras-like-model-summary-in-pytorch-110cb37c2cc1">Generating Keras like model summary in PyTorch</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[Creating custom data generator for training Deep Learning Models-Part 2]]></title>
            <link>https://medium.com/@anuj_shah/creating-custom-data-generator-for-training-deep-learning-models-part-2-be9ad08f3f0e?source=rss-c7f54cd28926------2</link>
            <guid isPermaLink="false">https://medium.com/p/be9ad08f3f0e</guid>
            <category><![CDATA[data-generator]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[dataloader]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Anuj shah (Exploring Neurons)]]></dc:creator>
            <pubDate>Mon, 09 Sep 2019 06:01:17 GMT</pubDate>
            <atom:updated>2023-04-23T07:37:25.264Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@anuj_shah/creating-custom-data-generator-for-training-deep-learning-models-part-1-5c62b20cff26"><strong>Chapter -1: What is a generator function in Python and the difference between yield and return</strong></a></p><p><strong>Chapter-2: Writing a generator function to read your data that can be fed for training an image classifier in Keras.</strong></p><p><a href="https://medium.com/@anuj_shah/creating-custom-data-generator-for-training-deep-learning-models-part-3-c239297cd5d6"><strong>Chapter-3: Writing generator function for different kinds of inputs — multiple input or sequence of input.</strong></a></p><p>Hello Readers! Welcome back to the second chapter, where we will be writing our own custom data generator to load image data for training an image classifier rather than storing entire data in a list and then feeding them to the image classifier for training.</p><p>If you already know what a generator function is, and want to learn about how to use it, to create a custom data generator you can proceed. However, if you don’t know what a generator function is, or want a refresher, quickly go through the first chapter —<a href="https://medium.com/@anuj_shah/creating-custom-data-generator-for-training-deep-learning-models-part-1-5c62b20cff26"><strong><em> what is a generator function in Python.</em></strong></a></p><p>In order to understand how to create different data generators for different kinds of input I will be elucidating 3 kinds of input scenarios and you can use this as a reference and create different generator functions as per your requirements. The three different input scenarios are depicted below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*aaU7ap8-2OdBjTvGt5Ghdw.png" /><figcaption>Scenario-1: when a single input is to be fed to a network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*7Yg_Df-4maoEdhQ7S-W9kA.png" /><figcaption>Scenario-2: when a sequence of input (e.g, video) is to be fed to the network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*5CEloHgf0JJfyVO7ybPsoQ.png" /><figcaption>Scenario-3: When you have multiple inputs that need to be fed to an ensemble of model</figcaption></figure><p>In this post we will just create the data generator for the first scenario and in the subsequent post we will do it for the second and third scenarios.</p><p>To elucidate the first scenario, I will be using a subset of the flower data set from the Kaggle competition — <a href="https://www.kaggle.com/alxmamaev/flowers-recognition">https://www.kaggle.com/alxmamaev/flowers-recognition</a>.</p><p>The data set consists a total of 4326 images distributed over 5 flower categories — Daisy, Dandelion, Rose, Sunflower, and Tulip, as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*9SFIki4_ajvlbFP3BXW_0Q.png" /></figure><p>One pre-processing that can be done is renaming all the images in each folder in the appropriate order (eg, say from gibberish name to daisy_000001.png). The picture below elucidates what I am saying-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0fPpO9-eAUEdzLmEkATkw.png" /><figcaption>Renaming files appropriately from gibberish names to a format of say (000001.png, 000002.png, and so on )</figcaption></figure><p>The script to do this is here — <a href="https://github.com/anujshah1003/useful-scripts-for-handling-data/tree/master/renaming_multiple_files_in_sequence">https://github.com/anujshah1003/useful-scripts-for-handling-data/tree/master/renaming_multiple_files_in_sequence</a> and a video explaining the code is here — <a href="https://www.youtube.com/watch?v=g3djohbIK3Q&amp;t=409s">https://www.youtube.com/watch?v=g3djohbIK3Q&amp;t=409s</a></p><p>The template which we will be following for creating a custom data generator is taken from this amazing blog — <a href="http://www.jessicayung.com/using-generators-in-python-to-train-machine-learning-models/">www.jessicayung.com/using-generators-in-python-to-train-machine-learning-models/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*O3qvOb5u1ZPOSMV_PmJRrg.png" /></figure><p>We are going to follow this template for creating any data generator. The sample list needs to be prepared as shown above. Each element in the samples list consists of an input file name and its corresponding label. If we are reading a sequence of video frames for video classification then our samples can be structured as</p><blockquote>samples — [[[frame1_filename,frame2_filename,…],label1], [[frame1_filename,frame2_filename,…],label2],……….].</blockquote><p>So you can use the above format to structure any kind of input while preparing your custom data generator.</p><p>For our data set, we need to create a CSV file having all filenames and corresponding labels which can then be easily loaded to create our data generator for flower recognition. So, for that, I created two CSV files flower_recognition_train.csv and flower_recognition_test.csv. The test set is created by randomly picking 60 samples from each flower category.</p><p>Read the data path and assign labels to each flower category</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*lkKTz6FEweXuIwWVhjaOZg.png" /></figure><p>Now create two data frames one for train and one for test csv with 3 columns of FileName, Label, and ClassName</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jzptiHX9ID9wDxrQ3MS9w.png" /></figure><p>Now loop over every file in each flower category, read each file, and exclude it if it is corrupted if not include it in the train or test data frame based on the random index chosen for test data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPQoKy73Y2scUQJzY8xlJg.png" /><figcaption>code to create train and test data frame</figcaption></figure><p>Now save the train and test data frame as train and test CSV files which you can later load for creating the data generator</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*8XE48DtZ_1PwbIeSg74cHQ.png" /></figure><p>My working directory looks like this now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*v0SWDqcg0bTVQUAyaJai6w.png" /></figure><p>So now everything is in place and we can write our data generator</p><pre>import os<br>import pandas as pd</pre><pre>def load_samples(csv_file):<br>    data = pd.read_csv(os.path.join(&#39;data_files&#39;,csv_file))<br>    data = data[[&#39;FileName&#39;, &#39;Label&#39;, &#39;ClassName&#39;]]<br>    file_names = list(data.iloc[:,0])<br>    # Get the labels present in the second column<br>    labels = list(data.iloc[:,1])<br>    samples=[]<br>    for samp,lab in zip(file_names,labels):<br>        samples.append([samp,lab])<br>    return samples</pre><pre>samples = load_samples(flower_recognition_train.csv)</pre><p>the samples are a list of 4023 items of the format [[image1_filename,label1], [image2_filename,label2],…].<br> let us see some of the first few and last few examples</p><pre>print (samples[0:5])</pre><pre>output:<br>[[&#39;flowers_renamed\\daisy\\daisy_000001.png&#39;, 0],<br> [&#39;flowers_renamed\\daisy\\daisy_000003.png&#39;, 0],<br> [&#39;flowers_renamed\\daisy\\daisy_000004.png&#39;, 0],<br> [&#39;flowers_renamed\\daisy\\daisy_000005.png&#39;, 0],<br> [&#39;flowers_renamed\\daisy\\daisy_000006.png&#39;, 0]]</pre><pre>print (samples[-15:-10])</pre><pre>output:<br>[[&#39;flowers_renamed\\tulip\\tulip_000969.png&#39;, 4],<br> [&#39;flowers_renamed\\tulip\\tulip_000970.png&#39;, 4],<br> [&#39;flowers_renamed\\tulip\\tulip_000971.png&#39;, 4],<br> [&#39;flowers_renamed\\tulip\\tulip_000973.png&#39;, 4],<br> [&#39;flowers_renamed\\tulip\\tulip_000974.png&#39;, 4]]</pre><p>you can see the file name and their corresponding label. we are going to use this to create our data generator. The code segment shown below is taken from this blog-<a href="http://www.jessicayung.com/using-generators-in-python-to-train-machine-learning-models/">www.jessicayung.com/using-generators-in-python-to-train-machine-learning-models/</a></p><pre>def generator(samples, batch_size=32,shuffle_data=True,resize=224):<br>    &quot;&quot;&quot;<br>    Yields the next training batch.<br>    Suppose `samples` is an array [[image1_filename,label1], [image2_filename,label2],...].<br>    &quot;&quot;&quot;<br>    num_samples = len(samples)<br>    while True: # Loop forever so the generator never terminates<br>        shuffle(samples)<br><br>        # Get index to start each batch: [0, batch_size, 2*batch_size, ..., max multiple of batch_size &lt;= num_samples]<br>        for offset in range(0, num_samples, batch_size):<br>            # Get the samples you&#39;ll use in this batch<br>            batch_samples = samples[offset:offset+batch_size]<br><br>            # Initialise X_train and y_train arrays for this batch<br>            X_train = []<br>            y_train = []<br><br>            # For each example<br>            for batch_sample in batch_samples:<br>                # Load image (X) and label (y)<br>                img_name = batch_sample[0]<br>                label = batch_sample[1]<br>                img =  cv2.imread(os.path.join(root_dir,img_name))<br>                <br>                # apply any kind of preprocessing</pre><pre>                img = cv2.resize(img,(resize,resize))<br>                # Add example to arrays<br>                X_train.append(img)<br>                y_train.append(label)<br><br>            # Make sure they&#39;re numpy arrays (as opposed to lists)<br>            X_train = np.array(X_train)<br>            y_train = np.array(y_train)<br><br>            # The generator-y part: yield the next training batch            <br>            yield X_train, y_train</pre><p>We are defining a function that takes as input :</p><blockquote>samples — the list of (filename,label pairs)</blockquote><blockquote>batchsize=32 — number of samples to load at once</blockquote><blockquote>shuffle_data — whether to shuffle the data or not</blockquote><blockquote>resize=224- what value to resize the images to (you can give parameters for any kind of preprocessing)</blockquote><p>we are creating a while loop that never terminates. After that, we have a for loop to loop over as many batches as defined by batch size and then we are loading the current batch of samples in <em>batch_samples</em>. To store the image sample and labels we are creating two empty lists at the beginning-<em>x_train and y_train</em>. Now we loop over each sample in the current batch for each sample</p><blockquote>1. Get the image name and the corresponding label</blockquote><blockquote>2. Read the image using cv2 and apply any kind of pre processing or transformations</blockquote><blockquote>3. Append the read image and label to x_train and y_train list respectively</blockquote><blockquote>4. Once all the samples in the current batch is read and loaded in the x_train and y_train list, convert this to an array and return it.</blockquote><p>In the above function where I am resizing the image, you can call a preprocessing function in which various pre-processing can be applied like normalization, rotation, etc.</p><p>Now let us call the defined generator and check some values, since we have a batch size of 8 and an image size of 224, the input shape is (8,224,224,3) and there are 8 corresponding labels to these 8 images</p><pre># this will create a generator object<br>train_datagen = generator(samples,batch_size=8,shuffle=True)</pre><pre>x,y = next(train_datagen)<br>print (x.shape)<br>#output: (8, 224, 224, 3)<br>print (y)<br>#output: [0 1 1 4 3 1 4 2]</pre><pre>#### we can plot the data and see by ourselves<br>import matplotlib.pyplot as plt<br>fig = plt.figure(1,figsize=(12,12))<br>for i in range(8):<br>  plt.subplot(4,4,i+1)<br>  plt.tight_layout()<br>  x[i] = x[i][:,:,::-1]<br>  plt.imshow(x[i], interpolation=&#39;none&#39;)<br>  plt.title(&quot;class_label: {}&quot;.format(y[i]))<br>  plt.xticks([])<br>  plt.yticks([])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*fKU0jAQBQHKdmo0TZgUucg.png" /></figure><p>we can use this generator to train a Keras model. <a href="https://keras.io/">Keras</a> has its own image data generator which you can use for training such problems. You can read this blog to see keras ImageDataGenerator in action- <a href="https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html">https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html</a>. I wanted to use this blog to explain how a data generator is created for image classification problems where just one image is input, in the next blog we will see how to create a data generator for multiple inputs (to feed into multiple models) or multi-channel input (say a sequence of frames from a video).</p><pre># Import list of train and validation data (image filenames and image labels)<br>train_samples = load_samples(flower_recognition_train.csv)<br>validation_samples = load_samples(flower_recognition_test.csv)<br><br># Create generator<br>train_generator = generator(train_samples, batch_size=32)<br>validation_generator = generator(validation_samples, batch_size=32)</pre><p>Now we have everything ready, we can either use a pre-trained network like VGG16, ResNet, Inception, etc or design your own network and train it using the created data generator.</p><p>For now, let’s define our own network. I will use Keras here but you can use this dataloader format and structure it to train PyTorch or TensorFlow model as well:</p><pre># import the necessary modules from the library<br>from keras.models import Sequential<br>from keras.layers import Dense, Conv2D, Flatten, Activation, MaxPooling2D, Dropout</pre><pre>input_shape = (Config.resize,Config.resize,3)<br>print (input_shape)</pre><pre>model = Sequential()</pre><pre>model.add(Conv2D(32, (3,3),padding=&#39;same&#39;,input_shape=input_shape,name=&#39;conv2d_1&#39;))<br>model.add(Activation(&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=(2, 2),name=&#39;maxpool2d_1&#39;))</pre><pre>model.add(Conv2D(32, (3, 3),name=&#39;conv2d_2&#39;))<br>model.add(Activation(&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=(2, 2),name=&#39;maxpool2d_2&#39;))model.add(Dropout(0.5))</pre><pre>model.add(Flatten())<br>model.add(Dense(64))<br>model.add(Activation(&#39;relu&#39;))<br>model.add(Dropout(0.5))<br>model.add(Dense(Config.num_classes))<br>model.add(Activation(&#39;softmax&#39;))</pre><pre>model.compile(loss=&#39;categorical_crossentropy&#39;,<br>              optimizer=&#39;rmsprop&#39;,<br>              metrics=[&#39;accuracy&#39;])</pre><pre>model.fit_generator(<br>        train_generator,<br>        steps_per_epoch=num_train_samples // batch_size,<br>        epochs=Config.num_epochs,<br>        validation_data=validation_generator,<br>        validation_steps=num_test_samples // batch_size)</pre><pre>Epoch 1/10<br>402/402 [==============================] - 1249s 3s/step - loss: 1.1912 - acc: 0.5431 - val_loss: 1.1057 - val_acc: 0.6333<br>Epoch 2/10<br>402/402 [==============================] - 1245s 3s/step - loss: 0.7368 - acc: 0.7438 - val_loss: 1.0109 - val_acc: 0.6667<br>Epoch 3/10<br>402/402 [==============================] - 10348s 26s/step - loss: 0.4385 - acc: 0.8529 - val_loss: 1.0953 - val_acc: 0.6467<br>Epoch 4/10<br>  5/402 [..............................] - ETA: 21:18 - loss: 0.2822 - acc: 0.8750</pre><p>The model starts training using the created train and validation generator. This post is not for showing you how to train an efficient model but just to show you how to create and use a data generator</p><p>All the codes in this post are available on GitHub as Python notebook and Python scripts:</p><p><strong>for creating train and test CSV files </strong>— <a href="https://github.com/anujshah1003/custom_data_generator/blob/master/flowers_recognition/preparing_labeled_train_test_csv_files.ipynb">https://github.com/anujshah1003/custom_data_generator/blob/master/flowers_recognition/preparing_labeled_train_test_csv_files.ipynb</a></p><p><strong>for the data generator creation</strong> — <a href="https://github.com/anujshah1003/custom_data_generator/blob/master/flowers_recognition/data_generator_demo.ipynb">https://github.com/anujshah1003/custom_data_generator/blob/master/flowers_recognition/data_generator_demo.ipynb</a></p><p>To conclude, in this post, we saw how we can create our own custom data generator and we did this for the first scenario when you have just single input to be fed to the network. we need to prepare a list in the format given below which can then be used for creating the generator function</p><blockquote>samples — [[frame1_filename,label1], [frame2_filename,label2],……….].</blockquote><p>In the subsequent post, we will see how we can create a generator function for the second and third scenarios when you have multiple inputs or sequences of input.</p><p>Till then, Keep Learning!! Keep Exploring Neurons!!!!</p><p>If you find my articles helpful and wish to support them — <a href="https://www.buymeacoffee.com/anujshah645">Buy me a Coffee</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be9ad08f3f0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>