<?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 Rrohan.Arrora on Medium]]></title>
        <description><![CDATA[Stories by Rrohan.Arrora on Medium]]></description>
        <link>https://medium.com/@rrohan-arrora?source=rss-dbb9cfaeb49a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*kYJ8ooTIav1nhVcKlhw6dg.png</url>
            <title>Stories by Rrohan.Arrora on Medium</title>
            <link>https://medium.com/@rrohan-arrora?source=rss-dbb9cfaeb49a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:25:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rrohan-arrora/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[Positional Encodings: let us revise together]]></title>
            <link>https://medium.com/ai-quest/positional-encodings-let-us-revise-together-40f78e12ae0e?source=rss-dbb9cfaeb49a------2</link>
            <guid isPermaLink="false">https://medium.com/p/40f78e12ae0e</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[self-attention]]></category>
            <category><![CDATA[positional-encoding]]></category>
            <dc:creator><![CDATA[Rrohan.Arrora]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 07:03:58 GMT</pubDate>
            <atom:updated>2024-08-28T12:48:05.007Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What you think is important is actually surprising…</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaM8adwv4U6ZWQ33-_PmTQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@markkoenig?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Mark König</a> on <a href="https://unsplash.com/photos/yellow-and-black-metal-frame-bMHWFXjp6-Q?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>This blog aims to provide you with an insight into what are positional encodings and how they are calculated.</p><p>Before we dive into the above concepts, let&#39;s review the basics.</p><h3>What is self-attention?</h3><p>Ans: Embeddings are always a better choice to use, but embeddings capture “<strong>average meaning</strong>.” They behave the same in different sentences with respect to the semantic meaning, irrespective of the context of the sentence.</p><p>i.e., <strong>an apple a day keeps the doctor away,</strong> and <strong>Apple is a multinational company.</strong></p><p>Here, embedding for Apple will capture the average meaning rather than the sentence in which it is used.</p><p>All in all, we need to capture the context of the sentence, and self-attention helps in that. Self-attention not only captures the context of the sentence and produces contextual embeddings, but this whole process of calculating the contextual embeddings occurs in parallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-9lZ-gS-6tNWAUbjpl-tug.jpeg" /><figcaption>I hope you already know what happens inside the Self-attention block.</figcaption></figure><p>But self-attention is not the sole winner. Self-attention may help us capture the contextual meaning of the sentence, but which word is in what order or what position? Self-attention does not tell us that.</p><p>i.e., <strong>the tiger killed the king </strong>or<strong> the king killed the tiger.</strong></p><p>For both of the above sentences, it will capture the same context (when both sentences are completely opposite), and the whole process will happen in parallel.</p><p>And here is where <strong>POSITIONAL ENCODING</strong> comes into play.</p><h3>Positional Encodings</h3><p>Let us start with some scenario. You have to place students in a row for the assembly, and you have to ensure that Rohan should always place after Maria, Maria is always placed after John, and there are a total of n students. The best way to ensure this is to give positions to the students, which will be easy to remember.</p><p>The same way, we will add a number corresponding to the position of the work in the embedding before giving it to the self-attention block, and it resolves our problem.</p><p>Wait, wait, wait,</p><p>It is not that easy. It might be a better solution, but it is not the best solution as it has few problems.</p><blockquote>Problem 1: Imagine a document consisting of thousands of words. It will be unbounded as the last word will have a large position number. And <strong>NN hates big numbers.</strong></blockquote><p>Solution: I heard you, and you suggested normalising the positions. Fine, let us normalise the positions.</p><p>Let us take an example and understand this. (I know it is simple, but hold on with me 😅)</p><p>There are 2 sentences.</p><p>I love machine learning — for this sentence, the normalized value for machine will be 3/4.</p><p>I hate machines—for this sentence, the normalized value will be 3/3 for machines, which will be 1.</p><p>Now for the same position, the normalised value is different, and this creates a discrepancy in the training data, and NN hates this(😿).</p><blockquote>Problem 2: Descrete numbers are used as positions, and NN suffers from numerical stability and gradient flow problems.</blockquote><blockquote>Problem 3: Relative position is not captured. Tiger word is how much distance from king, it is not captured. Only absolute position is captured.</blockquote><p>Solution:</p><p>We want a solution that is</p><ol><li><strong>Bounded</strong></li><li><strong>Continuous</strong></li><li><strong>Relative position</strong> is also captured</li></ol><p>And periodic functions like <strong>sine</strong> is the solution.</p><h3>The sine function as a solution</h3><p>sine curve definitely solves the previous 3 problems.<br>1. It is bound.<br>2. It is continuous.<br>3. It captures relative position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4wiWXlkywshWAB9h1yZbQ.png" /><figcaption>Sine function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*551HihK2n0yPtB6RmWPAwQ.jpeg" /></figure><p>💡 <strong>Do you think, we have achieved the solution?<br></strong>Positional encoding for every word should be unique but sine curve is periodic and values may repeat after a certain time. This will lead to an even bigger problem as more than 1 word will have the same positional encoding. Even though it solves the previous 3 problems, it introduces a new one.</p><p>The easiest solution is to use more than 1 trigonometric functions. and each word will be represented a vector. The catch here is that the frequency of every sine/cosine function added is lower than the previous one, and you can see that in the figure added below.</p><p>sol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQZ-i44cicSAYOT4I4Silg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTWXnclBFdpN-rz8Fs8pwg.jpeg" /><figcaption>Tiger: Vector[Sin(pos)=X, Cos(pos)=Y, Sin(pos/2)=Z, Cos(pos/2)=W]</figcaption></figure><p>Now, chances of numbers having same positional encoding is reduced. If the document is huge, then introduce more periodic functions, which will further reduce the chances of any two numbers having the same positional encoding.</p><p>Now, as per the research paper, attention<strong> is all you need.</strong></p><ol><li>The positional encoding vector is the same size as the embedding vector. In the original paper, a 512-dimensional self-encoding vector is used; therefore, 256 unique pairs of sine-cosine functions are used.</li><li>We add the embedding vector and positional encoding vector (rather than concatenating) and then pass it to the self-attention block.</li></ol><p>We still need to discuss about the frequency of sine-cosine functions and as per the paper, they have given below 2 functions to decide the frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*7yvl1s8GMGdG5icm3ufjNw.png" /></figure><p>How this formula comes, I also do not know. But we can apply and understand how this formula works.</p><p><strong>Pos</strong>: refers to the position of the word, which starts from 0.<br><strong>dmodel</strong>: dimensions of embeddings.<br><strong>i</strong>: fluctuates from 0 to dmodel/2–1</p><p>Let us take a model where we have embeddings of 6-dimension; therefore, the positional encoding vector for <strong>TIGER</strong> will also be of 6-dimension.</p><blockquote><strong>for i=0</strong>,<br>PE(0, 0) = Sin(0/10000⁰) = 0<br>PE(0, 0) = Cos(0/10000⁰) = 1</blockquote><blockquote><strong>for i=1</strong>,<br>PE(0, 2) = Sin(0/10000^(1/3)) = 0<br>PE(0, 3) = Cos(0/10000^(1/3)) = 1</blockquote><blockquote><strong>for i=2</strong>,<br>PE(0, 2) = Sin(0/10000^(2/3)) = 0<br>PE(0, 3) = Cos(0/10000^(2/3)) = 1</blockquote><p>So, this way we can calculate position encoding for every word and this whole process happens in parallel.</p><p>✈️: Position encoding of first word is always [0, 1, 0, 1, 0, 1... Here, it was in 6 dimension.</p><p>Now, let embedding for Tiger be [0.2, 0.4, 0.4, 0.5, 0.01, 0.09]</p><p>final vector would be = [0.2, 0.4, 0.4, 0.5, 0.01, 0.09] + [0, 1, 0, 1, 0, 1] = [0.2, 1.4, 0.4, 1.5, 0.01, 1.09].</p><p>And this final vector is an amalgam of embedding vector and positional encoding vector both, and this is fed to the self-attention block.</p><p><em>I hope I was able to structure it in a way that could help you. Do not foget to give a clap.</em></p><h3><strong>References:</strong></h3><ol><li><a href="https://arxiv.org/abs/1706.03762">Attention is all you need</a></li><li><a href="https://blog.timodenk.com/"><strong>Timo Denk’s Blog</strong></a></li><li><a href="https://www.youtube.com/watch?v=GeoQBNNqIbM&amp;list=PLKnIA16_RmvYuZauWaPlRTC54KxSNLtNn&amp;index=78">Campu</a>sX</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40f78e12ae0e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-quest/positional-encodings-let-us-revise-together-40f78e12ae0e">Positional Encodings: let us revise together</a> was originally published in <a href="https://medium.com/ai-quest">AI n U</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a good AI model for your startup?]]></title>
            <link>https://medium.com/ai-quest/how-to-build-a-good-ai-model-for-your-startup-37686b0be9a2?source=rss-dbb9cfaeb49a------2</link>
            <guid isPermaLink="false">https://medium.com/p/37686b0be9a2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rrohan.Arrora]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 19:36:26 GMT</pubDate>
            <atom:updated>2020-12-14T19:36:26.375Z</atom:updated>
            <content:encoded><![CDATA[<p>I will discuss the overview of how to build a good Artificial Intelligence model. I won’t be getting into many details of the processes, but you will certainly get the idea behind the excellent model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhqNdKi0FsjOPwwkjj1oVw.png" /><figcaption>Image Source — Fastai</figcaption></figure><h3>Step — 1</h3><p><strong>Overfit your model — </strong>Now, I know you people might be thinking that how overfitting can lead to a good model. Hold On! Let us first understand,</p><p><strong>What is Overfitting?</strong></p><p>A more traditional definition of overfitting states that if your training loss is lower than your validation loss, that means you are overfitting your model. But that is not accurate. Almost every good model has a more moderate training loss than the validation loss. So, the traditional definition of the overfitting is not all correct. But, to get a perfect model instead of gathering a smaller amount of data to avoid overfitting, which is what generally happens most of the time, instead, I would suggest you pick the right amount of data and start to overfit your model.</p><p>According to the more recent definition, Overfitting happens when your validation loss starts to decrease due to the overtraining of your model such that your model crams/learns the input rather than learning the behaviour of the input. <strong>But it’s ok.</strong></p><h3>Step — 2</h3><p><strong>Reduce overfitting — </strong>How unprofessional it is sounding, may not be at all. I told you to overfit the model against to train your model on lesser data which people used to do. So, What I want to say is very clear.</p><ul><li>Gather a large amount of data and train your model.</li><li>Let it get overfit.</li><li>If your model overfits, start to reduce the overfitting using the below methods.</li></ul><p><strong>Methods to reduce overfitting(in sequential order)</strong></p><ul><li><strong>Reduce the number of epochs</strong> — In some situations, when we cannot gather more amount of data, it is better to train the model on lesser epochs. Lesses epochs will help the model to train for lesser time, thus, less amount of interaction time between the model and the inputs and, therefore, less overfitting.</li><li><strong>More Data</strong> — It is always the first and foremost approach to reduce overfitting. Try to gather more amount of relevant data to reduce overfitting.</li><li><strong>Data Augmentation</strong> — In case of vision classification problems, Apply data augmentation to the images do as to reduce the overfitting. Data augmentation is a type of regularization technique but more broadly defined.</li><li><strong>Regularization </strong>— There are a lot of regularization techniques that I have already mentioned here. Take a look at them <a href="https://towardsdatascience.com/regularization-techniques-a-list-down-70df0e8693c">here</a>.</li><li><strong>Reduce the architectural complexity </strong>— This option should be the last preference when you are not able to reduce overfitting using the above three methods.</li></ul><p>Now, what happens is that whenever we overfit the model, we start with reducing the architectural complexity by reducing the number of layers in the model unless the model is very complex to handle. But that should be the last approach to manage. Firstly, you should start with more data, followed by Data Augmentation, Regularization, and then, at last, reducing the architectural complexity.</p><h3>Step — 3</h3><p>Train your model more and more based on the above steps. Building a good model comes more from practice and the intuitions which come with training.</p><p>I will add more and more methods on how to train a useful model with time. Till then, start loving and exploring Artificial Intelligence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37686b0be9a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-quest/how-to-build-a-good-ai-model-for-your-startup-37686b0be9a2">How to build a good AI model for your startup?</a> was originally published in <a href="https://medium.com/ai-quest">AI n U</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Percentiles, Quantiles and Plots]]></title>
            <link>https://rrohan-arrora.medium.com/percentiles-quantiles-and-plots-d094d8e5a266?source=rss-dbb9cfaeb49a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d094d8e5a266</guid>
            <category><![CDATA[quartile]]></category>
            <category><![CDATA[box-plot]]></category>
            <category><![CDATA[quantile]]></category>
            <category><![CDATA[violin-plot]]></category>
            <category><![CDATA[percentiles]]></category>
            <dc:creator><![CDATA[Rrohan.Arrora]]></dc:creator>
            <pubDate>Tue, 14 Apr 2020 11:50:21 GMT</pubDate>
            <atom:updated>2020-04-14T18:20:41.547Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understand the percentiles and quantiles, then the plots using these concepts.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwuV4OugFKdYhAXsvVtQXQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/hudsoncrafted-5201554/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4916430">hudsoncrafted</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4916430">Pixabay</a></figcaption></figure><h4>— What are percentiles?</h4><p>Consider an array consisting of 100 sorted values as shown below.</p><p>array Aᵢ= [A₁, A₂, A₃, A₄, A₅, A₆, A₇, A₈, A₉, A₁₀, ………, A₉₉, A₁₀₀]</p><p>The median of the above array is the average of A₅₀ &amp; A₅₁ values. The 50ᵗʰ percentile of the above array is actually the median of the array and it is equal to A₅₀. The 90th percentile of the above-sorted array is A₉₀. Similarly, the 20th percentile of the above-sorted array is A₂₀.</p><p>Therefore, once the values are sorted, then the values at the index become the percentile values. But, the question is, what does percentile tell about the data?</p><p>Let us understand the idea behind the percentiles with an example. Consider that you are working in any e-commerce company like Flipkart, Amazon or Myntra. You are a delivery manager and you want to know the average days taken for the delivery of the products.</p><p>Let the 95ᵗʰ percentile value = 4 and 99ᵗʰ percentile value = 5.4.</p><p>⇒ 95 percent of your deliveries are taking 4 days on average and 99 percent of the deliveries to customers are taking 5.4 days. Now, if you want to improve, then you need to fasten the deliveries by 1% in order to deliver the customer their packages before 6 days time limit.</p><p>The same goes for your sore in competitive exams as well. If your percentile is 99%, then that means that 99% of the score of the people appearing in the exam is less than you.</p><p>This is how percentiles help in evaluating the data.</p><h4>— What are quantiles?</h4><p>As the name suggests,</p><p>0ᵗʰ, 25ᵗʰ, 50ᵗʰ, 75ᵗʰ percentile values or 25ᵗʰ, 50ᵗʰ, 75ᵗʰ, 100ᵗʰ percentile values are known as quantiles.</p><h4>— Mean Absolute Deviation</h4><p>Let the median of input datasets is m . The dataset consists of 100 points as A₁, A₂, A₃, A₄, A₅, A₆, A₇, A₈, A₉, A₁₀, ………, A₉₉, A₁₀₀. Then MAD is defined as</p><pre>       100<br>median(Σ |Aᵢ-m|)<br>       n=1</pre><p>We could take mean as well but mean is very sensitive to outliers, therefore MAD is more reliable. This concept is similar to the traditional standard deviation.</p><h4>— Inter Quartile Range(IQR)</h4><p>Let the 75ᵗʰ percentile value be P₇₅ and 25ᵗʰ percentile value is P₂₅.</p><pre>IQR = P₇₅ - P₂₅</pre><p>50% of the values lie in this IQR range.</p><h4>— Box plot and Whiskers</h4><p>Though histograms are very valuable in telling the density of the points, they cannot give us the percentile values for the given data. Of course, we can get percentile estimates from CDF plots but there are some other plots, which tell more accurately with a gob of other things.</p><p><a href="https://www.wellbeingatschool.org.nz/information-sheet/understanding-and-interpreting-box-plots">Box plots</a> tell very accurately about the percentiles. Let us understand these plots.</p><p>Box plots are called so because of their shape. They represent the percentile values for the dataset in the form of boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*hBWzHm6T_X0rYSDKuKNfYA.png" /><figcaption>Areas of the box plot as described by SeaBorn.</figcaption></figure><p>Box plot analysis on the very famous iris dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*aAi_kk9063OhsSliAF0kfw.png" /><figcaption>Box plot on the iris dataset.</figcaption></figure><ul><li>The first box plot tells the percentile values of the sepal length feature for three different ranges of iris flowers. 25ᵗʰ, 50ᵗʰ, 75ᵗʰ percentile values for Setosa flower when sepal length is taken as a feature are 4.8, 5, 5.25(approx).</li><li>When petal length is considered as the feature, 25ᵗʰ, 50ᵗʰ, 75ᵗʰ percentile values for Virginica flower are 1.7, 2.0, 2.3(approx). This tells that 25% of Virginica flowers have petal lengths smaller than 1.7. Seeing the plot, we can also say that if petal length &gt; 2 and &lt; 5, then it is Versicolor. If petal length &lt; 2, then it is setosa and otherwise Virginica. At the same time, 25% of the Virginica flowers have petal length &lt; 5, this means if I use the above if-else, then 25% of the Virginical flowers will be labelled wrong.</li></ul><p>This way, we can see percentile values for others as well.</p><p><strong>Whiskers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*ZS--s4BQmhdyDyp7fAXa0g.png" /><figcaption>Box plot with whisker</figcaption></figure><p>There is no standard way to define whiskers. Whisker generally represents the max and min value of the feature.</p><h4>— Violin plots</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*2jERPRD28J9UDL9o0AWZrw.png" /><figcaption>Violing plots on Iris dataset.</figcaption></figure><p>A <a href="https://mode.com/blog/violin-plot-examples">violin plot</a> plays a similar role as a box and whisker plot. These plots shows the probability distribution functions on the sides and box plots inside them. You may notice the curve like boundaries which are actually probability distribution function. It is actually merging the histogram plots and box plots.</p><p>Violin plots typically are more informative as compared to the box plots as violin plots also represent the underlying distribution of the data in addition to the statistical summary.</p><h4>— Wind Ups</h4><p>I hope you may have understood the various concepts illustrated above. All the above concepts are basically required for univariate analysis on any dataset.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d094d8e5a266" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[do YOU know the ensemble]]></title>
            <link>https://medium.com/ai-quest/do-you-know-ensemble-b87cad32c7be?source=rss-dbb9cfaeb49a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b87cad32c7be</guid>
            <category><![CDATA[bagging]]></category>
            <category><![CDATA[cascading-classifiers]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[stacking-vs-cascading]]></category>
            <category><![CDATA[bootstrapping]]></category>
            <dc:creator><![CDATA[Rrohan.Arrora]]></dc:creator>
            <pubDate>Mon, 06 Apr 2020 23:34:20 GMT</pubDate>
            <atom:updated>2020-04-07T09:21:01.756Z</atom:updated>
            <content:encoded><![CDATA[<h4>quick and deep dive into ensembling techniques</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5GUEkv42D_hCA_zHV3zXA.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/spirit1993-354237/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=401845">spirit1993</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=401845">Pixabay</a></figcaption></figure><h3>— What are ensembles</h3><p>Consider a situation where you want to start your company and you are looking for some people highly qualified in their domain. You would definitely want to start your company with highly qualified people so as to deliver satisfactory results. Now, replace those bunch of highly qualified people with various machine learning models.</p><p>Thus, ensembles consist of multiple base models combine together. The more different the models are, the better you can combine them. Ensembles are very powerful and high performing models. They are very useful in the real world.</p><h3>— Various ensembling techniques</h3><ul><li>Bagging or Bootstrap Aggregation</li><li>Boosting</li><li>Stacking Models</li><li>Cascading</li></ul><p>Let us understand various techniques in detail.</p><h3>— Bagging or Bootstrap Aggregation</h3><p>Let us build an intuition behind the bagging technique. Consider a large dataset of points D{xᵢ, yᵢ} consisting of 10k points. Rather than building one whole model on the complete dataset and then using the results, what if we train a large number of models of a subset of data points.</p><p>D{xᵢ, yᵢ}<br>→ Sample m points with replacement →D₁´ →train model on the sample → M₁ →y₁<br>→ Sample m points with replacement →D₂´ →train model on the sample → M₂ →y₂<br>→ Sample m points with replacement →D₃´ →train model on the sample → M₃ →y₃<br>→ Sample m points with replacement →D₄´ →train model on the sample → M₄ →y₄<br>…</p><p>At last, we combine all the M₁, M₂, M₃ …. Mₖ to a big model M.</p><ul><li>D₁´, D₂´, D₃´, D₄´… are known as <strong>Bootstrap samples.</strong></li><li>The process of combining M₁, M₂, M₃ …. Mₖ models to a big model is known as <strong>Aggregation.</strong></li><li>For classification, we use the majority vote technique at the aggregation and mean/medium technique for regression.</li><li>Models Mᵢ´s are build using the same sample size but of different samples. So, we can say that each model has seen a different subset of samples.</li></ul><p>Bootstrapped models are generally high variance and low bias models. So, basically, the whole process of bootstrapping aggregation is to combine low bias and high variance models such that the model that we get at the last stage is low bias and low variance model. Therefore, Bagging can reduce variance in the models without impacting the bias. <em>High variance and low bias models are obtained if the depth of the models is considerably large.</em></p><p>Random Forest is the most used and most popular bagging algorithm. Actually, people thin that RF is the only bagging algorithm but that is not true. Bagging is the technique and Random Forest is built using that technique.</p><h4>Little into Random Forests</h4><p>Random in Random Forests is due to random sampling of points and Forests is due to a large number of Decision trees(DT) that are aggregated to create a large model.</p><p><em>Random Forests=DT(base learners of reasonable depth) + Bagging(row sampling with replacement, RS) + Feature Bagging(column sampling, CS) + aggregation</em></p><p>In the case of random forests, not only rows are sampled but also columns. More is the difference in the datasets in terms of quantity and features, more different your models would be and more accurate the results you would get. It also indicates that if we will remove some unwanted data points from the original dataset, then fewer models would get affected as a small number of models would have those points because of row sampling and column sampling.</p><p>Random Forests do not perform well in case of the high dimensionality of data, categorical variables with many categories.</p><p><strong>Out of bag points</strong></p><p>Let D be the dataset. After RS + CS, let D´ be the set of data points obtained to train the models M´. The rest of the points i.e. D-D´ points are used for cross-validating the model M´and is also known as out of bag points.</p><p><strong>Hyper-parameters in RF</strong></p><p>When we talk of RF, we generally discuss bias-variance trade-off. RF consists of low bias and high variance base learners.</p><p>M = aggregation(M₁, M₂, M₃ …. Mₖ),</p><ul><li>As the number of K increases, variance in the over-all result decreases while the bias of base learners is generally kept the same as of M.</li><li>As the row sampling rate(RSR) and the column sampling rate(CSR) decreases, variance also decreases. But we should not reduce the sampling rates to such an extent that bias of the model increases. <em>We can decide the</em> K <em>parameter through the performance/K graph using the cross-validation dataset.</em></li></ul><p>So, K , RSR and CSR are the major hyper-parameters.</p><h4>Little into Extremely Randomized Trees</h4><p>In case of any feature consisting of real values,</p><ul><li>if you model consists of regular DT´s, then we will sort the values first and then consider each value of the feature as a threshold in order to make decisions. We take the point as a threshold which has maximum information gain or an overall reduction in I𝓰/H. But the point to be noticed is that we consider each and every value of the feature as threshold once.</li><li>In the case of extremely randomized trees, instead of considering every point as a threshold, we randomly selected a few points from the possible values and then carry on the process. In these trees, randomization is a way to reduce the variance.</li></ul><p><em>Extremely Randomized Trees=DT(base learners of reasonable depth) + Bagging(row sampling with replacement, RS) + Feature Bagging(column sampling, CS) + aggregation + randomized </em>“𝜏”</p><h3>— Boosting</h3><p>Boosting is the second ensembling technique.</p><p>Bagging = low bias and high variance base models + randomization + aggregation</p><p>Boosting = high bias and low variance base models + additively combination of models in order to reduce the bias. High bias basically means high training error.</p><blockquote>Consider a situation where you are training a model to predict 12 as output. You first train the model and it predicts 8 as output. Now, you again train the model with some constraints like regularization or more complex architecture and model predicts 10 this time. Now, you will keep on increasing various constraints to the model in order to achieve higher and higher accuracy.</blockquote><blockquote>NOW, consider the same above situation. At first, your model predicted 8 as output. Now, rather than increasing the constraints to the model, what if you train your model on the residual error, in the above case 12–8=4. Now, we will train our model to predict 4 rather than predicting 12. Let us assume the model predicts 3 in the second run. Now, the overall error is 12-(8+3) = 1. We will again train the model to predict 1 in the final pass and hurrah, we get the most accurate results. This is all about the boosting technique. We are additively adding the residual errors of the models to get best of the best results.</blockquote><p>Now, let us understand the above concept in more technical terms, the base of which we have understood above.</p><ul><li><strong>Stage 0</strong></li></ul><p>Let D <strong>ₜᵣₐᵢₙ</strong>{xᵢ, yᵢ}(i=1….n) be the training dataset. M₀(ley y = h₀(x)) be the high bias and low variance model(like shallow decision tree) at stage 0.</p><p>Training data for the model = {xᵢ, yᵢ}</p><p>Error for the above model(y⁰ₑᵣᵣₒᵣ) = yᵢ-h₀(xᵢ)(assuming the simplest loss function)</p><ul><li><strong>Stage 1</strong></li></ul><p>M₁(ley y = h₁(x)) be the high bias and low variance model(like shallow decision tree) at stage 1.</p><p>Training data for the model = {xᵢ, y⁰ₑᵣᵣₒᵣ}</p><p>Error for the above model(y¹ₑᵣᵣₒᵣ) = yᵢ-h₁(xᵢ)</p><p>The model obtained at stage 1= α₀* h₀(xᵢ) + α₁* h₁(xᵢ)</p><ul><li><strong>Stage 2</strong></li></ul><p>M₁(ley y = h₂(x)) be the high bias and low variance model(like shallow decision tree) at stage 2.</p><p>Training data for the model = {xᵢ, yᵢ-(α₀* h₀(xᵢ) + α₁* h₁(xᵢ))} — <em>additive addition of models to find the residual error.</em></p><p>Error for the above model(y²ₑᵣᵣₒᵣ) = yᵢ-h₂(xᵢ)</p><p>The model obtained at stage 2 = α₀* h₀(xᵢ) + α₁* h₁(xᵢ) + α₂* h₂(xᵢ)</p><p>…</p><pre>Now, we can say that model obtained at Kᵗʰ stage is<br><br>k<br>Σ αᵢ * hᵢ(x) = Fₖ₋₁ + αₖ * hₖ(x)<br>i=0</pre><p>Thus, as the training error reduces, bias also reduces.</p><p>Now, assume that we are trying to solve a regression problem and the loss we are considering is the square loss.</p><p>So, low residual error model obtained at stage k = Fₖ(x)</p><p>⇒ residual @ for the stage k+1(eₖ₊₁) = yᵢ-Fₖ(x)</p><p>⇒ Input data for the model at stage k+1 = {xᵢ, eₖ₊₁}</p><p>In terms of square loss, the residual error would be defined as</p><pre>L(yᵢ, Fₖ(x)) = (yᵢ - Fₖ(x))²</pre><pre><strong>∂</strong>(L) / <strong>∂</strong>(Fₖ(x)) = <strong>∂</strong>(yᵢ - Fₖ(x))² / <strong>∂</strong>(Fₖ(x))</pre><pre>= <strong>-1 * 2 * (yᵢ - Fₖ(x))</strong></pre><p>Wow, did you observe anything!!!</p><p>We can write residuals in the form of the loss functions. Our square loss function can be represented in the terms of the residual error obtained at stage k+1. The most important thing to notice is that we can represent any loss function as long as the loss function is differentiable.</p><p>The negative gradient of the loss function(aka residual error) is approximately equal to the residual error.</p><p>Thus, earlier the training data for the model = {xᵢ, yᶦₑᵣᵣₒᵣ}</p><p>Now, the training data could be taken as = {xᵢ, <strong>∂</strong>(L) / <strong>∂</strong>(Fₖ(x))}.</p><p>This whole idea forms the basis of the Gradient Boosting.</p><p>In the case of RF, we cannot minimize hinge loss as we have to minimize the entropy. But for Gradient Boosting, we can minimize any loss as long as the loss function is differentiable.</p><p>Just like we show how the square loss can be represented in terms of residual error, likewise, you can check the pseudo residuals for log loss.</p><p><a href="https://stats.stackexchange.com/a/219405">Gradient for logistic loss function</a></p><h3>This is just so awesome and so powerful!!!</h3><p>If you want to get more insights into the Gradient Boosting algorithm, check the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CR44XOFprKGJOLvyrSS-mQ.png" /><figcaption>Image source — Wikipedia, M in the image is the total number of base learners.</figcaption></figure><p>One extension of GB is GBDT where base learners are either decision stumps or shallow decision trees.</p><p><strong>Regularization and shrinkage parameter</strong></p><p>Now, when we are using GB, one primary concern is to figure out the number of base learners to use. As the number of base learners increases, the variance of the whole model increases and therefore the model starts to overfit. Thus, we need to take care of the number of the models i.e. K . You can predict the value using the cross-validation.</p><p>An important part of the gradient boosting method is regularization by shrinkage which consists of a learning parameter as shown below.</p><p>Model at stage k = Fₖ₋₁ + ν * αₖ * hₖ(x), where parameter ν (0&lt; ν ≤ 1) is called the “learning rate”.</p><p>It has been found that using small learning rates such as ν &lt; 0.1 yields dramatic improvements in the model’s generalization ability over gradient boosting without shrinking(ν = 1).</p><p>⚠️ XgBoost implementation of the GB technique is one of the best implementations. Check out the library below.</p><p><a href="https://xgboost.readthedocs.io/en/latest/python/python_api.html">Python API Reference - xgboost 1.3.0-SNAPSHOT documentation</a></p><h3>— Stacking Models</h3><p>This the third ensemble technique. It is somewhat similar to the bagging technique with few differences. It consists of very different models like SVM, RF, GBDT, KNN, LR, etc.</p><ul><li>In this technique, various models are trained parallelly and independently. Models used in the stacking process are well-trained and perfect models. They have a good bias-variance trade-off.</li><li>The more different are the models, the better the stacking model work.</li><li>Meta-classifier used in the end is also a well-trained model like logistic regression or linear regression.</li></ul><p>Read about the stacking models below:</p><p><a href="http://rasbt.github.io/mlxtend/user_guide/classifier/StackingClassifier/">StackingClassifier</a></p><p>In general, stacking techniques are used in Kaggle competitions where 0.01 difference in accuracy makes a whole lot of differences. In the real world, we do not use these techniques because of its being computationally expensive.</p><h3>— Cascading Models</h3><p>Cascading models are generally used where the cost of making a mistake in very-very high. Like in credit card fraud detection, cancer prediction, etc.</p><p>It generally consists of models in cascade fashion where the later models are trained on data points which are not corrected predicted by the former models based on if-else conditions.</p><p>Input → M₁ (if p(<strong>ŷ) &gt; 0.99</strong>⇒ <strong>ŷ</strong>=0 else) → M₂ (if p(<strong>ŷ) &gt; 0.90 </strong>⇒ <strong>ŷ</strong>=0 else) → M₃ (if p(<strong>ŷ) &gt; 0.95 </strong>⇒ <strong>ŷ</strong>=0 else) M4</p><p>…</p><p>There are many ways to cascade the models based on if-else conditions.</p><h3>Wind-ups</h3><p>That&#39;s all on ensembling techniques. I would suggest the readers explore the ensembling techniques. In general, these techniques are used mainly.</p><h3>References:</h3><ol><li><a href="https://en.wikipedia.org/wiki/Gradient_boosting">https://en.wikipedia.org/wiki/Gradient_boosting</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b87cad32c7be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-quest/do-you-know-ensemble-b87cad32c7be">do YOU know the ensemble</a> was originally published in <a href="https://medium.com/ai-quest">AI n U</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep, Deep Learning Concepts]]></title>
            <link>https://medium.com/ai-quest/convolutional-neural-network-recondite-concepts-e61e1486e206?source=rss-dbb9cfaeb49a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e61e1486e206</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[face-recognition]]></category>
            <category><![CDATA[coursera]]></category>
            <category><![CDATA[inception-networks]]></category>
            <category><![CDATA[1x1-convolution]]></category>
            <dc:creator><![CDATA[Rrohan.Arrora]]></dc:creator>
            <pubDate>Fri, 07 Feb 2020 12:37:07 GMT</pubDate>
            <atom:updated>2020-03-06T16:03:32.925Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep dive into face recognition and 1x1 convolution concepts. Also, I will discuss various optimization algorithms that I learned from Coursera. Let&#39;s start.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmByCfgmm2saW0ATAsg2vA.png" /><figcaption>Image by <a href="https://pixabay.com/users/ahmedgad-9403351/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3501528">Ahmed Gad</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3501528">Pixabay</a></figcaption></figure><p>Before we could understand the face recognition problem, let us understand the face verification concept.</p><h3>— What is face verification?</h3><p>In the face verification problem, we verify if the input face image belongs to the particular name/ID of the person which is also passed as input to the face verification system. In other terms, you can say that it is a 1:1 concept. Generally, in the real world, we could achieve up to 99% accuracy and sometimes a little more in some verification systems.</p><p>Face verification is a concept that is used in face recognition also.</p><h3>— What is face recognition?</h3><p>Face recognition is a broader concept which definitely uses the face verification concept. In this, we recognize the input face image among the bulk of data and outputs the name/ID of the person if the image belongs to anyone of the people in the bulk data. Let us assume that we have a database of 1000 persons and we are using the face verification concept also. For verifying the image, we have accuracy up to 99%. That means that there is only a 1% probability of occurring error for each image while verifying it. Thus, if we could improve our face verification to more accuracy, we could improve the face recognition accuracy as well.</p><p><strong>— What is One-shot learning?<br></strong>One of the problems that we have to face while achieving face recognition is one-shot learning. It is defined as recognizing the face using only 1 image, i.e. we have to learn to recognize the face of the person using only 1 sample image when we don’t have any considerable amount of dataset to learn the model. But after learning this, we could train a convolutional neural network.</p><p>In order to overcome this problem, we compare the features of the two images and find the degree of difference between the images. If the difference between the images is more than the threshold value then we say that the images belong to different persons and to a similar person otherwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/0*VptJZrav5M5cXMfC" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*tC_pfoBoRcoh585Q.png" /></figure><p>So long as you can learn this function d, which inputs a pair of images and<br>tells you, basically, if they’re the same person or different persons. Then if you have someone new join your team, you can add that person to your database, and it just works fine.</p><blockquote><em>In order to learn the difference function as explained above, we use Siamese Networks.</em></blockquote><p><strong>— What are Siamese Networks?<br></strong>Imagine, if we could achieve something in which we could compare the last feature vectors of the convoluted images i.e. the vector obtained before passing it through the softmax function. That encoded feature vector contains the information about the discrete features of the image and if we will compare that vector, then we will certainly be comparing the features of the two input images. This way we could easily tell if the images belong to the same person or not. I hope you imagined properly!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/0*-zEt_8EV6ygrTUPa" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*t2ONHJL93x5O3SFD.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/0*04vo60Oaj74Snprv" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*Df1bS06XkdQsqxo6.png" /></figure><blockquote><em>In order to train the modal and learn the parameters, we need to define the cost function. For face recognition systems, we define a triplet loss function.</em></blockquote><p><strong>— What is the triplet loss function?<br></strong>As the name suggests, we define the loss function containing the three images. The three images are defined below:</p><ul><li>Target image(A) — the image which we are trying to recognize</li><li>Positive image(P) — the image very much similar to the target image</li><li>Negative image(N) — the image different from the target image</li></ul><p>Now, the loss function is defined as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/0*Viag7_tdeqYDmrtw" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3qOZMxZFVcoUE-W3.png" /></figure><p>During training, if A, P, N are chosen randomly, it is easily satisfied. Therefore, choose triplets that are “hard” to train on.</p><p>In order to learn more about the above concept, I would suggest the readers read <a href="https://arxiv.org/abs/1503.03832">this paper</a>.</p><p>Just a little more knowledge!</p><h3>— 1x1 convolution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/0*F3HL6DWBygbfQGTH" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/0*zpGisakYUvnfoSxk.png" /></figure><ul><li>In the above convolution procedure, we multiply the 6x6x1 matrix with the 1x1x1 matrix.</li><li>We are getting the 6x6x1 convoluted output. Since there is only 1 filter being used to evaluate, therefore, we are getting the single channel in the output.</li></ul><p>Let us now evaluate using a 6x6x32 input matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/0*q1VB6nSO11EVCPnM" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*MGEw65tpkA93tUJJ.png" /></figure><ul><li>If we have a 6 by 6 by 32 instead of by 1, then convolution with a 1 by 1 filter makes much more sense.</li><li>The one by one convolution will look at each of the 36 different positions, and it will take the element-wise product between 32 numbers on the left and 32 numbers in the filter.</li><li>At last, it will then apply a ReLU non-linearity to it.</li></ul><p>If there will more than 1 filter, then the output will look something like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/0*vLJyrOdbdWlh9S9M" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*Ee9r_HUm5kUXpbcg.png" /></figure><p>blue lines represent different layers</p><ul><li>#filters correspond to the number of the filters required in the output.</li></ul><p>The above concept is also known as Network in Network and it is best explained in <a href="https://arxiv.org/abs/1312.4400">Network In Network</a> research paper.</p><h3>— Using 1x1 convolutions</h3><ul><li>If you want to shrink the height and width, you can use a pulling layer. But what if we want to shrink the number of channels without affecting the width and height of the image, then 1x1 convolutions helps a lot. Let us understand this using an example.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/0*VIPg9b_ieheVctMN" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/0*s0ShiYVxd-sKiXAy.png" /></figure><ul><li>We have 28x28x192 dimensional volume as the input and we want to decrease the volume to 28x28x32 i.e. keeping the width and height the same and reducing the number of the channels.</li><li>We can achieve this by selecting the 1x1x192 convoluted matrix with 32 channels/filters.</li><li>Thus we will have 28x28x32 dimensional volume in the output with the same width and height but the different number of channels.</li><li>The one by one convolution adds non-linearity to the convolution matrix.</li></ul><p><strong>The above concept of Network in Network has influenced many other network architectures including the Inception networks. In order to learn more about inception networks, read the blog post added in the references section.</strong></p><h3>— What is the Exponentially weighted average?</h3><p>Let us understand this concept using an example.<br>Consider the below graph showing the temperature of London for the whole year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*Tb3iXdwzLCP5vz5ZZSsRXQ.png" /></figure><p>If we analyze the graph, then we have zig-zag values for the temperature which leads to a very irregular graph. Thence, this data looks a little bit noisy and if you want to compute the trends, the local average or a moving average of the temperature would work. In order to compute the moving average or exponentially weighted average, we consider the effect of previous values to a certain extent and add it to the present values like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*6jc6RUZExoO1EdF_8CSzyw.png" /></figure><p>In more generic ways, we could say like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*lbf6oiCoO6CaFn5rOTY1wg.png" /></figure><p>If β = 0.9, then the graph would look like(in red):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*26BSE1r6y04wh0B8tAg3eQ.png" /></figure><p>β=0.9<strong> </strong>means average over the 10 days.</p><p>If β = 0.98, then the graph would look like(in green):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*HX_M452-GFRAUHLSqoaR9Q.png" /></figure><p>β=0.98<strong> </strong>means average over the 50 days.</p><p>If β = 0.5, then the graph would look like(in yellow):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*y317t5iKPOq19vseXUxPCw.png" /></figure><p>β=0.5<strong> </strong>means the average over the 2 days.</p><h4>Bias Correction</h4><p>When we define <strong>β=0.98, </strong>we actually get the below purple curve rather than the green curve,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*cQLKQJc4liuRItUSbRb0lA.png" /></figure><p>If you see the above carefully, the purple curve actually starts very low. This happens because we define V0 = 0.</p><p>Thus,</p><p>V1 = βV0 + (1-β)V1</p><p>⇒ V1 = (1-β)V1</p><p>Which is not a good estimate. In order to handle such a scenario, we add bias term in order to handle this.</p><p>Instead of taking Vt, we calculate Vt/1-β^t.</p><p>This formula gives us more related values.</p><h3>— What is Gradient Descent with Momentum?</h3><ul><li>Let’s say that you’re trying to optimize a cost function that has contours as shown below. So the red dot in the middle denotes the position of the minimum.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*wfn3xs3IPIkSwvN4DJsd5w.png" /></figure><ul><li>You may be doing gradient descent on the whole batch or mini-batch, the process of the gradient descent would look like below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*yAUFEgeE_rB8AsgraOvH7A.png" /></figure><ul><li>This up and down oscillations slow down gradient descent and prevent you from using a much larger learning rate.</li><li>In particular, if you were to use a much larger learning rate, you might end up overshooting and end up diverging like below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*eeBmB5411RVdfioyg_BCqQ.png" /></figure><ul><li>In order to handle the above behaviors, we could use momentum in gradient descent also. With momentum, the algorithm would look like</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*ek0yYo-bsr7tRWi1RpFs7Q.png" /></figure><h3>— What is Gradient Descent with RMSProp?</h3><p>You see above that momentum can really speed up your gradient descent process. There is one more algorithm known as Root Mean Square Prop. Let us understand that.</p><p>RMSProp algorithm is similar in effects as momentum algorithm, just there is a difference of the equations. Please look at the below image to know the algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*w3lqzG5izhoQo5s5lc0qgg.png" /></figure><p>🎶 β used in the RMSProp algorithm is different from the one used in the momentum algorithm. Do not think of them as same.</p><h3>— ADAM Algorithm</h3><p>Adam algorithm is also known as Adaptive momentum estimation. The algorithm uses both the momentum and RMSProp concepts and comes out to be a very efficient algorithm. Please look below to understand the algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBPCt8VO9jg9CCQXqT5JFg.png" /></figure><p>Generally, we consider the values of the variables used in the above algorithm.</p><ul><li><strong>α — needs to be tuned</strong></li><li><strong>β1–0.9</strong></li><li><strong>β2–0.999</strong></li><li><strong>ε — 10^(-8)</strong></li></ul><p><em>I would like to thanks Coursera deeplearning.ai for the above concepts and would suggest the readers go through it. Links are added in the references section.</em></p><h3>— References</h3><ol><li><a href="https://www.coursera.org/learn/convolutional-neural-networks/home/week/4">Coursera</a>(CNN by deeplearning.ai) — **highly recommended**</li><li><a href="https://www.coursera.org/learn/deep-neural-network/home/week/2">Optimization algorithms by Coursera</a> — **highly recommended**</li><li><a href="https://towardsdatascience.com/a-simple-guide-to-the-versions-of-the-inception-network-7fc52b863202">https://towardsdatascience.com/a-simple-guide-to-the-versions-of-the-inception-network-7fc52b863202</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e61e1486e206" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-quest/convolutional-neural-network-recondite-concepts-e61e1486e206">Deep, Deep Learning Concepts</a> was originally published in <a href="https://medium.com/ai-quest">AI n U</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convolutional implementation of the sliding window algorithm]]></title>
            <link>https://medium.com/ai-quest/convolutional-implementation-of-the-sliding-window-algorithm-db93a49f99a0?source=rss-dbb9cfaeb49a------2</link>
            <guid isPermaLink="false">https://medium.com/p/db93a49f99a0</guid>
            <category><![CDATA[coursera]]></category>
            <category><![CDATA[object-localization]]></category>
            <category><![CDATA[sliding-window-algorithm]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Rrohan.Arrora]]></dc:creator>
            <pubDate>Wed, 29 Jan 2020 16:19:02 GMT</pubDate>
            <atom:updated>2020-03-06T16:53:30.145Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dig dive into the Object Detection notion</h4><p>In this article, I will discuss how the sliding window algorithm can be understood using the convolutional algorithm. But before that, let us build the intuition for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSSqvuw566rPUDpYjXaslg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/geralt-9301/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4760281">Gerd Altmann</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4760281">Pixabay</a></figcaption></figure><p>— <strong>Object classification and localization</strong></p><p>Object detection includes the object classification and the object localization concepts in great detail. So, it becomes more evident to understand these concepts. Image classification is a more general concept of classifying the type of image from a bunch of classes. Image classification includes various strategies like traditional neural network or convolutional neural network, etc.</p><p>Image localization is finding the boundaries of the object in the image. You can easily see in the below image a box around the car that states the position of the object in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FpTbS-pDNvhQPO_xAeQXKQ.png" /><figcaption>Image by <a href="https://pixabay.com/users/isakarakus-2336747/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1962813">Isa KARAKUS</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1962813">Pixabay</a></figcaption></figure><p>Now, object detection is simply detecting multiple objects in the image using two above concepts i.e. classification and localization.</p><h4>— Defining the target label y</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*ng0C1s8mSKXbLHQCmwp1Hw.png" /></figure><p>The output y will include the values for the below sections:</p><ol><li>If the image contains an object or not(pc).</li><li>The bounding box coordinates including the center of the image, width of the image and the height of the image(bx, by, bh, bw).</li><li>Class of the object(c1, c2, c3).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*BeT0gUBXahtLT2AOdT20Lg.png" /><figcaption>Defining variable y</figcaption></figure><p>Object localization is also known as landmark detection where we try to detect the presence of the object in the image. Now, we could extract different types of information from the landmark detection like the pose of the person in the image, type of smile of the person, etc.</p><h4>— The sliding windows detection algorithm</h4><p>In object detection problems, we generally have to find all the possible objects in the image like all the cars in the image, all the pedestrians in the image, all the bikes in the image, etc. To achieve this, we use an algorithm known as <strong>Sliding window detection. </strong>Let us understand this algorithm.</p><ul><li>In this algorithm, we choose a grid cell of a specific size. Let us choose the grid cell of size 2x2.</li><li>We pass the above grid cell through the image and convolute the part of the image in the grid cell and predict the output.</li><li>Then we slide the grid cell through stride-2 and then convolute the next part of the image.</li><li>In this way, we go cover the whole image.</li><li>We repeat the same procedure with different grid cells size.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*Mey9Pt8DzXerzaIfkl7oLg.png" /></figure><p>Disadvantages of the sliding window:</p><ul><li>It is computationally expensive(Earlier simple linear classifiers were used which were not as expensive to compute as compared to neural networks.).</li><li>Time-consuming.</li></ul><p>Fortunately, however, this problem of computational cost has a pretty good solution. It can be handled by the <strong><em>convolutional implementation of the sliding window algorithm.</em></strong></p><p>We train our development dataset on the below convolutional neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*JegEc4C777HKwCBtJsUYAw.png" /></figure><p>But in our test dataset, we get the image of size 16x16x3. So, there are two ways:</p><ol><li>Sliding window approach:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*SSRQzwEK4iWa-wKVHYMbKw.png" /></figure><p>We pass through 14x14x3 image size through the above convolutional neural network and then try to predict the class of the object in the image.</p><p>2. Convolutional approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*asfkE3GZDH4L-_dD_XnMzQ.png" /></figure><p>We apply convolutional techniques to the whole image and output a 2x2x4 image. Each 1x1x4 in the output corresponds to one of the sliding windows as shown in different colors above. Moreover, this convolutional replacement of the sliding window protocol is much more economical.</p><p>Let us understand the above concept for the 28x28 image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*6pnTy2UB0NuuSCwRNCsfsQ.png" /></figure><p>Each 1x1x4 block in the output image corresponding to one of the sliding windows in the image as shown above. Now, this algorithm still has one weakness, the position of the bounding boxes is not too accurate.</p><p>This is how the sliding window algorithm is implemented convolutionally.</p><h4><strong>— You Only Look Once(YOLO)</strong></h4><p>“You Only Look Once” (YOLO) is a popular algorithm because it achieves high accuracy while also being able to run in real-time. This algorithm “<strong>only looks once</strong>” at the image in the sense that it requires only one forward propagation pass through the network to make predictions. After non-max suppression, it then outputs recognized objects together with the bounding boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*khs7Ce6eBaaFKXGUwIIEtA.png" /></figure><ul><li>To understand the above algorithm, we take a 100x100 image and place 3x3 grid cells over it.</li><li>We take image classification and localization algorithm &amp; apply that to each of the nine grid cells of this image.</li><li>Now, our labels would include pc, bx, by, bh, bw, c1, c2, c3. Label for upper left grid cell would be</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*qBHPKtgKR1VVujvQ4C4yDQ.png" /><figcaption>? represents don’t care.</figcaption></figure><ul><li>As per the Yolo algorithm, the object is assigned to the grid cell whose midpoint lies in it. Therefore, the first car object is assigned to the 4th grid cell and the second car object is assigned to the 6th grid cell.</li><li>The target output in the above case would be 3x3x8 in correspondence to each grid cell.</li><li>The bounding box for the second car would be:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*GLMX4bfRACBPWiCep47l-A.png" /></figure><p>bx and by would be smaller than 1 as they represent the grid cell where the midpoint of the object lies whereas bh and bw could be larger than 1 as the image could be present in more than 1 grid cell.</p><p><strong>—</strong> <strong>Intersection over union &amp; Non-max suppression</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*sKusXOnjuvENGGkW5kFkJg.png" /></figure><p>In some cases, we get more than 1 bounding box for the object detection. In order to handle this, we apply the non-max suppression algorithm. Befoe understanding the algorithm, let us understand IoU first.</p><p>As per the IoU, we can choose the most accurate bounding box among the other bounding boxes for the same object using IoU algorithm. More generally, IoU is a measure of the overlap between two bounding boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*LBzAnoM1Wkp-Prpm7-8QTw.png" /></figure><ul><li>It is defined as the ratio of the size of the intersection between the bounding boxes to the union between the boxes.</li><li>It is considered accurate if the IoU ratio comes out bigger than 0.5.</li></ul><p>Now, as per the non-max suppression algorithm,</p><ul><li>Pick the box with the largest Output as a prediction i.e. pc value.</li><li>Discard any remaining box using IoU with the box output in the previous step.</li></ul><p><strong>— Anchor boxes</strong></p><p>In some cases, more than one object is assigned to the single grid cell as the mid-point of more objects lies in the same grid cell. In order to handle this problem, we use the concept of the anchor boxes.</p><p>We define certain shapes of the boxes and try to match various objects with different shapes. Now, it is very rare that more than 2 objects have the same anchor box shape and they are assigned to the same grid cell. If this happens, then it is the drawback of YOLO algorithm.</p><p>Due to anchor boxes, our output labels would also change. In the case of two anchor boxes, our output label would be like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*ZHAPyNxB5bY0iT3hxQ5ZPw.png" /></figure><ul><li>Previously, each object in the training image is assigned to the grid cell that contains that object’s midpoint.</li><li>With two anchor boxes, each object in the training image is assigned to the grid cell that contains the object’s midpoint and anchor box for the grid cell with the highest IoU.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*hg9n-aOhg5gysLXo7ae_Pw.png" /></figure><h4>— Wrap up</h4><p>So, this is all about object detection and various terms related to it. There is one more algorithm known as SSD(<strong>Single Shot Detector</strong>). SSD is a more robust recommendation. However, if exactness is not too much of matter but you want to go super quick, YOLO will be the best way to move forward.</p><p>I would suggest the readers explore SSD and YOLO.</p><h3>— References:</h3><p>1. <a href="https://www.coursera.org/learn/convolutional-neural-networks/home/week/3">Object detection by Coursera.</a> **highly recommended**</p><p>2. <a href="https://arxiv.org/abs/1506.02640">You Only Look Once: Unified, Real-Time Object Detection</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db93a49f99a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ai-quest/convolutional-implementation-of-the-sliding-window-algorithm-db93a49f99a0">Convolutional implementation of the sliding window algorithm</a> was originally published in <a href="https://medium.com/ai-quest">AI n U</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Other than GANs]]></title>
            <link>https://medium.com/data-science/gans-or-d0fb38ff8ddb?source=rss-dbb9cfaeb49a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0fb38ff8ddb</guid>
            <category><![CDATA[perceptual-loss]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[feature-loss]]></category>
            <category><![CDATA[gans]]></category>
            <dc:creator><![CDATA[Rrohan.Arrora]]></dc:creator>
            <pubDate>Fri, 22 Nov 2019 21:47:35 GMT</pubDate>
            <atom:updated>2019-12-13T16:55:32.414Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this blog post, I will discuss the alternative to using GANs more precisely. I would suggest the readers read the GANs to understand and compare the strategy explained below. Let us get started.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1jfC_Yb8w557T17K0-rBw.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/geralt-9301/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1991865">Gerd Altmann</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1991865">Pixabay</a></figcaption></figure><p>I hope by now, you all are very well kenned with the concept of GANs. But, still, we cannot achieve much accuracy with the GANs. If you have read my blog on GANs, the below was the output at the last stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*UaT4ct5C1W-jLPQNFvJgiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*OiyyXAs4OemtNpWTjCpQyw.png" /></figure><p>The mid image is what the GAN predicted. Though it is somewhat similar to the targeted one but still not the acceptable one because the eyes of the cat in the predicted image are not bright, the paws of the cat are not clear. These small-small things matter a lot if we start differentiating the cats based on the features.</p><p>We may improve the results to a more extent, but still, the GANs cannot come up with enough clearance of the features because we have not trained the model in that way. GAN does not care about the eyes of the cat, and it does not care about the paws and other things.</p><h4>Can we get rid of the GANs?</h4><p>Fastai has come up with something which provides more better, restoring the power of the images. Now, when we talk of a better model, the first thing that comes up in mind is to improve the loff function. If we could enhance the loss function, then our model will train better and hence, more accurate results. So, our primary purpose is to create a better loss function. Now, we could also come up with more complex architecture design, but then that would undoubtedly be the last option to implement.</p><p>Something that i concern here is explained in <a href="https://arxiv.org/abs/1603.08155">Perceptual Losses for Real-Time Style Transfer and Super-Resolution</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*Oj2CiLsg9pBifRub3qsuCw.png" /><figcaption>Image source — research paper mentioned above</figcaption></figure><ul><li>Image Transformation Net — It is basically the UNet or generator part of the GANs. It produces the output, which is the image predicted.</li><li>The above type of model is known as generative models. In these types of models, we have a downsampling part, which is also known as the encoder and the upsampling part, which is known as the decoder.</li><li>Ŷ is the predicted image. Yc is the target image that we want to come up with.</li><li>Now, we pass the predicted image and the target image through the pre-trained image classification model like ResNet34, VGG-16, etc. These models are pre-trained on a lot of categories of images, and they classify the input images.</li><li>Typically, the output of that would tell you, “Hey, is this generated thing a dog, a cat, an airplane, or whatever.” But in the process of getting to that final classification, it goes through lots of different layers. In this case, they’ve color-coded all the layers with the same grid size and the feature map with the same color. So every time we switch colors, we’re switching grid size. So there’s a stride two convolution, or in VGG’s case, they use max-pool layer.</li><li>Now, what we could do is that rather than comparing the last layers, we could compare the activations of the middle layers and then find the pixel losses between the predicted image layers and the target image layers. If we could do so, then we could direct the middle layers of the model to be more specific and accurate.</li><li>Let us understand this concept of comparing the middle layers with an example.</li></ul><blockquote>The structure of the layers in the output before the max-pooling layer is 216*28*28. this means that we have 216 channels with image size of 28*28. Each channel tells us a different kind of features in the image. Maybe the 100th channel compares the eyeball of the cat image. If we could compare the 100th layer of the predicted image and the target image, then our model would be prepared better for the desired results.</blockquote><ul><li>In our case, the feature map is going to say, “there are eyeballs here (in the target image), but there isn’t in the generated version, so please train more and do a better job. Make better eyeballs.” So that’s the idea. That’s what fastai calls feature losses or Johnson et al. called perceptual losses.</li></ul><p>This is how we could improve the image restoration without using the GANs.</p><p>Let us understand how the loss function in practical. I am using the code from the fastai library.</p><pre>class class <strong>FeatureLoss</strong>(nn.Module):<br>    def __init__(self, m_feat, layer_ids, layer_wgts):<br>        super().__init__()<br>        <strong>self.m_feat</strong> = m_feat<br>        <strong>self.loss_features</strong> = [self.m_feat[i] for i in layer_ids]<br>        <strong>self.hooks</strong> = hook_outputs(self.loss_features, detach=False)<br>        <strong>self.wgts</strong> = layer_wgts</pre><pre>def <strong>make_features</strong>(self, x, clone=False):<br>        <strong>self.m_feat</strong>(x)<br>        <strong>return</strong> [(o.clone() if clone else o) for o in self.hooks.stored]<br>    <br>    def <strong>forward</strong>(self, input, target):<br>        <strong>out_feat</strong> = self.make_features(target, clone=True)<br>        <strong>in_feat</strong> = self.make_features(input)<br>        <strong>self.feat_losses</strong> = [base_loss(input,target)]<br>        <strong>self.feat_losses</strong> += [base_loss(f_in, f_out)*w<br>                             for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]<br>        <strong>self.feat_losses</strong> += [base_loss(gram_matrix(f_in), gram_matrix(f_out))*w**2 * 5e3<br>                             for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]<br>       <strong> self.metrics</strong> = dict(zip(self.metric_names, self.feat_losses))<br>        <strong>return sum(self.feat_losses)</strong><br>    <br>    def __del__(self): self.hooks.remove()(nn.Module):</pre><ul><li>m_feat — is the pre-trained model; in our case, we are using the VGG.</li><li>layer_ids — That’s the list of ids of layers before it changes. So there’s our list of layer numbers just before the max-pooling layers. All of those are ReLU’s, not surprisingly. Those are where we want to grab some features. It’s just a list of ids.</li><li>out_feat — it consists of the list of concerned layers mentioned in the layer_ids in the target image.</li><li>in_feat — it consists of the list of relevant layers specified in the layer_ids in the predicted image.</li><li>self.feat_losses — It is the sum of the loss that happened in the out_feat and in_feat layers and the basic MSE loss between the predicted image and target image as defined in the GANs as well.</li></ul><p>So, this is how we improve the loss function. After training the model for quite a good time, we come up with the below output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*Sa0CJe1_-cC1yfkc4r2Qtw.png" /></figure><p>Now, we predict the image, which is quite similar to the target image. Currently, our predicted cat has more justified features as compared to the target image.</p><p>Notably, this is how we could use something different than GANs. I would suggest the users explore the fastai library more to know more behind the approach, as mentioned above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0fb38ff8ddb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/gans-or-d0fb38ff8ddb">Other than GANs</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[restoration gains with GANs]]></title>
            <link>https://medium.com/data-science/restoration-gains-with-gans-faad910c8b66?source=rss-dbb9cfaeb49a------2</link>
            <guid isPermaLink="false">https://medium.com/p/faad910c8b66</guid>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[image-restoration]]></category>
            <dc:creator><![CDATA[Rrohan.Arrora]]></dc:creator>
            <pubDate>Thu, 21 Nov 2019 20:30:13 GMT</pubDate>
            <atom:updated>2019-11-24T03:45:54.022Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, I will discuss the GANs and how it is used for restoring the images. I will use the fastai library for the practical. I would suggest the readers to explore <a href="https://www.fast.ai/">fastai</a> as well. Let us start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PStRrCrQvbxCbmHH63fk0Q.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/Didgeman-153208/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4459235">Thomas B.</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4459235">Pixabay</a></figcaption></figure><h4>What is Image Restoration?</h4><p>Image restoration is the process of restoring the original image from the distorted one. Image restoration is of various kinds like:</p><ul><li>take a low-resolution image and convert it to the high-resolution image</li><li>convert the black and white image to the coloured image</li><li>restore the broken part of the image</li></ul><p>and many more.</p><p>Let us deal with the first kind of it, i.e. convert the low-resolution image with some unwanted text on the image to the high-resolution clear image. We need a dataset of images to restore, and fastai provides us with the dataset of images. Let us use it.</p><pre>import fastai<br>from fastai.vision import *<br>from fastai.callbacks import *<br>from fastai.vision.gan import *</pre><pre><strong>path</strong> = untar_data(URLs.PETS)<br><strong>path_hr</strong> = path/&#39;images&#39;<br><strong>path_lr</strong> = path/&#39;crappy&#39;</pre><p><strong>path_hr</strong> — PosixPath(‘/root/.fastai/data/oxford-iiit-pet/images’)<br><strong>path_lr</strong> — PosixPath(‘/root/.fastai/data/oxford-iiit-pet/crappy’)</p><p>Now, we need to crappify the images, and we can create any function for distorting the images. Below, I will use a function in which I have distorted the image to low resolution with written text over it. Let us understand it.</p><pre>from fastai.vision import *<br>from PIL import Image, ImageDraw, ImageFont</pre><pre>class crappifier(object):<br>    def __init__(self, path_lr, path_hr):<br>        <strong>self.path_lr</strong> = path_lr<br>        <strong>self.path_hr</strong> = path_hr</pre><pre>def __call__(self, fn, i):<br>        <strong>dest</strong> = self.path_lr/fn.relative_to(self.path_hr)<br>        dest.parent.mkdir(parents=True, exist_ok=True)<br>        <strong>img_open</strong> = PIL.Image.open(fn)<br>        <strong>targ_sz</strong> = resize_to(img_open, 96, use_min=True)<br>        <strong>img</strong> = img.resize(targ_sz,     resample=PIL.Image.BILINEAR).convert(&#39;RGB&#39;)<br>        <strong>w,h</strong> = img.size<br>        <strong>q</strong> = random.randint(10,70)<br>        ImageDraw.<br>          <strong>Draw</strong>(img).<br>          <strong>text</strong>((random.randint(0,w//2),random.randint(0,h//2)), str(q), fill=(255,255,255))</pre><pre><strong><em>img.save(dest, quality=q)</em></strong></pre><ul><li><strong>dest</strong> — we are initialising the destination path for the crappy images to store.</li><li><strong>img_open</strong> — opening the image using the PIL library</li><li><strong>targ_sz</strong> — initialising the size for the crappy image.</li><li><strong>img</strong> — resized image</li><li><strong>w, h</strong> — width and height of the image</li><li><strong>q </strong>— choosing any random number to display over the image</li><li><strong>Draw() — </strong>draws the text over the image.</li><li><strong>text() — </strong>finds the text to be drawn over the image. The first parameter declared the dimensions where we have to place the text. The second parameter is the number that is displayed over the image.</li><li>Finally, we are saving the image to the destination folder with quality q.</li></ul><p>So, this is how we can crappify the images. You can distort the images in any fashion.</p><blockquote>Memorize one thing, anything you do not include in the crappifier() , the model won’t learn to fix that.</blockquote><pre>il = ImageList.from_folder(path_hr)<br>parallel(crappify, il.items)</pre><p>The process to crappify the images can take a while, but fast.ai has a function called parallel. If you pass parallel a function name and a list of things to run that function on, it will run that function on them all in parallel. So, it will save a lot of time.</p><h4>Now let’s pre-train the generator. This is the usual stuff that we do after we have processed the data.</h4><pre><strong>bs,size </strong>= 32, 128<br><strong>arch</strong> = models.resnet34<br><strong>src</strong> = ImageImageList.from_folder(path_lr).split_by_rand_pct(0.1, seed=42)</pre><pre>def get_data(bs,size):<br>    <strong>data</strong> = (src.<strong>label_from_func</strong>(lambda x: path_hr/x.name)<br>               .<strong>transform</strong>(get_transforms(max_zoom=2.), size=size, tfm_y=True)<br>               .<strong>databunch</strong>(bs=bs).normalize(imagenet_stats, do_y=True))<br>    <br><em>    </em><strong>return data</strong></pre><p>Let use the get_data() for the pre-processed dataset of images.</p><pre>data_gen = <strong>get_data</strong>(bs,size)<br>data_gen.<strong>show_batch</strong>(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*GHbdzAAM3VWPSR394tHJ3g.png" /></figure><p>Now, we have created the data bunch, and we have to use this data bunch to create the leaner.</p><p>Here, I would expect the readers to know about the UNets and why do we use them. If you have little or no knowledge about it, please refer <a href="https://medium.com/swlh/resnets-densenets-unets-6bbdbcfdf010">here</a>.</p><p>What we are doing is restoring the image from learning from the original image and restoration is what the UNet performs. We need to pass the UNet, our data. Let us use UNets and build the need for GANs.</p><p>The obtained to us is just the list of images from different folders, normalised and transformed as per the requirement. Now, we are using the ImageNet stats above in the normalise method normalize(imagenet_stats, do_y=True) because we will use the pre-trained model. Now, why will we use the pre-trained model? We want to restore the distorted image. It is always better to train the model using the model who at least knows about the animals(not all but a lot) than to train the model on something which knows nothing about the animals. Moreover, we want to restore the image, i.e. remove the unwanted text from the images that our model should in general.</p><blockquote>A word of advice is that transfer learning helps in almost every kind of computer vision problem.</blockquote><p>Let us declare the parameters.</p><pre>wd = 1e-3<br>y_range = (-3.,3.)<br>loss_gen = MSELossFlat()</pre><pre>def <strong>create_gen_learner</strong>():<br>    return <strong>unet_learner</strong>(<strong>data_gen</strong>,<br>                        <strong>arch</strong>, <strong>wd</strong>=wd,<br>                        <strong>blur</strong>=True,<br>                        <strong>norm_type</strong>=NormType.Weight,<br>                        <strong>self_attention</strong>=True,<br>                        <strong>y_range</strong>=y_range,<br>                        <strong>loss_func</strong>=loss_gen)</pre><pre><strong>learn_gen</strong> = create_gen_learner()</pre><ul><li>wd — the weight decay for the model to describe the regularisation.</li><li>y_range — it is the sigmoid function applied to the activations obtained at the last step. The values are defined for such type of problems.</li><li>loss_gen — defined the loss function. Since we are restoring from the original image, therefore we need to compare the output with the original image and MSE loss works great for it. MSE loss basically finds loss between the two input vectors. In our case, the input is images. So, we need to flatten the images before they could be put into the loss function. MSELossFlat() basically does the same kind of thing.</li><li>If you want to know more about it, learn it <a href="https://docs.fast.ai/vision.models.unet.html#DynamicUnet">here</a>.</li></ul><p>So, we have created the UNet learner using a predefined and pre-trained model, ResNet34. This whole process is known as <strong><em>generative learning,</em></strong> where we are generating the images using the unet learner. This is not the exact definition but more of the broad definition. Let us now fit the model.</p><pre>learn_gen.fit_one_cycle(2, pct_start=0.8)</pre><ul><li>pct_start — stands for the number of iterations in the single epoch, the learning rate would rise and the number of iterations for which the learning rate would decrease. Let us understand it using the above example only.</li></ul><p>Let the number of iterations per epoch = 100<br>Number of iterations for which the learning rate would increase per epoch = (100 * 1) * 0.8 = 80<br>Number of iterations for which the learning rate would decrease = 100–80 = 20</p><p>The above fitting of the model happens with the freezing of the encoder in the UNet part, i.e. ResNet part of the UNet. But, since we are using the transfer learning, so we can unfreeze the pre-trained part of the UNet (<strong>the pre-trained part of a U-Net is the downsampling part.</strong>) That’s where the ResNet is.</p><pre>learn_gen.unfreeze()</pre><pre>learn_gen.fit_one_cycle(3, slice(1e-6,1e-3))</pre><pre><strong>learn_gen.show_results(rows=2)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*NguYNqZjIJ3AqG1jK_NQzA.png" /></figure><ul><li>We have obtained above relatively a good prediction model. Being the fast that our image is not as clear is due to the loss function. We are using the MSE loss that the pixel difference between the obtained image and the actual image is very less. If removing the text is the only task, then we have accomplished our objective. But, we are also working on to improve the image resolution.</li><li>Basically, the model is doing an excellent job in the upsampling but not working fine in downsampling.</li><li>All that we have to improve is the loss function. A better loss function would give us better results. This is what defines the Neural Networks. This establishes the need for the GANs.</li></ul><h3>Generative Adversarial Network</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*teeyztRl5b5qTZXpn39QbA.png" /><figcaption>image source — fastai</figcaption></figure><p>Let us understand the semantics behind the GANs.</p><ul><li>Till now, we have a model which moderately predicts the images that are not so much different from the original images. As per the above image, we have already created the crappy images and also the generator which is generating not such terrible images. We are then using the Pixel MSE to compare the predicted images and Hi-res images.</li><li>Imagine if we could come with something that rather than comparing the pixels between the images, actually classified the predicted image between the hi-resolution image and low-resolution image. And it would even be more interesting if we could fool that binary classifier in a way that it starts classifying the generated images to the high-resolution images.</li><li>Once, we start fooling the classifier, then we will train the classifier more to predict the actual class of the image, i.e. if the image is generated one, then it should predict it correctly, and if the image is the high-resolution image, then it should predict it high-resolution image.</li><li>Once, the classifier trains to predict the class of the predicted image correctly, that means that we cannot fool the classifier any more. In that situation, we will more train the generator so that it could generate images that are more close to the high-res image. Once we train the generator much enough, then we could again fool the classifier.</li><li>Once, we start fooling the classifier again, and we will begin training the classifier more this time. This process of training generator and classifier more and more actually sums up to the GANs.</li><li>So, basically, the loss function in the GANs calls us another model and that model itself has attained state of the art result. All game is to get a better and better loss function.</li></ul><h3>Believe me! This is all GAN.</h3><p>We have already created the generator. Let us now create the classifier. But before we create the classifier, we need to store our predictions somewhere because we need to classify between the predicted images and high-resolution images. So, let us store the predicted images somewhere.</p><pre>name_gen = &#39;image_gen&#39;<br>path_gen = path/name_gen</pre><pre>path_gen.mkdir(exist_ok=True)</pre><ul><li>We have created a path PosixPath(‘/root/.fastai/data/oxford-iiit-pet/image_gen’)] where we want to store the generated images.</li><li>We already have a path PosixPath(‘/root/.fastai/data/oxford-iiit-pet/images’) where we store the high-resolution images.</li></ul><pre>def save_preds(dl):<br>    i=0<br>    names = dl.dataset.items<br>    <br>    for b in dl:<br>        preds = learn_gen.pred_batch(batch=b, reconstruct=True)<br>        for o in preds:<br>            o.save(path_gen/names[i].name)<br>            i += 1</pre><pre>save_preds(data_gen.fix_dl)</pre><ul><li>We have saved the predictions in the folder.</li><li>data_gen.fix_dl will generate the fixed-size data loader.</li><li>Then we iterate over the data loader and extract a particular size of data and pass it to the pred_batch to predict.</li><li>We then store the predicted images to the folder under the image name itself.</li></ul><p>Now, we need to code the classifier. If you need to know more about the classifiers, read <a href="https://medium.com/analytics-vidhya/image-classification-using-fastai-5ff5b374d414">here</a>.</p><pre>def <strong>get_crit_data</strong>(classes, bs, size):<br>    <strong>src</strong> = ImageList.<strong>from_folder</strong>(path, include=classes)<br>                   .<strong>split_by_rand_pct</strong>(0.1, seed=42)<br>    <strong>ll</strong> = src.<strong>label_from_folder</strong>(classes=classes)<br>    <strong>data</strong> = (ll.<strong>transform</strong>(get_transforms(max_zoom=2.), size=size)<br>              .<strong>databunch</strong>(bs=bs).normalize(imagenet_stats))<br>    return <strong>data</strong></pre><pre>data_crit = <strong>get_crit_data</strong>([name_gen, &#39;images&#39;], bs=bs, size=size)</pre><ul><li>from_folder — extract the images from the folder located in path . We want to include the data of only those folders whose name are mentioned in the include=classes .</li><li>label_from_folder — label the images using the classes which are basically the folder names itself.</li><li>Then we transformed the data, created the data bunch and finally normalised the data.</li></ul><pre>data_crit.show_batch(rows=3, ds_type=DatasetType.Train, imgsize=3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*u1DQ8Zyh1L-2eeAaEWNB0A.png" /></figure><p>Let us define the learner for the classifier.</p><pre>loss_critic = AdaptiveLoss(nn.BCEWithLogitsLoss())</pre><pre>def <strong>create_critic_learner</strong>(data, metrics):<br>    return <strong>Learner</strong>(data, gan_critic(), metrics=metrics, loss_func=loss_critic, wd=wd)</pre><pre>learn_critic = <strong>create_critic_learner</strong>(data_crit, accuracy_thresh_expand)</pre><ul><li>if you say gan_critic, fast.ai will give you a binary classifier suitable for GANs.</li><li>Because we have this slightly different architecture and slightly different loss function, we did a slightly different metric. accuracy_thresh_expand is the equivalent GAN version of accuracy for critics.</li><li>Finally, we are calling the create_critic_learner to create the learner for GANs. Fastai data block API is beneficial in creating the learners.</li></ul><pre>learn_critic.fit_one_cycle(6, 1e-3)</pre><ul><li>Now, we have a learner who is pretty much good at differentiating the predicted images from the high-resolution images.</li><li>This is the predicted behaviour also because we already have images well differentiable.</li></ul><p>Now, we have a generator, classifier/critic. Let us move to the last part of the section.</p><h4>Finishing up GAN</h4><pre>learn_crit=None<br>learn_gen=None</pre><pre><strong>data_crit</strong> = <strong>get_crit_data</strong>([&#39;crappy&#39;, &#39;images&#39;], bs=bs, size=size)</pre><pre><strong>learn_crit</strong> = <strong>create_critic_learner</strong>(data_crit, metrics=None).load(&#39;critic-pre2&#39;)</pre><pre><strong>learn_gen</strong> = <strong>create_gen_learner</strong>().load(&#39;gen-pre2&#39;)</pre><ul><li>Now that we have pre-trained the generator and pre-trained the critic, we now need to get it to kind of ping pong between training a little bit of each.</li><li>The amount of time you spend on each of those things and the learning rates you use is still a little bit on the fuzzy side, so fastai provides a GANLearner , you just pass in your generator and your critic (which we&#39;ve just simply loaded here from the ones we just trained) and it will go-ahead</li><li>When you go learn.fit, it will do that for you - it&#39;ll figure out how much time to train generator and then when to switch to training the discriminator/critic, and it&#39;ll go backwards and forwards.</li></ul><pre><strong>switcher</strong> = <strong>partial</strong>(AdaptiveGANSwitcher, critic_thresh=0.65)<br>learn = <strong>GANLearner</strong>.from_learners(<strong>learn_gen</strong>, <br>                                 <strong>learn_crit</strong>, <br>                                 <strong>weights_gen</strong>=(1.,50.),        <br>                                 <strong>show_img</strong>=False, <br>                                 <strong>switcher</strong>=switcher,    <br>                                 <strong>opt_func</strong>=partial(optim.Adam, betas=(0.,0.99)), wd=wd)</pre><pre><strong>learn.callback_fns.append(partial(GANDiscriminativeLR, mult_lr=5.))</strong></pre><ul><li>GANs hate momentum when you’re training them. It doesn’t make sense to train them with momentum because you keep switching between generator and critic, so it’s kind of tough. So this number here (betas=(0.,...)) when you create an Adam optimiser is where the momentum goes, so you should set that to zero.</li><li>Basically, the above-defined hyperparameters generally work for the GAns. You may pretty much use these parameters for every GAN problem.</li></ul><pre>lr = 1e-4<br>learn.fit(40,lr)</pre><ul><li>As the generator gets better, it gets harder for the discriminator (i.e. the critic) and then as the critic gets better, it’s harder for the generator. One of the tough things about training GANs is it’s hard to know how are they doing. The only way to know how are they doing is to actually take a look at the results from time to time.</li><li>If you put show_img=True in the <strong>GANLearner, </strong>then<strong> </strong>It’ll actually print out a sample after every epoch.</li></ul><p>After all this, you may check the results below.</p><pre>learn.show_results(rows=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*4n62XS9HmWvdbiqf3WE0Ug.png" /></figure><p>Finally, You can compare the previous results with the now results. So, that is where GANs come into play.</p><h4>Shortcoming of GANs</h4><p>We are using a critic which is not using any a pre-trained model like ResNet34, rather we are using the gan_critic(). So, we need a pre-trained classifier model that is not only trained on ResNet34 but also compatible with GANs.</p><p>So, that is my take on GANs. Thanks for reading it and keep exploring fastai.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faad910c8b66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/restoration-gains-with-gans-faad910c8b66">restoration gains with GANs</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[ResNets, DenseNets & UNets]]></title>
            <link>https://medium.com/swlh/resnets-densenets-unets-6bbdbcfdf010?source=rss-dbb9cfaeb49a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bbdbcfdf010</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Rrohan.Arrora]]></dc:creator>
            <pubDate>Mon, 11 Nov 2019 05:01:02 GMT</pubDate>
            <atom:updated>2019-11-29T18:53:38.720Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYBQIscoOfGr5jso8iX9Mg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pietrozj?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pietro Jeng</a> on <a href="https://unsplash.com/s/photos/net?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>“ResNets”</h3><p>The most important question is how to train the deep convolutional networks? And quest to answer this question led to the invention of the ResNets. As per the traditional approach to train deeper convolutional neural networks, we increase the number of layers.</p><p>And as per our knowledge on convolutional neural networks, the below should happen — <em>With the increase in the layers, the network should have low training error. </em>But this was what didn’t happen!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFWJlipxw201O2IgNvqs1w.png" /><figcaption>Image source — Deep Residual Learning for Image Recognition Reseach Paper</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*nxkcTumBXCaj8W7LWI51VQ.png" /><figcaption>Image source — Deep Residual Learning for Image Recognition Reseach Paper</figcaption></figure><ul><li>The deeper network is represented in “red,” and the shallow network is described in “yellow.”</li><li>We can easily observe that the deep neural network has more training errors, which we didn’t expect.</li></ul><p>The confusion led Kaiming He and other researchers to publish their <a href="http://openaccess.thecvf.com/content_cvpr_2016/papers/He_Deep_Residual_Learning_CVPR_2016_paper.pdf">research</a>. Let us understand the idea.</p><h4><strong>Deep Residual Learning</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*n6XK73QfQMUhR3NMY2lVDQ.png" /><figcaption>Image source — Deep Residual Learning for Image Recognition Reseach Paper</figcaption></figure><p>As per the above plain neural net, the output H(x) is the combined effect of 2 weight layers and then two non-linear ReLu layers on the input. If we could turn this plain net into some deeper net that sustains the impact of the shallow net with added layers at the same time, then after the operation, the deeper network would at least retain the effect of the process on the shallow network. The same approach led to the phenomenon of the ResNets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*PHV1HqhZ-VO5R82sSArv6g.png" /><figcaption>Image source — Deep Residual Learning for Image Recognition Reseach Paper</figcaption></figure><ul><li>In ResNet, we add a layer which is the addition of the F(x) and x i.e. identity function.</li><li>This helps in solving the problem of dissolving gradient by allowing an alternative path for the gradient to flow through. Also, they use identity function, which allows a higher layer to perform as good as a lower layer, and not worse at least.</li><li>Now, after every two-weight layers and 1 Relu operation, we add to the output of the neural process, the identity. Thus, it would retain at least the effect of 20 layers on a deep 56 layers network in the situation when we start adding the impact of the 20 layer operation on the added 36 layers to the network.</li><li>When the back-propagation is done through identity function, the gradient will be multiplied only by 1. This preserves the input and avoids any loss in the information.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*NAwVigyJxPr5Xu3C6JkgBw.png" /></figure><ul><li>In the image, for any number of added layers to the deep neural network, even after the added layers zero the gradients, the output must retain the affect of the 20 layers neural network because we have added its effect as identity.</li><li>The same type of research happened, and to everyone’s surprise there, the output was better.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*Jq3-geGo-DhBUBWKu6TR2A.png" /></figure><p>In other words, instead of doing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/0*X9MshkKpJuLxswkX" /></figure><p>do</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*HihxHRj6gjKy7RhR" /></figure><p><em>— Identity Connection is also known as Skip connection.</em></p><p>What happened was they won ImageNet that year. They easily won ImageNet that year. ResNet has been revolutionary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*Z04ldHzh9ApjTHI2NQeKMw.png" /><figcaption>Image Source — <a href="https://arxiv.org/abs/1712.09913">Visualizing the Loss Landscape of Neural Nets</a></figcaption></figure><p>In the research paper mentioned in the above image caption, we could easily see the effect of ResNet block on the loses. Without ResNets, the loss surface is so bumpy, and this is the reason that loss got stuck in the valley and could not getter better further. But, on the other hand, if we use ResNet, then the loss graph is much better, and therefore, the loss reaches optimum value.</p><h3>“Dense Nets”</h3><p>Dense Net is the concept that is similar to ResNet, but rather than adding the convolution output with the identity, we concatenate the identity connection to the convolution output. In this way, our input remains in the final output.</p><p>Now, when we are concatenation the identity connection, then the final output that comes out is enormous. This makes dense nets — memory intensive. Thus, dense nets are generally not performed on the deep neural nets. But you definitely, try it on smaller networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*eWyYHFbi-NCJ2ibljYSlIA.png" /></figure><p>DenseNets are very helpful in Image Segmentation where we need to keep track of the previous pixels in the photo to construct the picture further.</p><h3>“U-Nets”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*eu4QDPWJ-UzzO0oOEnmM7Q.png" /><figcaption>Image Source — fastai</figcaption></figure><p>U-Net has two main components:</p><ul><li>Down Sampling</li><li>Up Sampling</li></ul><p>Let us understand the above two concepts using the above image.</p><h4><strong>— Down Sampling</strong></h4><ul><li>U-Net starts with one channel, and their images are 572 by 572.</li><li>They did stride-2 convolution, leading to 128 channels and images of 568 by 568. They lose two pixels for every stride-2 convolution because of a lack of padding.</li><li>Then, they did max-pooling leading to half the size of images, i.e., now the pixels of images are 284*by 284.</li><li>Then again, the first three steps are followed until we get the images of 28 by 28 and 1024 channels.</li><li>This process is known as downsampling.</li></ul><p>This is only one part of the U-Net structure. Let us build an attitude for Upsampling.</p><h4><strong>— Up Sampling</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*ywFuKxsfZgy0P704OSnH4Q.png" /><figcaption>Image source — <a href="https://arxiv.org/pdf/1603.07285.pdf">https://arxiv.org/pdf/1603.07285.pdf</a></figcaption></figure><ul><li>Up Sampling is also known as stride half convolution, deconvolution, or transpose convolution.</li><li>It is creating bigger size images from shorter images.</li><li>There is a beneficial<a href="https://arxiv.org/pdf/1603.07285.pdf"> research paper</a> on this concept.</li><li>You have a 2x2 input, so the blue squares are the 2x2 input</li><li>You add not only 2 pixels of padding all around the outside, but you also add a pixel of padding between every pixel.</li><li>Now if we put this 3x3 kernel here over the enlarged image, you see how the 3x3 kernels are just moving across it in the usual way, you will end up going from a 2x2 output to a 5x5 output.</li><li>If you added one pixel of padding around the outside, you would end up with a 4x4 output.</li></ul><p>This was how people used to do. But this is not an excellent way to do reconstruct larger pixeled images from the low pixeled images. There are many for saying like we are adding a lot of white or black pixels in the image, which would affect the actual pixel of the image, and we may end up with something entirely different from what we expected.</p><p>Nowadays, people are doing upsampling in some other way, which is also known as Nearest Neighbor Interpolation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*17fRPuUtoHZ4lMApUycc9Q.png" /><figcaption>Image source — fastai</figcaption></figure><ul><li>So you can do a nearest-neighbour interpolation, and then a stride one conv, and now you’ve got some computation which is using no zeros in upper left 4x4 like in the previous approach.</li></ul><p>There is one more way, known as <strong>Bilinear Interpolation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*Agjj0GAT-BluJz9AksaK-w.png" /><figcaption>Image source — fastai</figcaption></figure><ul><li>It means instead of copying A to all those different cells, you take a weighted average of the cells around it.</li><li>If you are looking at what should go here (red), it’s about 3 A’s, 2 C’s, 1 D, and 2 B’s, and you take the average.</li></ul><p><em>Anytime you look at a picture on your computer screen and change its size; it’s doing bilinear interpolation.</em></p><p>Now, since we have some prior information about the upsampling, let us now understand what Olaf Ronneberger and others did.</p><ul><li>He used skip connections, as I explained above in ResNets.</li><li>Rather than adding a skip connection that skipped every two convolutions as in the ResNets, they added skip connections where the grey lines are in the above image.</li><li>In other words, they concatenated a skip connection from the same part of the downsampling path to the same-sized bit in the upsampling path. So basically, these are like dense blocks.</li><li>They’ve nearly got the input pixels coming into the computation of these last couple of layers.</li><li>These grey arrows are called cross-connections.</li><li>That’s going to make it super handy for resolving the fine details in these segmentation tasks because you’ve got all of the fine details.</li></ul><p>So that is mine thought on ResNets, DenseNets, and UNets. Moreover, I would like to thank Fastai which helped me in understanding the above concepts. I would also recommend the readers to explore fastai library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bbdbcfdf010" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/resnets-densenets-unets-6bbdbcfdf010">ResNets, DenseNets &amp; UNets</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Steps to basic modern NN model from scratch]]></title>
            <link>https://medium.com/data-science/steps-to-basic-modern-nn-model-from-scratch-1e86b7c042?source=rss-dbb9cfaeb49a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e86b7c042</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[convolutional-neural-net]]></category>
            <category><![CDATA[fastai]]></category>
            <dc:creator><![CDATA[Rrohan.Arrora]]></dc:creator>
            <pubDate>Sat, 09 Nov 2019 19:49:31 GMT</pubDate>
            <atom:updated>2019-12-07T05:49:58.131Z</atom:updated>
            <content:encoded><![CDATA[<h4>The blog will consist of the steps to create a primary neural network, starting from understanding matrix multiplication to building your training loop. Apart from building the neural net, I will discuss various customisation techniques as well.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w03uvoQUwhNKye4HFvdzKg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@skraidantisdrambliukas?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Gertrūda Valasevičiūtė</a> on <a href="https://unsplash.com/s/photos/artificial-intelligence?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Step:1 — MatMul</h3><p>Today, we will learn the first step to building the Neural network, and it is the primary matrix multiplication. There are many ways to do so, and we will see each one and will compare them to get the best results.</p><p>We require matrix multiplication in the linear layer of the Neural Networks. To do matrix multiplication, we need a dataset. Fastai is kind to provide various datasets, and we will use the MNIST dataset to do operations.</p><p>So, let’s grab the dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3ebffd542295e5d50271199e9665139/href">https://medium.com/media/f3ebffd542295e5d50271199e9665139/href</a></iframe><ul><li>Firstly, I am importing the libraries that I will use throughout the series.</li><li>After that, I am downloading the MNIST dataset with the extension .gz provided.</li><li>Since the file downloaded was in pickle format; therefore, I am using the function pickle.load to access the dataset.</li><li>Dataset downloaded is the numpy arrays, and we want PyTorch tensors to perform operations in regards to the Neural Networks. Therefore, I am using map function to map the numpy array to torch tensors.</li><li>Thus, our dataset is ready.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*gIvFg5QtsjTJymRpUoYeVA.png" /><figcaption>Training dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*4RXkUbEwXXZNLam1ns2_mg.png" /><figcaption>Validation dataset</figcaption></figure><pre>weights = torch.randn(784,10)<br>bias = torch.zeros(10)</pre><pre>m1 = x_valid[:5]<br>m2 = weights</pre><pre>m1.shape,m2.shape<strong><br>  = (torch.Size([5, 784]), torch.Size([784, 10]))</strong></pre><h4>Type — 1: Simple Python Programme</h4><p>We can do matrix multiplication using the simple python programs. But python programs take a lot of time to implement and let us see how.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9272392086ff16ff91efb7bc59f1f6ba/href">https://medium.com/media/9272392086ff16ff91efb7bc59f1f6ba/href</a></iframe><pre>%timeit -n 10 t1=matmul(m1, m2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*4S96nuZwYApfTB5Vy6rEdg.png" /><figcaption>847 ms</figcaption></figure><ul><li>847 ms is a lot of time when we have only five rows in the validation dataset.</li></ul><h4>Type — 2: Element wise Operations</h4><p>Pytorch provided us with an effortless way to do matrix multiplications, and it is known as element-wise operations. Let us understand it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e547c95779c4fb9414276ebcec4907c5/href">https://medium.com/media/e547c95779c4fb9414276ebcec4907c5/href</a></iframe><ul><li>We have eliminated the last loop.</li><li>In the element-wise operation, the multiplying units are considered as the Rank-1 tensors.</li></ul><pre>m2[:, 1].shape<br>  <strong>=</strong> <strong>torch.Size([784])</strong></pre><pre>m1[1, :].shape<br>  <strong>=</strong> <strong>torch.Size([784])</strong></pre><ul><li>The above code runs in C. Let us see the time taken by it to execute.</li></ul><pre>%timeit -n 10 t1=matmul(m1, m2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*dAnwZCyTfz8Ud6TC70R0Aw.png" /><figcaption>1.31 ms &lt; 847 ms</figcaption></figure><h4>Type — 3: Broadcasting</h4><p>Broadcasting is another way of matrix multiplication.</p><p>As per the Scipy docs, the term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorising array operations so that looping occurs in C instead of Python. It does this without making needless copies of data and usually leads to efficient algorithm implementations. Broadcasting happens a C speed and with CUDA speed on GPU.</p><pre>m1[2].unsqueeze(1).shape<strong><br>  = torch.Size([784, 1])</strong></pre><ul><li>In broadcasting, the entire column of the input having dimensions as [1 * 784] is squeezed to [784 * 1] and then multiplied with the weights.</li><li>Finally, the sum is taken across the column as sum(dim=0) and is stored in the c .</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2718307c9950ba9cf6f23a7cab9c73ba/href">https://medium.com/media/2718307c9950ba9cf6f23a7cab9c73ba/href</a></iframe><pre>%timeit -n 10 _=matmul(m1, m2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*4-tHXP3qj8i-JbGIKGq1UA.png" /><figcaption>265 us &lt;&lt; 1.31 ms &lt; 847 ms</figcaption></figure><h4>Type — 4: Einstein summation</h4><p>Einstein summation (einsum) is a compact representation for combining products and sums in a general way.</p><p>From the numpy docs:<br>“The subscripts string is a comma-separated list of subscript labels, where each label refers to a dimension of the corresponding operand.”</p><ul><li>It is a more compact representation.</li><li>The number of inputs represents the rank of input ik designates rank-2 tensor, kj designates rank-2 tensor.</li><li>The dimension of a matrix is represented as i*k, k*j and i*j .</li><li>Whenever you see the repeated dimension, do dot product over that dimension.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d87429326c3f5ff86324372d5583b89b/href">https://medium.com/media/d87429326c3f5ff86324372d5583b89b/href</a></iframe><pre>%timeit -n 10 _=matmul(m1, m2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*z7PSf4mcnd-STJSplVRVbQ.png" /><figcaption>39.5 us &lt;&lt;&lt; 265 us &lt;&lt; 1.31 ms &lt; 847 ms</figcaption></figure><h4>Type — 5: PyTorch Operation</h4><p>We can use PyTorch’s function or operator directly for matrix multiplication.</p><pre>%timeit -n 10 t2 = m1.matmul(m2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*t0NoP_D2utdJhlE--oX8Rw.png" /><figcaption>15.5 us &lt; 39.5 us &lt;&lt;&lt; 265 us &lt;&lt; 1.31 ms &lt; 847 ms</figcaption></figure><pre>%timeit -n 10 t2 = m1@m2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*18uad0V6xbCnM7q6XtWTEg.png" /><figcaption>10.9 us &lt; 15.5 us &lt; 39.5 us &lt;&lt;&lt; 265 us &lt;&lt; 1.31 ms &lt; 847 ms</figcaption></figure><p>Thus, we can easily compare the timings of various codes. This is the reason also that we do not prefer to write the code in the Python language due to its slow performance. Therefore, most of the python libraries are implemented in the C.</p><h3>Step:2&amp;3 — Relu/init &amp; Forward pass</h3><p>After we have defined the matrix multiplication strategy, its time to defined the ReLU function and the forward pass for the Neural Network. I would request the readers to go through the Part — 1 of the series to get the background of the data used below.</p><p>The Neural Network is defined as below:</p><pre>output = MSE(Linear(ReLU(Linear(X))))</pre><p><strong>Basic Architecture</strong></p><pre>n,m = x_train.shape<br>c = y_train.max()+1<br><strong>n,m,c</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*kL5DBefdUzZ65W4UXuoVeg.png" /></figure><p>Let us explain the weights for the matrix multiplication.</p><p>I will create a 2-layer neural network.</p><ul><li>The first linear layer will do the matrix multiplication of the input with w1.</li><li>The output of the first linear layer will be the input for the second linear operation, where the input will be multiplied with the w2.</li><li>Instead of getting ten predictions for a single input, I will obtain the single output and will use MSE to calculate the loss.</li><li>Let us declare the weights and biases.</li></ul><pre>w1 = torch.randn(m,nh)<br>b1 = torch.zeros(nh)</pre><pre>w2 = torch.randn(nh,1)<br>b2 = torch.zeros(1)</pre><ul><li>When we declare the weights and biases using the PyTorch randn , then the weights and biases obtained are normalized, i.e. they have a <strong>mean</strong> of 0 and a <strong>standard deviation</strong> of 1.</li><li>We need to normalise the weights and biases so that they do not lead to substantial values after the linear operation with the input to the Neural Network. Because large outputs become difficult for the computers to handle. Therefore, we prefer to normalise the inputs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*ja2ZRiJuW7f6lZM0VrxxbA.png" /></figure><ul><li>For the same reason, we want out input matrix to have a <strong>mean</strong> of 0 and a <strong>standard deviation</strong> of 1, which is not at present. Lets us see.</li></ul><pre>train_mean,train_std = x_train.mean(),x_train.std()<br>train_mean,train_std</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*QLCbFBLvgoWco4qobI2acw.png" /></figure><ul><li>Let us define a function to normalise the input matrix.</li></ul><pre>def normalize(x, m, s): return (x-m)/s</pre><pre>x_train = <strong>normalize</strong>(x_train, train_mean, train_std)<br>x_valid = <strong>normalize</strong>(x_valid, train_mean, train_std)</pre><ul><li>Now, we are normalising the training dataset and the validation dataset on the same mean and standard deviation so that our training and validation dataset has the same feature definitions and scale. Now, let’s recheck the <strong>mean</strong> and <strong>standard deviation</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*cAPB8Sc76ZIjRj7yAWxbfA.png" /><figcaption>Mean approx. to 0 &amp; SD approx. to 1</figcaption></figure><ul><li>Now, we have normalised weights, biases, and input matrix.</li></ul><p>Let us define the <strong>linear layer</strong> for the Neural Network and perform the operation.</p><pre>def lin(x, w, b): return x@w + b</pre><pre>t = lin(x_valid, w1, b1)<br>t.mean(),t.std()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*99U46qF9C334bxh61si5Cw.png" /></figure><p>Now, the mean and standard deviation obtained after the linear operation is again non-normalized. Now, the problem is still pure. If it remains like this, more linear operations will lead to significant and substantial values, which will be challenging to handle. Thus, we want our activations after the linear operation to be normalized as well.</p><h4>Simplified Kaiming Initialization or He Initialization</h4><p>To handle the non-normalized behaviour of linear neural network operation, we define weights to be Kaiming initialized. Though Kaiming Normalization or He initialisation is defined to handle ReLu/Leaky ReLu operation, we still can use it for linear operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*yKzDsaYg8P77yM2wVo3BFg.png" /></figure><p>We divide our weights by math.sqrt(x) where x is the number of rows.</p><p>After the above trivia, we get the normalized mean and SD.</p><pre>def lin(x, w, b): return x@w + b</pre><pre>t = lin(x_valid, w1, b1)<br>t.mean(),t.std()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*d0NYScfDGBTzdZ8ACevHDQ.png" /></figure><p>Let us define the <strong>ReLU</strong> <strong>layer</strong> for the Neural Network and perform the operation. Now, why we are defining the ReLU as a non-linear activation function, I hope you are aware of the <strong><em>Universal Approximation Theorem.</em></strong></p><pre>def relu(x): return x.clamp_min(0.)<br>t = relu(lin(x_valid, w1, b1))</pre><pre>t.mean(),t.std()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*eHIcHpT2bz2a9pisZi14Ww.png" /></figure><pre>t = relu(lin(x_valid, w1, b1))<br>t = relu(lin(t, w2, b2))</pre><pre>t.mean(),t.std()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*paUHCEsbWF4qXyVl9nsgPw.png" /></figure><h4>Did you notice something weird?</h4><p>Notice above that our standard deviation gets halved of the one obtained after the linear operation, and if it gets halved after one layer, imagine after eight layers it will get to 1/2²⁸, which is very very small. And if our neural network has got 10000 layers 😵, forget about it.</p><p>From PyTorch docs: <br>a: the negative slope of the rectifier used after this layer (0 for ReLU by default)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*sKB7utoama8w6L_D-NdbiA.png" /></figure><p>This was introduced in the paper that described the Imagenet-winning approach from Kaiming He and others: <a href="https://arxiv.org/abs/1502.01852">Delving Deep into Rectifiers</a>, which was also the first paper that claimed “super-human performance” on Imagenet (and, most importantly, it introduced ResNets!)</p><p>Thus, following the same strategy, we will multiply our weights with math.sqrt(2/m) .</p><pre>w1 = torch.randn(m,nh)*math.sqrt(2/m)</pre><pre>t = relu(lin(x_valid, w1, b1))<br>t.mean(),t.std()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*hnkkD8Xvgz_mxe_ZHEh-Aw.png" /><figcaption>It is still better than (0.1276, 0.5803).</figcaption></figure><p>Though we have better results, still the mean is not so good. As per the fastai docs, We could handle the mean by the below tweak.</p><pre>def relu(x): return x.clamp_min(0.) - 0.5</pre><pre>w1 = torch.randn(m,nh)*math.sqrt(2./m )<br>t1 = relu(lin(x_valid, w1, b1))<br>t1.mean(),t1.std()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*6J-WYXmxTido8k5BmrU3dA.png" /><figcaption>Now, it is so much better.</figcaption></figure><p>Let us combine the above all code and strategies and create the <strong>forward pass of our Neural Network</strong>. PyTorch has a defined method for Kaiming Normalization i.e kaiming_normal_ .</p><pre>def model(xb):<br>  l1 = lin(xb, w1, b1)<br>  l2 = relu(l1)<br>  l3 = lin(l2, w2, b2)<br>  return l3</pre><pre>%timeit -n 10 _=<strong>model(x_valid)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*G5xwkEAZZhGl5XM9ObEcng.png" /></figure><p>The last to be defined for the forward pass is the <strong>Loss function: MSE.</strong></p><p>As per our previous knowledge, we generally use CrossEntroyLoss as the loss function for single-label classification functions. I will address the same later. For now, I am using MSE to understand the operation.</p><pre>def mse(output, targ): return (output.squeeze(-1) - targ).pow(2).mean()</pre><p>Let us perform the above operations for the training dataset.</p><pre>preds = model(x_train)<br>preds.shape, preds</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*JzuzAnNEJTAZQNMBo5ge9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*6-Ew9x6mCQJIa_0HGMqzuQ.png" /></figure><p>To perform the MSE, we need the floats.</p><pre>y_train,y_valid = y_train.float(),y_valid.float()</pre><pre><strong>mse(preds, y_train)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*I9bVVCwNYYwpCSxOsET2dw.png" /></figure><p>After all of the above operation, one question is still not answered substantially and it is</p><h3>Why do we need Kaiming Initialization?</h3><p>Let us understand it again.</p><p>Initialise two tensors as below.</p><pre>import torch</pre><pre><strong>x</strong> = torch.randn(512)<br><strong>a</strong> = torch.randn(512,512)</pre><p>For Neural Networks, the primary step is the matrix multiplication and if we have a deep neural network with approx 100 layers, then let us see what will the standard deviation and mean of the activations obtained.</p><pre>for i in range(100):<br>    <strong>x = x @ a</strong></pre><pre>x.<strong>mean()</strong>, x.<strong>std()</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*Hl2D8a71ancsIWy2IekS3Q.png" /><figcaption>mean=nan, sd=nan</figcaption></figure><p>We can easily see that mean, and a standard deviation is no longer a number. And it is justified as well. The computer is not able to store that large numbers; it cannot account for such large numbers. It has restricted the practitioners to train such deep neural networks for the same reason.</p><p>The problem you’ll get with that is activation explosion: very soon, your activations will go to nan. We can even ask the loop to break when that first happens:</p><pre>for i in range(100):<br>    <strong>x</strong> = x @ a<br>    if x.std() != x.std(): <strong>break</strong></pre><pre>i</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*qtUj-lwrXLftn7kcKG0pew.png" /><figcaption>Just after 28 loops</figcaption></figure><p>Thus, such problems lead to the invention of Kaiming Initialization. It surely took decades to come up with the idea finally.</p><p>So, that’s how we define the ReLu and backward pass for the neural network.</p><h3>Step:4 — Backward Pass</h3><p>Till now, we have understood the idea behind the matrix multiplication, the ReLu function, and the forward pass of the Neural Network. Now, we will discuss the backward pass.</p><p>Before going into the backward pass, Lets us understand one question.</p><h4>What is backpropagation?</h4><p>This is the fancy term for the deep learning practitioners, especially when you are discussing with someone. But, in simpler terms, backpropagation is just calculating gradients through the chain rule. We find a gradient concerning the weights/parameters. It is this simple. Backpropagation is just the reverse of the gradient of the forward pass.</p><p>So let us find the gradients step by step.</p><p>— <strong>The gradient of the MSE layer</strong></p><p>def mse(output, targ): return (output.squeeze(-1) — targ).pow(2).mean()</p><pre>def <strong>mse_grad</strong>(inp, targ):<br>    <strong># grad of loss with respect to output of previous layer</strong><br>    inp.g = 2. * (inp.squeeze() - targ).unsqueeze(-1) / inp.shape[0]</pre><ul><li>We calculate the gradient of the input layer, which is the output of the previous layer. The gradient of MSE is defined as<br> 2(predicted — target)/mean .</li><li>Since calculating gradients form the chain rule, we need to store the gradients of each layer, which gets multiplied to the previous layer. For this reason, we are saving the gradients in the inp.g input layer because it is the output layer in the prior layer.</li></ul><p>— <strong>The gradient of the ReLU</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*g8dvlB0LpublP8w87aWf-w.png" /></figure><p>Now, for any value greater than 0, we have to replace it with 0, and for values smaller than 0, we have to keep them 0.</p><p>def relu(x): return x.clamp_min(0.)</p><pre>def <strong>relu_grad</strong>(inp, out):<br>    <strong># grad of relu with respect to input activations</strong><br>    inp.g = (inp&gt;0).float() * out.g</pre><ul><li>We are multiplying the gradients of the previous layer which is the output layer for the ReLU i.e. out.g .</li><li>This defines the chain rule.</li></ul><p>— <strong>The gradient of the Linear layer</strong></p><p>I found the gradient of the linear layer more challenging to understand than the other layers. But I will try my best to simplify it.</p><p>def lin(x, w, b): return x@w + b</p><pre>def <strong>lin_grad</strong>(inp, out, w, b):<br>    <strong># grad of matmul with respect to weights</strong><br>    <strong>inp.g</strong> = out.g @ w.t() <br>    <strong>w.g</strong> = (inp.unsqueeze(-1) * out.g.unsqueeze(1)).sum(0)<br>    <strong>b.g</strong> = out.g.sum(0)</pre><ul><li>inp.g — First, we calculate the gradient of the linear layer concerning the parameters.</li><li>w.g — Gradient of weights</li><li>b.g — Gradient of bias concerning the weights.</li></ul><p>Now, let us combine both forward pass and backward pass.</p><pre>def <strong>forward_and_backward</strong>(inp, targ):</pre><pre><strong># forward pass:</strong><br>    <strong>l1</strong> = inp @ w1 + b1<br>    <strong>l2</strong> = relu(l1)<br>    <strong>out</strong> = l2 @ w2 + b2  <br>    <strong># we don&#39;t actually need the loss in backward!</strong><br>    <strong>loss</strong> = mse(out, targ)</pre><pre><strong># backward pass:</strong><br>    <strong>mse_grad</strong>(out, targ)<br>    <strong>lin_grad</strong>(l2, out, w2, b2)<br>    <strong>relu_grad</strong>(l1, l2)<br>    <strong>lin_grad</strong>(inp, l1, w1, b1)</pre><p>forward_and_backward(x_train, y_train)</p><p>What if we compare the gradients we calculated with the gradients calculated by the PyTorch.</p><p>Before comparison, we need to store our gradients.</p><pre><strong>w1g</strong> = w1.g.clone()<br><strong>w2g</strong> = w2.g.clone()<br><strong>b1g</strong> = b1.g.clone()<br><strong>b2g</strong> = b2.g.clone()</pre><p><em>We cheat a little bit and use PyTorch autograd to check our results.</em></p><pre><strong>xt2</strong> = x_train.clone().requires_grad_(True)<br><strong>w12</strong> = w1.clone().requires_grad_(True)<br><strong>w22</strong> = w2.clone().requires_grad_(True)<br><strong>b12</strong> = b1.clone().requires_grad_(True)<br><strong>b22</strong> = b2.clone().requires_grad_(True)</pre><p>Let us define the forward function to calculate the gradients using the PyTorch.</p><pre>def <strong>forward</strong>(inp, targ):<br>    <strong># forward pass:</strong><br>    <strong>l1</strong> = inp @ w12 + b12 <br>    <strong>l2</strong> = relu(l1) <br>    <strong>out</strong> = l2 @ w22 + b22<br>    <strong># we don&#39;t actually need the loss in backward!</strong><br>    <strong>return</strong> mse(out, targ)</pre><pre>loss = forward(xt2, y_train)<br>loss.backward()</pre><p>Let us compare the w2 gradients.</p><pre>w22.grad.T, w2g.T</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*be1k_zP1CJQjYbdVCXBVHQ.png" /><figcaption>They are almost the same.</figcaption></figure><p>Now, there are so many ways in which we can refactor the above-written code, but that is not the concern. We need to understand the semantics behind the backward pass of the Neural Networks. This is how we define backwards pass in our model.</p><h3>Step:4(b) — kaiming Initialization for Convolutional network</h3><p>In the previous part, we looked for the need of <strong>Kaiming Initialization </strong>for stabilising the effects of non-linear activation action. Now, the major for now is to see how kaiming initalization is used for Convolutional Networks. I will also tell you how it is implemented in PyTorch. So let us start the learning journey.</p><h4>Background</h4><p>From the last chapters, we have the below values.</p><pre><strong>x_train.shape, y_train.shape, x_valid.shape, y_valid.shape</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*T7eKUc_e1asCQ9DCw49i-w.png" /></figure><p>Let us look into the shape of the dataset.</p><pre><strong>x_train</strong>[:100].shape, <strong>x_valid</strong>[:100].shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*toTFhZc5Lrk9tO2Sr9EM4Q.png" /></figure><p>From our knowledge of <a href="https://towardsdatascience.com/cnn-resnets-a-more-liberal-understanding-a0143a3ddac9">convolutional networks</a>, Let us create a simple convolutional neural network using PyTorch.</p><pre>import torch.nn as <strong>nn</strong></pre><pre><strong>nh</strong>=32<br><strong>l1</strong> = nn.<strong>Conv2d</strong>(1, nh, 5)</pre><ul><li>The number of input layers to the CNN is 1.</li><li>The number of output filters or layers are 32.</li><li>5 represents the kernel size.</li></ul><p>When we are talking of Kaiming initialization, the first thing that comes to the mind is to calculate the mean and standard deviation of weights of the convolutional neural network.</p><pre>def <strong>stats</strong>(x): return x.mean(),x.std()</pre><p>l1 has defined weights in it. Let’s understand them before calculating the stats.</p><pre>l1.weight.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*jLrtXt-d_nlprYTBZkV49g.png" /></figure><p>As per the weights:</p><ul><li>32 represents the number of output layers/filters.</li><li>1 represents the number of input layers</li><li>5, 5 represents the kernel size.</li></ul><p>We need to focus on the output of the convolutional neural network.</p><pre><strong>x = x_valid[:100] </strong><br># <em>you may train the neural network using the training dataset but for now, I am taking vaidation daaset. There is no specific reason behind it.</em></pre><pre>x.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*71A4AeRd5K5KqNGo6AZvMQ.png" /></figure><ul><li>100 — number of images</li><li>1 — input layer.</li><li>28, 28 — dimensions of the input image.</li></ul><pre><strong>t</strong> = l1(x)<br>t.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*J-c7AP4QgtHd-Tffl-w9sQ.png" /></figure><ul><li>100 — number of images</li><li>32 — number of output layers</li><li>24, 24 — kernel size</li></ul><pre>stats(t)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*5hO-kFjVGeDiUREzvn11FQ.png" /></figure><p>But, we want the standard deviation of 1 instead of 0.6, though we have a mean of 0. So, let us apply kaiming initialization to the weights.</p><pre>init.<strong>kaiming_normal_</strong>(l1.weight, a=1.)<br><strong>stats</strong>(l1(x))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*Ism-zV5-f-RXxBltQRI7ZA.png" /></figure><p>Now, it is better. Mean is almost 0 and SD is around 1.</p><p>But, kaiming initialization was introduced to handle the non-linear activation function. Let us define it.</p><pre>import torch.nn.functional as <strong>F</strong></pre><pre>def f1(x,a=0): return F.<strong>leaky_relu</strong>(l1(x),a)</pre><pre>init.<strong>kaiming_normal_</strong>(l1.weight, a=0)<br><strong>stats</strong>(f1(x))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*m9f21lwkBeKruxHszr2dXQ.png" /></figure><p>— Mean is not around 0, but SD is almost equal to 1.</p><p>Without kaiming initialization, let us find the stats.</p><pre>l1 = nn.<strong>Conv2d</strong>(1, nh, 5)<br>stats(f1(x))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*ljjGJKMNJOY6_8dXU-60kQ.png" /></figure><ul><li>Now, you can easily compare the stats with and without the kaiming.</li><li>With kaiming, results are much better.</li></ul><h3>Compare</h3><p>Now, let us compare our results with the PyTorch. Before that, we need to see the PyTorch code.</p><pre><strong>torch.nn.modules.conv._ConvNd.reset_parameters</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*pOLTrRwvtX46ohPBjN2iSg.png" /></figure><h4>kaiming_uniform</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*3h9TglSNT4ni5j9_rZRGaw.png" /></figure><h4>calculate_correct_fan</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*ao3KoMwV4-GEHuG1ff4iHQ.png" /></figure><h4>calculate_fan_in_fan_out</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*PjpeIv59LM_bsSoOIMa1hw.png" /></figure><p>Let us understand the above methods.</p><ul><li>PyTorch uses kaiming_uniform instead of kaiming_normal. The kaiming_uniform is different from the later in terms of the value boundaries.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*c1o2VK-0g4OHdo6XlU8A8A.png" /></figure><ul><li>There is a variable receptive_field_size in calculate_fan_in_fan_out(). It is calculated as below.</li></ul><pre>l1.weight.shape<br> <strong> = torch.Size([32, 1, 5, 5])</strong></pre><pre>l1.weight[0,0].<strong>shape<br>  = torch.Size([5, 5])</strong></pre><pre>rec_fs = <strong>l1.weight[0,0].numel()</strong><br><strong>rec_fs</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*0eW1FyWLJtcN_3o-sGv5Sw.png" /></figure><ul><li>fan_in(number of input parameters) and fan_out(number of output filters) are calculated as below.</li></ul><pre>nf,ni,*_ = <strong>l1.weight.shape</strong><br>nf,ni</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*lX_vBw2UVG67qmgMYHYdqQ.png" /><figcaption>32 is output filters/layers, 1 is the input layer</figcaption></figure><pre><strong>fan_in</strong>  = ni*rec_fs<br><strong>fan_out</strong> = nf*rec_fs</pre><pre>fan_in,fan_out</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*8w5Z24Q8f2mHa7yf_un4LQ.png" /></figure><ul><li>There is one more parameter gain in kaiming_uniform(). It is the amount of leakiness in the non-linear activation function. It is defined as below.</li></ul><pre>def <strong>gain</strong>(a): return math.sqrt(2.0 / (1 + a**2))</pre><ul><li>For ReLU, the value of a is 0. Therefore, the value of gain for ReLU is math.sqrt(2.0). Look into the below link.</li></ul><p><a href="https://github.com/pytorch/pytorch/blob/fd4f22e4eaae17b8ee8c7de8b0b2b0e202fdf147/torch/nn/init.py#L60">pytorch/pytorch</a></p><p>From all the above knowledge, we can create our kaiming_uniform as below.</p><pre>def <strong>kaiming2</strong>(x,a, use_fan_out=False):<br>    <strong>nf,ni</strong>,*_ = x.shape<br>    <strong>rec_fs</strong> = x[0,0].shape.numel()<br>    <strong>fan</strong> = nf*rec_fs if use_fan_out else ni*rec_fs<br>    <strong>std</strong> = gain(a) / math.sqrt(fan)<br>    <strong>bound</strong> = math.sqrt(3.) * std<br>    <strong>x.data.uniform_</strong>(-bound,bound)</pre><p>Let us calculate the stats.</p><pre><strong>kaiming2</strong>(l1.weight, a=0);<br><strong>stats</strong>(f1(x))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*ZZc2jaQDkIKrj1vYPlh8xA.png" /></figure><p>The results are still better.</p><p>So, this is how kaiming concept is used in the Convolutional Neural Networks.</p><h3>Step:5 — Training Loop</h3><p>Now, we have reached to the point where we need to know about the CrossEntropy loss because mainly CrossEntropy loss is used in single or multi-classification problems. Since we are using MNIST dataset, then we need to create a neural network which will predict for ten numbers, i.e. from 0 to 9. Earlier, we used the MSE loss and predicted the single outcome, which we generally do not do.</p><p>So before learning the loss function deeply, let us create a neural network using PyTorch nn.module.</p><pre>from torch import nn<br>class <strong>Model</strong>(<strong>nn</strong>.Module):<br>    def __init__(self, n_in, nh, n_out):<br>        super().__init__()<br>        <strong>self.layers</strong> = [nn.<strong>Linear</strong>(n_in,nh), nn.<strong>ReLU</strong>(),      nn.<strong>Linear</strong>(nh,n_out)]<br>    <br>    def __call__(self, x):<br>        for l in self.layers: x = <strong>l(x)</strong><br>            return <strong>x</strong></pre><p>We have below-defined variables.</p><pre><strong>n,m</strong> = x_train.shape<br><strong>c</strong> = y_train.max()+1<br><strong>nh</strong> = 50</pre><p>Let us defined the weights again.</p><pre><strong>w1</strong> = torch.randn(m,nh)/math.sqrt(m)<br><strong>b1</strong> = torch.zeros(nh)<br><strong>w2</strong> = torch.randn(nh,10)/math.sqrt(nh)<br><strong>b2</strong> = torch.zeros(10)</pre><p>You may observe the differences in the weight initialization. This time, we want ten predictions, one for each number in the output. That is why I initialized w2 to be (nh, 10).</p><pre>model = Model(m, nh, 10)<br>pred = model(x_train)</pre><pre><strong>pred.shape</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*STH0olKwekRnCk111tutVA.png" /></figure><h4>— Cross entropy loss</h4><p>Again, before indulging into the Cross-Entropy loss, we need to take softmax of our predictions or activations. We do softmax in the case; we want single-label classification. In practice, we will need the log of the softmax when we calculate the loss because it helps further in calculating the cross-entropy loss.</p><p>Softmax is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*hx7CCdDij0C_0S6erfhSgQ.png" /></figure><p>or more concisely:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Z4G2ivzdgNABX0J8iST-5A.png" /></figure><pre>def log_softmax(x): return (x.exp()/(x.exp().sum(-1,keepdim=True))).log()</pre><ul><li>x.exp().sum(-1,keepdim=True) will sum the exponentials of the activations along the row.</li><li>If keepdim is True, the output tensor is of the same size as input except in the dimension dim where it is of size 1. Otherwise, dim is squeezed, resulting in the output tensor having one fewer dimension than input.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*fZGS08W6jb8bicFx_ppiYA.png" /><figcaption>Dimensions are squeezed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*hUcPoKbUS1SX2afVVshyTw.png" /></figure><p>Since we have defined the log_softmax , let us take the log_softmax of our predictions.</p><pre>sm_pred = log_softmax(pred)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*tf-k60d7C0imb-H8kKVnIQ.png" /></figure><p>The cross-entropy loss is defined as below:</p><pre><strong>def</strong> CrossEntropy(yHat, y):<br>    <strong>if</strong> y == 1:<br>      <strong>return</strong> -log(yHat)<br>    <strong>else</strong>:<br>      <strong>return</strong> -log(1 - yHat)</pre><p>In binary classification, where the number of classes M equals 2, cross-entropy can be calculated as:</p><pre>−(<em>𝑦</em>log(<em>𝑝</em>)+(1−<em>𝑦</em>)log(1−<em>𝑝</em>))</pre><p>If M&gt;2 (i.e. multiclass classification), we calculate a separate loss for each class label per observation and sum the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*rzD3og2DLsu5U3tQCm26sg.png" /></figure><p>Our problem is multiclass classification, so our cross-entropy loss function would be later one. The cross-entropy loss function for multiclass classification can also be done using numpy-style <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#integer-array-indexing">integer array indexing</a>. Let us implement using it.</p><pre>def <strong>nll</strong>(input, target): return -input[range(target.shape[0]), target].mean()<br><strong>loss</strong> = nll(sm_pred, y_train)</pre><p>Note that the formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*x46kfXI63OH5WTkF5Lalnw.png" /></figure><p>gives a simplification when we compute the log softmax, which was previously defined as (x.exp()/(x.exp().sum(-1,keepdim=True))).log() .</p><pre>def <strong>log_softmax</strong>(x): return x - x.exp().sum(-1,keepdim=True).log()<br><strong>loss</strong> = <strong>nll</strong>(log_softmax(pred), y_train)</pre><p>Then, there is a way to compute the log of the sum of exponentials in a more stable way, called the <a href="https://en.wikipedia.org/wiki/LogSumExp">LogSumExp trick</a>. The idea is to use the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*_mIm3TmXIFHQGBsW6WUeeg.png" /><figcaption>where a is the maximum of the <em>𝑥𝑗</em>.</figcaption></figure><ul><li>Take out the maximum value from the predictions.</li><li>Subtract the maximum value from the exponential of the predictions.</li><li>At last, add the maximum value to the log of the operation, as suggested in the above image.</li><li>It helps in the computation and makes it faster without affecting the output in either case.</li></ul><p>Let us define our LogSumExp.</p><pre><strong>m</strong> = <strong>pred</strong>.max(-1)[0]<br>m[:,None]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*kQn3gy58NSEvJpuhyf9psQ.png" /></figure><pre>def <strong>logsumexp</strong>(x):<br>    m = x.max(-1)[0]<br>    return m + (x-m[:,None]).exp().sum(-1).log()</pre><p><em>So</em> we can use it for our log_softmax function.</p><pre>def <strong>log_softmax</strong>(x): return x - x.<strong>logsumexp</strong>(-1,keepdim=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*hquoDrZKxFemXihOB-sQMQ.png" /></figure><p>Let us see the above implementation in PyTorch.</p><pre>import torch.nn.functional as F<br>F.<strong>nll_loss</strong>(F.<strong>log_softmax</strong>(pred, -1), y_train)</pre><blockquote>In PyTorch, F.log_softmax and F.nll_loss are combined in one optimized function, F.cross_entropy.</blockquote><h4>— Basic training loop</h4><p>The training loop repeats over the following steps:</p><ul><li>get the output of the model on a batch of inputs</li><li>compare the output to the labels we have and compute a loss</li><li>calculate the gradients of the loss with respect to every parameter of the model</li><li>update the parameters/weights with those gradients to make them a little bit better.</li><li>repeat the above steps at loop known as epochs .</li></ul><p>Let us combine all the above concepts and create our loop.</p><pre>bs = 64<br>lr = 0.5   # learning rate<br>epochs = 1 # how many epochs to train for</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e96b62fcc6478d08a37050a4d7327ae/href">https://medium.com/media/5e96b62fcc6478d08a37050a4d7327ae/href</a></iframe><p>So, this is how we define the training loop in the neural loop. Now, in PyTorch, it has some syntax differences which you can understand now. I will add more steps to this series with time. Till then, feel free to explore fastai.</p><h4>References</h4><ul><li><a href="https://www.fast.ai/">fast.ai</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e86b7c042" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/steps-to-basic-modern-nn-model-from-scratch-1e86b7c042">Steps to basic modern NN model from scratch</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>
    </channel>
</rss>