<?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 Ilango Rajagopal on Medium]]></title>
        <description><![CDATA[Stories by Ilango Rajagopal on Medium]]></description>
        <link>https://medium.com/@ilango100?source=rss-8cd0801dc76f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*lHJwzuJeMgkYUT5qt4YA3w.jpeg</url>
            <title>Stories by Ilango Rajagopal on Medium</title>
            <link>https://medium.com/@ilango100?source=rss-8cd0801dc76f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:39:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ilango100/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[Preparing for TensorFlow Certification]]></title>
            <link>https://medium.com/mediaagility-sparks/preparing-for-tensorflow-certification-4447489d6cd4?source=rss-8cd0801dc76f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4447489d6cd4</guid>
            <category><![CDATA[digital-transformation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[certification]]></category>
            <category><![CDATA[tensorlfow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ilango Rajagopal]]></dc:creator>
            <pubDate>Wed, 16 Dec 2020 10:52:54 GMT</pubDate>
            <atom:updated>2020-12-16T10:52:54.132Z</atom:updated>
            <content:encoded><![CDATA[<h3>A quick guide for level 1 exam of Tensorflow Developer Certification</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rl6BceSubiVjIN3V" /><figcaption>Image source: Pexels.com</figcaption></figure><p><a href="https://www.credential.net/f68a7f38-64a2-4cb9-a30e-a3566a42b0c3">TensorFlow Developer certification</a> was my third certification after <a href="https://www.credential.net/9f100d64-5bb5-4f41-aa53-c4498a6334c5">Google Cloud Associate Cloud Engineer </a>and <a href="https://www.credential.net/77ddb865-3843-4971-9b14-43cabba166d5">Professional Data Engineer</a> certifications. Tensorflow is one of the most important Machine Learning ecosystems and its developer certification helps showcase expertise in Machine Learning and Tensorflow, of course, in particular.</p><p>If you have built basic models on Tensorflow, then cracking this <a href="https://www.tensorflow.org/certificate">exam</a>, which tests foundational knowledge on building and integrating models with Tensorflow, and getting added to <a href="https://developers.google.com/certification/directory/tensorflow">Google’s Certificate Network</a> will be easy for you.</p><p><strong>Here is a quick examination guide.</strong></p><p>The certificate exam tests your ability to build models in the following domains:</p><ul><li>Simple regression models</li><li>Complex models with DNNs</li><li>Image recognition with CNNs</li><li>Natural Language Processing with Text Preprocessing, LSTMs or CNNs</li><li>Time Series prediction</li></ul><h4><strong>Course for the Certification</strong></h4><p>As recommended in the <a href="https://www.tensorflow.org/site-assets/downloads/marketing/cert/TF_Certificate_Candidate_Handbook.pdf">Candidate Handbook</a> for the exam, it’s better to take the Coursera Specialization course: <a href="https://www.coursera.org/specializations/tensorflow-in-practice">Tensorflow in Practice</a>. The course covers all the domains required for the exam. In addition to covering the topics for the exam, it also teaches newer concepts in Tensorflow 2.0 like Keras preprocessing utilities and API.</p><p>If you are coming back to Tensorflow after some time, this course teaches newer and simpler ways of doing things. And if you are experienced in Tensorflow, I recommend that you take the course exercises, at least.</p><p>Since I work as a Machine Learning Engineer at <a href="http://mediaagility.com/">MediaAgility</a> and work with Tensorflow on a daily basis, I took the programming exercises at the end of each week in the specialization. Whenever I would get stuck, I would go through the Tensorflow documentation and API reference to finish those exercises. Doing those exercises prepared me well for the exam.</p><h4>Exam Details</h4><p>The examination costs $100. It is online only. You can take exams from anywhere with these prerequisites:</p><ul><li>A stable internet connection</li><li>PyCharm IDE installed on your system</li></ul><p>The exam duration is five hours and it is more than sufficient time to complete the exam.</p><p>When you start the test, you will have to install a <strong>PyCharm plugin</strong> that provides the programming questions for the examination. The plugin also creates a <strong>python virtual environment</strong> and installs <strong>Tensorflow version 2.0</strong> and the necessary packages required for the test.</p><p>The question has the skeleton of the program, such as downloading the dataset and basic preprocessing steps. You will have to complete the script to build a Tensorflow model and train the model on the dataset. The model will be saved as an h5 file.</p><p>The datasets will not be huge enough to require a lot of time for downloading nor will they be too complicated to require a lot of time for training. You will be able to easily build and train the model in five hours.</p><p>Now for the evaluation — it is not based on the code that you write in the script. It is <strong>completely based on the models</strong> that are trained and saved. When you submit a solution, the test plugin will upload the saved model file and then evaluate based on some test set inputs hidden from the user.</p><p>For each model, a score out of 5 is presented, like 3/5. Based on the result, you can try again with a different model architecture or try training with different hyperparameters, use data augmentation, and more. You can submit the results for each category any number of times. Once you will have achieved satisfactory results in all the question categories, you can submit the whole exam. At the end of five hours, the exam will be submitted automatically.</p><p>I completed the exam in 3 hours after I got 5/5 on all 5 categories. Initially, I had scores like 2/5, 3/5, etc. But I kept trying different approaches till I got 5/5 on all of the categories. Since I got 25/25, I was confident and went ahead and submitted the exam.</p><h4>Exam Tips</h4><p>As mentioned above, the evaluation is not made on the basis of the code that you write, it is based on the models you build. So, it is important that the <strong>model generalizes</strong> and does not overfit the training data. You can use data augmentation and regularization techniques to avoid overfitting and generalize the model better.</p><p>It will help a lot if you get familiar with the PyCharm IDE. Getting to know the shortcuts for quick documentation, function call signature will save a lot of time during the exam. It is also good to have the Tensorflow API reference open by the side to refer to when needed.</p><p>Since this is an online test, you can use AI explainers like LIME, Shapley to debug your model and retrain it based on the explanation. This will also save a lot of time in understanding the model if you keep on getting lower scores. But if you plan to use it, you need to get the explainer setup ready before the exam, so that you don’t end up losing time setting up.</p><p>So, this is my 2 cents from my experience of preparing for this certification with like-minded engineers driven by <a href="https://www.mediaagility.com/careers/">#LifelongLearning</a>. If you have any questions, please share them in the comments section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4447489d6cd4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mediaagility-sparks/preparing-for-tensorflow-certification-4447489d6cd4">Preparing for TensorFlow Certification</a> was originally published in <a href="https://medium.com/mediaagility-sparks">MediaAgility Sparks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intuition behind Residual Neural Networks]]></title>
            <link>https://medium.com/data-science/intuition-behind-residual-neural-networks-fa5d2996b2c7?source=rss-8cd0801dc76f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa5d2996b2c7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[image-recognition]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ilango Rajagopal]]></dc:creator>
            <pubDate>Wed, 22 Jul 2020 15:05:11 GMT</pubDate>
            <atom:updated>2020-07-22T15:05:11.242Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how Residual Networks work and how they are naturally derived</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O4Yeogq7PytlX86K" /><figcaption>Deeper is better? (Photo by <a href="https://unsplash.com/@craig000?utm_source=medium&amp;utm_medium=referral">Riccardo Pelati</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>)</figcaption></figure><p>Deep Neural Networks — “deep” because of large number of layers, have come a long way in lot of Machine Learning tasks. But how deep? Let’s see the popular case of Image Classification: <a href="https://en.wikipedia.org/wiki/AlexNet">AlexNet</a> popularized stacking CNN layers. It consisted of 5 convolution layers. Soon, it was believed that stacking more convolution layers brings better accuracy. <a href="https://arxiv.org/abs/1409.4842">Inception</a> is one of the first architectures to demonstrate better performance by using a very deep architecture. It uses 22 convolution layers. Now, what is the deepest we can go to get better accuracy?</p><p>Let’s build a toy dataset and train on that with neural networks having more and more fully connected layers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b567eb4191fab27e151d0d0778a5232c/href">https://medium.com/media/b567eb4191fab27e151d0d0778a5232c/href</a></iframe><p>This creates “sin function” dataset, creates neural networks with 1 to 30 hidden layers, trains them on the dataset. One might expect that the loss values should be decreasing, then saturating at a point and staying constant. But the results are different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XPj_TXR4NtaPX6lOG4qA3w.png" /><figcaption>Neural network loss increases with number of layers?</figcaption></figure><p>What?! Initially, when having 1 hidden layer, we have high loss, where increasing the number of layers is actually reducing the loss, but when going further than 9 layers, the loss increases. Here we are training for <strong><em>epochs=20*t</em></strong>, meaning more training epochs for bigger model. We get our lowest loss at 9 layers, but above that, loss increases. An important point to note here is this is <strong>not overfitting</strong>, since this is just training loss that we are considering. Does this mean, more layers result in worser performance?</p><h3>Why does this happen?</h3><p>Let’s try to understand this problem intuitively. If a “shallow” model is able to achieve an accuracy, then their deeper counterparts should at least have the same accuracy. But, when the model gets deeper, it becomes more and more difficult for the layers to propagate the information from shallow layers and the information is lost. This is called <strong>Degradation Problem</strong>.</p><p><a href="https://arxiv.org/abs/1512.03385">ResNet paper</a> studies about this problem:</p><blockquote>When deeper networks are able to start converging, a degradation problem has been exposed: with the network depth increasing, accuracy gets saturated (which might be unsurprising) and then degrades rapidly.</blockquote><p>To solve the problem, the deeper layers have to propagate the information from the shallow layers directly, i.e. identity mapping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RP94azymP220VzxPkxyoGQ.png" /><figcaption>As more layers are added to the network, it becomes more difficult to propagate the information from the shallow layers.</figcaption></figure><p>In our case, model with 9 layers is the best performing. In model with 30 layers, the same 9 layers are also present, if the further 21 layers propagate the same result as 9th layer, then the whole model will have the same loss. So now this problem reduces to getting those layers to learn “identity function”, <em>f(x) = x</em>.</p><h3>Solving the Problem with “Shortcuts”</h3><p>Can we modify our network in anyway to avoid this information loss? An intuitive solution is to connect the shallow layers and deep layers directly, so that the information is passed directly to the deep layers, like identity function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qGZ_wE2jItb-NDjNKxYhyw.png" /><figcaption>Shortcuts to the rescue!</figcaption></figure><p>Here we bypass the intermediate layers, and connect the shallow layer to a deep layer. In our case, we could connect 9th layer neurons to the 30th layer directly, then the deep model would perform as same as shallow model. This way, the information is passed directly as identity function. This is the intuition behind Residual Networks.</p><p>By “shortcuts” or “skip connections”, we mean that the result of a neuron is added directly to the corresponding neuron of a deep layer. When added, the intermediate layers will learn their weights to be zero, thus forming identity function. Now, let’s see formally about Residual Learning.</p><h3>Residual Learning</h3><p>Let <em>g(x)</em> be the function learned by the layers. Let’s consider <em>h(x) = g(x)+x</em>, layers with skip connections. Here <em>+x</em> term denotes the skip connection.</p><p>In <em>h(x)=g(x)+x</em>, the +x term will bring the original value, layer g(x) has to learn just <strong>the changes in the value</strong>, or <strong>the residue</strong> or delta x. Whatever being learned in <em>g(x)</em> is just the residue, either positive or negative to modify x to required value. Hence the name “Residual Learning”.</p><p>For <em>h(x)</em> to be identity function, the residue <em>g(x)</em> just has to become zero function, which is <strong>very easy to learn</strong>, i.e. set all weights to zero. Then <em>h(x) = 0+x = x</em>, which is the required identity function. This will help overcome the degradation problem.</p><p>Without skip connections, the weights and bias values have to be modified so that it will correspond to identity function. It is very <strong>difficult to learn </strong>identity function from the scratch, exacerbated by the non-linearity in the layers and results in the degradation problem.</p><blockquote>With the residual learning re-formulation, if identity mappings are optimal, the solvers may simply drive the weights of the multiple nonlinear layers toward zero to approach identity mappings.</blockquote><h3>Residual Neural Networks</h3><p>Let’s see the building blocks of Residual Neural Networks or “ResNets”, the Residual Blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*pQhmHnRaqs4uX_D80Qb8YA.png" /><figcaption>Residual Block [1]</figcaption></figure><p>Here, the skip connection helps bring the identity function to deeper layers. In the Residual Block, some may notice two points:</p><ol><li>Why is the relu applied after adding the skip connection?</li><li>Why are there two weight layers in one residual block?</li></ol><p>For 1, if we had performed relu before addition, then the residues will all be positives or zero. Only positive increments to the identity are learnt, which significantly reduces the learning capacity. For example in the sin function, sin(3<em>π</em>/2) = -1, which would need negative residue. Similarly, using sigmoid will also be disadvantageous, because it produces residues only within 0 to 1. Ideally, we would like <strong>unconstrained response from weight layer </strong>(spanning any numerical range), to be added to skip layer, then apply activation to provide non-linearity. This helps the model learn any function.</p><p>For 2, if we had used a single weight layer, adding skip connection before relu, gives F(x) = Wx+x, which is a simple linear function. This is equivalent to just a single weight layer and there is no point in adding skip connection. So we need <strong>at least one non-linearity before adding skip connection</strong>, which is achieved by using two layers.</p><p>The weight layers in these blocks are learning residuals as we saw in previous section. These blocks can be stacked more and more, but there won’t be degradation in the performance.</p><h3>Implementation</h3><p>Enough theory, let’s see how we can implement residual block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/209ee2a68cb38349c816e74414c1440c/href">https://medium.com/media/209ee2a68cb38349c816e74414c1440c/href</a></iframe><p>This is a simple implementation of residual block. We can call this multiple times to stack more and more blocks. Here we can replace dense layers with convolution layers in the case of images. One constraint to this residual block is that the layer outputs have to be in the same shape as the inputs, but there are workarounds for it.</p><p>Let’s experimentally verify whether the ResNets work the way we describe. We build progressively deeper models and train it on sin function dataset, similar to the example above, this time with Residual blocks. The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ku0ChYxemQyF1hz348ExVA.png" /><figcaption>ResNets does not have degradation problem!</figcaption></figure><p>The above graph clearly verifies the whole point of this ResNets! We see that ResNet is not degrading in performance when we increase the number of layers. It’s actually improving, which is even better! The code for training the PlainNets and ResNets on sin function dataset is in the following github repo:</p><p><a href="https://github.com/ilango100/resnet">ilango100/resnet</a></p><p>This characteristic of ResNet helped train very deep models, spawning several popular neural networks namely ResNet-50, ResNet-101, etc. Can we go even deeper? Lo and behold, <a href="https://github.com/KaimingHe/resnet-1k-layers">ResNet-1001</a>!</p><h3>Results on CIFAR-10</h3><p>Working on toy dataset helped understand the ResNet. Now, time for some real world dataset. The above github repo has code to build and train multiple configurations of ResNets and PlainNets on CIFAR-10. You can see all the implementation details there. It is built using Tensorflow (Keras API).</p><p>The results of training on CIFAR-10 are available here in this <a href="https://tensorboard.dev/experiment/n2VONYJsRRC1nGLI18aLag">tensorboard experiment</a>. You can see the comparison between different depths of PlainNet and ResNet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NccjoBLh4NC3N2VZb2hjXw.png" /><figcaption><a href="https://tensorboard.dev/experiment/n2VONYJsRRC1nGLI18aLag">Tensorboard makes life easier!</a></figcaption></figure><p>The run names are <strong><em>Network x Size</em></strong>. In the ‘Graphs’ tab, you can visualize the network architectures. We can see the skip connections in ResNet models and absence of them in PlainNets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*OEMy6FKLvQTaHaR1AjJKlw.png" /><figcaption><a href="https://tensorboard.dev/experiment/n2VONYJsRRC1nGLI18aLag/#graphs">ResNet and its skip connection</a></figcaption></figure><p>Plotting accuracy values vs network size, we can clearly see, for PlainNet, the accuracy values are decreasing with increase in network size, showcasing the same degradation problem that we saw earlier. As for ResNet, we see increase in accuracy as we increase the network depth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*d7kyxMT4db9zIjfCOjmF3w.png" /><figcaption>Training Accuracy of networks with increasing sizes</figcaption></figure><p>Looking at these graphs, you might be wondering, what ResNetV2 is. ResNetV2 is ResNet with some improvements. That will be topic of another article!</p><h3>Conclusion</h3><p>Key takeaways from here are:</p><ul><li>More layers in neural network does not always mean better performance. Very deep networks tend to degrade in performance.</li><li>Residual networks solve degradation problem by shortcuts or skip connections, by short circuiting shallow layers to deep layers.</li><li>We can stack Residual blocks more and more, without degradation in performance. This enables very deep networks to be built.</li></ul><p>References:</p><p>[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun, <a href="https://arxiv.org/abs/1512.03385">Deep Residual Learning for Image Recognition</a> (2015)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa5d2996b2c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/intuition-behind-residual-neural-networks-fa5d2996b2c7">Intuition behind Residual Neural Networks</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BatchNorm: Fine-Tune your Booster]]></title>
            <link>https://medium.com/@ilango100/batchnorm-fine-tune-your-booster-bef9f9493e22?source=rss-8cd0801dc76f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bef9f9493e22</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Ilango Rajagopal]]></dc:creator>
            <pubDate>Fri, 08 Jun 2018 19:44:09 GMT</pubDate>
            <atom:updated>2018-06-08T19:51:09.480Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@ilango100/batch-normalization-speed-up-neural-network-training-245e39a62f85">previous</a> <a href="https://medium.com/@ilango100/batch-normalization-in-tensorflow-e60bd06148da">posts</a>, I have explained how Batch Norm works and showed how it can be used in tensorflow. In this post, I’ll tell about best practices, tips and tricks and points to remember to complete this series about Batch Normalization. So let’s get in!</p><p>All the examples provided here are also in the github repository, with explanation. You can try those notebooks out.</p><p><a href="https://github.com/ilango100/batch_norm">ilango100/batch_norm</a></p><p>In the previous post, in which I provided links to experiment with CNN, if you have run it in default state, the accuracy of the model would not have risen immediately, making BN useless. This is because I didn’t set an important hyperparameter — Momentum of BN. So let’s start with that.</p><h3>Momentum</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nePTWq-SqDKOoTyl2ztR-A.png" /><figcaption>Here, α is the momentum</figcaption></figure><p>As discussed earlier, momentum is the importance given to the previous moving average, when calculating the population average for inference. If you can’t understand what momentum is, It’s nothing but the <strong>smoothing</strong> that we can adjust in Tensorboard. Momentum is the “lag” in learning mean and variance, so that noise due to mini-batch can be ignored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZZ99uw9Cg4mwDYta4beJQ.png" /><figcaption>Actual(light) and lagged(bold) values with momentum 0.99 and 0.75</figcaption></figure><p>By default, momentum would be set a high value about 0.99, meaning high lag and slow learning. When <strong>batch sizes are small</strong>, the no. of steps run will be more. So high momentum will result in slow but steady learning (more lag) of the moving mean. So, in this case, it is helpful.</p><p>But when the <strong>batch size is bigger</strong>, as I have used, i.e 5K images (out of 50K) in single step, the number of steps is less. Also, the statistics of mini-batch are mostly same as that of the population. At these times, momentum has to be less, so that the mean and variance are updated quickly. Hence a ground rule is that:</p><blockquote>Small batch size =&gt; High Momentum (0.9–0.99)</blockquote><blockquote>Big batch size =&gt; Low Momentum (0.6–0.85)</blockquote><p>For big batch size, even better scheme is <strong>inverse decay momentum</strong>, where momentum is very less at starting and goes on increasing as and when training goes on:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32e54555e83a30bbf9c39501c9fd0137/href">https://medium.com/media/32e54555e83a30bbf9c39501c9fd0137/href</a></iframe><p>In the colab notebook I have provided, you can now set the momentum as hyperparameter and see how training goes.</p><h3>Scale and Shift</h3><p>Scale and shift parameters are applied to normalized values to move the distribution away from around 0. This is mostly useful when BN is used before activation. Currently, BN is widely applied after activation and so, these parameters could be neglected. The tensorflow way to do that would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10eacf8d39d20ed5b554be0e57cd6482/href">https://medium.com/media/10eacf8d39d20ed5b554be0e57cd6482/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-tyPQdTQmaK8gLjYafEQPw.png" /><figcaption>There is no difference when scaling and shifted are used and not used. Note that BN is applied after activation.</figcaption></figure><p>The difference would be that, it is not needed to learn 2 extra parameters with each batch_norm layer and hence extra speed up. Also leads to lesser parameters and slimmer models. You can see the changes in accuracy and training time with and without scale and shift with <a href="https://colab.research.google.com/drive/1d6RkPZoZ1DanTRRJbZGGBo3wdJxW-dag">this Colab Notebook</a>.</p><blockquote>BN before non-linearity =&gt; Use scale, shift</blockquote><blockquote>BN after non-linearity =&gt; No need of scale, shift</blockquote><h3>BatchNorm and Dropout</h3><p>So far we have used only Batch Normalization and saw our model overfit the data. We have also learnt that BN can only provide a weak regularization, which should be used in addition with any other regularization such as Dropout. But how shall we use Dropout and BatchNorm together?</p><p><a href="https://arxiv.org/abs/1801.05134">Disharmony between Dropout and Batch Normalization</a> — this paper studied in detail about the problems faced when dropout and BN are used together. The best conclusion drawn is that dropout should be used only after all the BN layers, i.e. at final dense layers. BatchNorm should not be used after a dropout layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEgmneUW2GtcwIT9sJlFIQ.png" /><figcaption>(a) When BN layers are applied after dropout (b) When dropout layers are applied after all BN</figcaption></figure><p>As we can see, when BN is used after dropout, the accuracy is not stable. Dropout should be used at the end of the network, where BN cannot come after that.</p><blockquote>Use dropout after all BN layers</blockquote><p><a href="https://colab.research.google.com/drive/1D9_ltbQaT7yCpnEyg8il1jpRrxEQEWfx">This Colab Notebook</a> provides you framework to check how batchnorm performs after dropout and in ideal way.</p><h3>Batch Renormalization</h3><p><a href="https://arxiv.org/abs/1702.03275">Batch Renormalization</a> is another technique used when batch size is very small like 32, 64 etc. There taking mini-batch mean and variance may be too error-prone and hence moving statistics are taken for training itself. This leads to more accurate training. But then you need to set another set of hyperparameters like momentum for this moving statistics.</p><p>To enable batch renorm in Tensorflow, set renorm parameter to True and also set the renorm_momentum:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59ee01cb4ee4b234eba9731bbc49fd2f/href">https://medium.com/media/59ee01cb4ee4b234eba9731bbc49fd2f/href</a></iframe><blockquote>Tiny batch size =&gt; Use Batch Renormalization</blockquote><h3>Update moving statistics</h3><p>One of the important things people tend to forget when using Batch Normalization is that they forget to update the moving average when training. So at testing time, the inference values for mean and variance are missing, ending up in low accuracy.</p><p>In tensorflow, add update ops as dependency to training step:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1dfd76f3a5b1a0e13f2c0b56ce7d4fb/href">https://medium.com/media/f1dfd76f3a5b1a0e13f2c0b56ce7d4fb/href</a></iframe><p>To summarize:</p><ol><li>Set momentum accordingly.</li><li>Use scale and shift only when needed.</li><li>Use dropout correctly: Dropout to be applied after all the BN layers.</li><li>When batch size is very small, use batch renormalization.</li><li>Don’t forget to update population statistics while training.</li></ol><p>This wraps up the series about Batch Normalization. If you have any queries or suggestions, feel free to comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bef9f9493e22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Batch Normalization —With TensorFlow]]></title>
            <link>https://medium.com/@ilango100/batch-normalization-in-tensorflow-e60bd06148da?source=rss-8cd0801dc76f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e60bd06148da</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[image-recognition]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Ilango Rajagopal]]></dc:creator>
            <pubDate>Sun, 03 Jun 2018 21:25:02 GMT</pubDate>
            <atom:updated>2018-06-08T19:13:34.784Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@ilango100/batch-normalization-speed-up-neural-network-training-245e39a62f85">previous post</a>, I introduced Batch Normalization and hoped it gave a rough understanding about BN. Here we shall see how BN can be incorporated in your models. I am using Tensorflow as my platform.</p><p>Tensorflow offers lot of flexibility and ease of use. It provides both High level and Low level APIs. The Estimator API provides super-fast way to create, train and test a model. Tensorflow also provides <strong>TensorBoard</strong>, an interactive visualization tool. It helps view the plots or model graph.</p><h4>Dataset</h4><p>The dataset I have chosen to work with is CIFAR 10, which is a famous dataset for image recognition. The images are of size 32x32, with 10 categories for classification. It has 50,000 images to train and 10,000 images to test. A simple neural network with 3 conv layers and 2 dense layers is mostly enough to learn the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*SQ25eg8_qY6y9E6Edk-JkQ.jpeg" /><figcaption>Convolution layer</figcaption></figure><h4>Google Colaboratory</h4><p>Colaboratory is a Google research project created to help disseminate machine learning education and research. It’s a Jupyter notebook environment that requires no setup to use and runs entirely in the cloud. It even provides a GPU accelerator to speed up training. And all of it for free, if you have a Google Account.</p><p>The model done here is available as <a href="https://colab.research.google.com/drive/1w7k4r7CQaqnK_f6596SbuON9xcaw5lNo">Colab notebook here</a>. You can experiment with the notebook as you read through this post. On opening, you need to save it to your google drive first. Then, Go to Edit -&gt; Notebook Settings -&gt; <strong>Select Accelerator</strong> -&gt; <strong>GPU</strong>, so that training happens faster.</p><p>If you want to run the notebook in your local system, clone this Github repo:</p><p><a href="https://github.com/ilango100/batch_norm">ilango100/batch_norm</a></p><h3>Define the Model</h3><p>The model is first defined as a generic convnet specification:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f9e7375fc8a5d22bd909febd7f4ef3b/href">https://medium.com/media/2f9e7375fc8a5d22bd909febd7f4ef3b/href</a></iframe><p>In lines 43–46, this is where we tell Tensorflow to update the moving average of mean and variance, at training time. It is important to include this, which many tend to forget. Make sure you include to update moving averages during training.</p><p>Since this model is generic, it builds a Convolutional neural network, given the hyper-parameters as params. For my model, I have given the hyper-parameters as:</p><pre>hparams = {<br>    &quot;filters&quot;: [30, 50, 60],<br>    &quot;kern&quot;: [[3, 3]]*3,<br>    &quot;strides&quot;: [[2, 2], [1, 1], [1, 1]],<br>    &quot;dense&quot;: [3500, 700],<br>    &quot;n_classes&quot;: 10,<br>    &quot;with_bn&quot;: True<br>}</pre><p>You can tweak the parameters such as filters, kernel, strides or even number of dense layers and units after conv layers. Just experiment with the values and see what you can find. Also, ‘with_bn’ can be changed to include BatchNorm or not. First we disable it and train the dataset. Then we enable BatchNorm and train to compare the results.</p><h4>BatchNorm before or after Activation</h4><p>In the previous post, we saw that BatchNorm can be applied before or after non-linearity, which is still a question of debate. In the current model, I have decided to use BatchNorm after Activation, and more specifically, before the input of each layer, since BatchNorm was introduced to reduce the internal covariate shift. As to use whether scaling and shifting, I decided to use them for now.</p><h4>Pooling Layers</h4><p>Pooling Layers are mostly used in convolutional networks when the size of the images are large and need to be scaled down. It also provides translational and rotational invariance, i.e, provides same output if the region of feature map is rotated. But in most cases, size reduction can be achieved by increasing stride of conv layer. <a href="https://arxiv.org/abs/1412.6806">This paper</a> studied such models and shows that pooling layer is not necessary at all.</p><p>Some image recognition models use pooling, and some use only conv layer with stride greater than 1. In my model, I have decided not to use pooling layer. Instead, I used stride of 2x2 in the first layer to reduce resolution and consecutive layers stride of 1x1.</p><h3>Let’s start the Train!</h3><p>I highly recommend using Google Colab with GPU accelerator for training, unless you have a powerful GPU in your system. Let us start training the model. Since Estimator API is used, the learnt parameters as saved automatically while training. The training graph can be viewed in TensorBoard.</p><p>The version without BN is run for 400 steps and with BN is run only until 100 steps. For each 2 training epochs, a testing run is done. The results can be seen here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RM_dQP4e0cD9xYWvnMj_Xg.png" /><figcaption>Loss without BatchNorm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43FHCUQAYrQ2MqcQ5hEPkw.png" /><figcaption>Loss with BatchNorm</figcaption></figure><p>As we can see, what the model without BN achieves in 350 steps, the model with BN achieves in just 70! Training with BN is faster by factor of 5. Batch Normalization is working after all!</p><p>With this model only 65 to 70% accuracy can be achieved. Many models employ <strong>data augmentation</strong>, to improve accuracy, which I will explain later in another post.</p><h4>Overfitting</h4><p>As we can see in the plots, testing losses (blue) goes up during training — an obvious indication of overfitting. For now, I have concentrated only to know how the BN fastens up the regular networks. So, I didn’t use any regularization.</p><p>BN also provides a weak form of regularization. But since here it cannot prevent overfitting, it should be used with any other regularization layers like dropout.</p><p>But how to use dropout? Like activation, should it be used before or after BN? And how would the current model perform if it is applied before activation or when scaling and shifting parameters are neglected? We shall find out in the next post.</p><p>Do try this out with <a href="https://colab.research.google.com/drive/1w7k4r7CQaqnK_f6596SbuON9xcaw5lNo">the Colab Notebook</a> and comment about any difficulties you faced or things you want explanation about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e60bd06148da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Batch Normalization — Speed up Neural Network Training]]></title>
            <link>https://medium.com/@ilango100/batch-normalization-speed-up-neural-network-training-245e39a62f85?source=rss-8cd0801dc76f------2</link>
            <guid isPermaLink="false">https://medium.com/p/245e39a62f85</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Ilango Rajagopal]]></dc:creator>
            <pubDate>Tue, 29 May 2018 19:15:58 GMT</pubDate>
            <atom:updated>2018-06-12T14:55:09.026Z</atom:updated>
            <content:encoded><![CDATA[<p>Neural Network — a complex device, which is becoming one of the basic building blocks of AI. One of the important issues with using neural network is that the training of the network takes a long time for effectively deep networks — even on GPUs, let alone CPUs.</p><p>Neural networks learn the problem using BackPropagation algorithm. By backpropagation, the neurons learn how much error they did and correct themselves, i.e, correct their “weights” and “biases”. By this they learn the problem to produce correct outputs given the inputs. BackPropagation involves computing gradients for each layer and propagating it backward, hence the name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*rXY5zJrDdHv6EdKhJvKqcA.png" /><figcaption>The BackProp Algorithm</figcaption></figure><p>But during backpropagation of errors to the weights and biases, we’ll face a undesired property of Internal Covariate Shift. This makes the network too long to train.</p><h3>Internal Covariate Shift</h3><p>During training, each layer is trying to correct itself for the error made up during the forward propagation. But every single layer acts separately, trying to correct itself for the error made up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*X76xBHMpT4rzws_-L2s1TA.png" /><figcaption>Internal Covariate Shift</figcaption></figure><p>For example, in the network given above, the 2nd layer adjusts its weights and biases to correct for the output. But due to this readjustment, the output of 2nd layer, i.e, the input of 3rd layer is changed for same initial input. So the third layer has to learn from scratch to produce the correct outputs for the same data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*-QyZahd2pGwQv2T_Wo11VA.png" /><figcaption>Order of training</figcaption></figure><p>This presents the problem of a layer starting to learn after it’s previous layer, i.e, 3rd layer learns after 2nd finished, 4th starts learning after 3rd, etc. Similarly, think of the current existing deep neural networks that are about 100 to even 1000 layers deep! It would really take epochs to train them :D</p><p>More specifically, due to changes in weights of previous layers, the distribution of input values for current layer changes, forcing it to learn from new “input distribution”.</p><h3>Normalization</h3><p>In a dataset, all the features (columns) may not be in same range. For eg. Price of house (thousands), Age of house (within 100) etc. It takes lot of time to train for these kind of datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*4T4y3kI0R9Alk_2pe6B4Pg.png" /><figcaption>Raw and normalized data</figcaption></figure><p>Usually, in simpler ML algorithms like linear regression, the input is “normalized” before training to make them into single distribution. Normalization is to convert the distribution of all inputs to have <strong>mean=0</strong> and <strong>standard deviation=1</strong>. So most of the values lie between -1 and 1.</p><p>We can even apply this normalization to the input of neural networks. It fastens up training as in linear regression. But since the 2nd layer changes this distribution, the consecutive layers are not benefited. So, what can we do? Yeah! Why not add normalization between each layers? This is what Batch normalization does.</p><h3>Batch Normalization</h3><p>To reduce this problem of internal covariate shift, Batch Normalization adds Normalization “layer” between each layers. An important thing to note here is that normalization has to be done separately for each dimension (input neuron), over the ‘mini-batches’, and not altogether with all dimensions. Hence the name ‘batch’ normalization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*WRio7MD4JDeLww-CyrxEbg.png" /><figcaption>Batch Normalization</figcaption></figure><p>Due to this normalization “layers” between each fully connected layers, the range of input distribution of each layer stays the same, no matter the changes in the previous layer. Given <em>x</em> inputs from <em>k</em>-th neuron.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*c9mS1eNNJQqIFKvu8_Ji7g.png" /></figure><p>Normalization brings all the inputs centered around 0. This way, there is not much change in each layer input. So, layers in the network can learn from the back-propagation simultaneously, without waiting for the previous layer to learn. This fastens up the training of networks.</p><blockquote>We apply Batch Normalization to the best-performing ImageNet classification network, and show that we can match its performance using only 7% of the training steps, and can further exceed its accuracy by a substantial margin. — <a href="https://arxiv.org/pdf/1502.03167.pdf">Original BatchNorm Paper</a></blockquote><p>Batch Normalization is great. But, there are a few minor issues with BatchNorm which we need to take care of.</p><h3>Scale and Shift</h3><p>There are usually two types in which Batch Normalization can be applied:</p><ol><li>Before activation function (non-linearity)</li><li>After non-linearity</li></ol><p>In the original paper, BatchNorm is applied before the applying activation. Most of the activation functions have problems while applied this way. For sigmoid and tanh activation, normalized region is more of linear than nonlinear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RTaZgDmAQ-3issS0S74zA.png" /><figcaption>Sigmoid and Tanh become linear near zero</figcaption></figure><p>For relu activation, half of the inputs are zeroed out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*KkyMv1R6dEdqlSiqX4l5kg.png" /><figcaption>Relu activation</figcaption></figure><p>So, some transformation has to be done to move the distribution away from 0. A scaling factor γ and shifting factor β are used to do this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*eVoEAup1t0agj-_7T0nQEA.png" /></figure><p>As training progresses, these γ and β also learn through backpropagation so as to improve accuracy. This imposes that 2 extra parameters be learnt for each layer to increase training speed.</p><p>This final transformation thus completes definition of Batch Normalization algorithm. Use of scaling and shifting is particularly much useful because, it provides more flexibility. Suppose if we decide not to use BatchNorm, we can set <strong><em>γ = σ</em></strong> and <strong><em>β = mean</em></strong>, thus giving back the original values.</p><p>Recently, it has been observed that the BatchNorm when applied after activation, performs better and even gives better accuracy. For such case, we may decide to use only BatchNorm alone and not scaling and shifting. For such, set <strong><em>γ = 1 </em></strong>and <strong><em>β = 0</em></strong>. Nevertheless, γ and β are included in Batch Normalization Algorithm.</p><h3>BatchNorm at Inference time</h3><p>We now know that Batch Normalization calculates mean and variance for each mini-batch at training time and learns using back-propagation. But, what to do at Inference time? It would not be ok if we are to use mean and variance of testing mini-batch, because it may be skewed.</p><p>What we do is, we calculate “population average” of mean and variances after training, using all the mini-batch mean and variances. And at inference time, we fix the mean and variance to be this value and use it in normalization. This provides more accurate value of mean and variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*jI7ARlj8waUzILS5zYHiog.png" /><figcaption>Population mean and variance.</figcaption></figure><p>But, sometimes, it is difficult to keep track of all the mini-batch mean and variances. In such cases, exponential weighted “moving average” can be used to update population mean and variance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nePTWq-SqDKOoTyl2ztR-A.png" /><figcaption>Calculation of moving mean and variance</figcaption></figure><p>Here α is the “momentum” given to previous moving statistic, around 0.9. And those with B subscript are mini-batch mean and mini-batch variance. This is the implementation found in most libraries, where the momentum can be set manually.</p><p>An important thing to note here is that the moving mean and moving variance are calculated at training time, with training dataset and not at testing time.</p><h3>Regularization by BatchNorm</h3><p>In addition to fastening up the learning of neural networks, BatchNorm also provides a weak form of regularization. How does it introduce Regularization? Regularization may be caused by introduction of noise to the data. Since the normalization is not performed on the whole dataset and just on the mini-batch, they act as noise.</p><p>However BatchNorm provides only a weak regularization, it must not be fully relied upon to avoid over-fitting. Yet, other regularization could be reduced accordingly. For example, if dropout of 0.6 (drop rate) is to be given, with BatchNorm, you can reduce the drop rate to 0.4. BatchNorm provides regularization only when the batch size is small.</p><p>This ends introduction to Batch Normalization. In the <a href="https://medium.com/@ilango100/batch-normalization-in-tensorflow-e60bd06148da">next post</a>, I have explained how Batch Normalization layers can be used with Tensorflow and provided links to train neural network with and without Batch Normalization.</p><p>Please do comment about what you feel about this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=245e39a62f85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>