<?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 Akash Shastri on Medium]]></title>
        <description><![CDATA[Stories by Akash Shastri on Medium]]></description>
        <link>https://medium.com/@akashgshastri?source=rss-567a94bbd3d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4LA8cqy9xQGi0R09cYyLRA.jpeg</url>
            <title>Stories by Akash Shastri on Medium</title>
            <link>https://medium.com/@akashgshastri?source=rss-567a94bbd3d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:24:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akashgshastri/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[When your idols come crashing down]]></title>
            <link>https://akashgshastri.medium.com/when-your-idols-come-crashing-down-d188c835e213?source=rss-567a94bbd3d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d188c835e213</guid>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[heartbreak]]></category>
            <category><![CDATA[parenting]]></category>
            <category><![CDATA[relationships]]></category>
            <category><![CDATA[family]]></category>
            <dc:creator><![CDATA[Akash Shastri]]></dc:creator>
            <pubDate>Wed, 08 Sep 2021 19:44:21 GMT</pubDate>
            <atom:updated>2021-09-08T19:44:21.999Z</atom:updated>
            <content:encoded><![CDATA[<h4>A story about my relationship with my father</h4><h3>Gaslighting</h3><p>When I was 5, I remember thinking my father was the coolest, smartest person who could do anything he wanted. My father was a morally sound man, did not want to cheat people, believed in honesty and not harming others. But he also had his fair share of issues, he was an alcoholic and was possibly depressed.</p><p>I didn’t get to spend a lot of time with my father, he was never emotionally available. He never had time to go out on family outings. Whenever I went out, be it shopping, eating, or travel, I always went with my mother. I distinctly remember this one weekend afternoon, I couldn’t have been any older than 12. We had planned to go out <strong><em>as a family</em></strong> (this phrase will forever haunt me). My father, cancelled last minute, and I was distraught. After looking forward to spending time with both parents for a long time, all my anticipation was in vain. I began sobbing and, as any kid who didn’t get their way would do, started throwing a tantrum. I cried and begged him to join, but to no avail.</p><p>After I’d been sobbing for a while, my father told me I have the innate ability to disappoint myself, and it was my fault I was upset. This happened multiple times, we would plan to go out, he would cancel, I would be disappointed and he would point out that I <strong><em>“ have the ability ”</em></strong> to make myself sad.</p><p>I believed this for the longest time. I thought I was the one making myself sad, and it wasn’t his fault.</p><h3>Broken promises</h3><p>I did not recognize the gaslighting till a few days ago (I’m now 24), when my aunt mentioned how my father had promised to take my mother to Switzerland for her 50th birthday (she’s 49, turns 50 this November).</p><p>Now you might be wondering why this redemption story is under a subtitle called broken promises. And I would argue that this is barely redemption for all the time he missed, or it would have been had he not killed himself when I was 19.</p><p>Now it&#39;s not entirely accurate to characterise his death as suicide. He died of complications from a damaged liver, the result of his years of alcohol abuse. Now we could argue all day if that was his fault or not. I could argue that he chose to drink himself to his grave instead of spending time with his family, but one could also argue that his alcoholism was a symptom of depression and he was a victim. I would be willing to give him a pass, had it not been for the following chain of events.</p><h4>His death…</h4><p>How did my father die? It wasn’t overnight. The first indicator of his poor health was back when I was in high school, maybe 15 or 16. There were concerns about his health, so my mother took him to multiple specialists and therapists, to attempt to solve both the liver issue, and potentially the underlying mental issue. My father was an adamant, egotistical, intelligent man. He did a little of his own reading, and the doctors could no longer convince him he had a mental issue ( I feel disgusted that I was impressed by his “Intelligence”. More on that later). And my father went on drinking much to my mother&#39;s dismay. With great mental and emotional strength, my mother unilaterally decided to have my father forcefully committed to a rehab facility.</p><p>I cannot tell you how destroyed I was watching the man I looked up to all my life getting carried away by clinicians of the rehab facility, but I stood with my mother’s decision, and still do to this day. This should have been my first clue that he was not the man I thought him to be.</p><p>My father being the arrogant man was unfazed by the rehab. After spending a couple of months there (during which he was sober), he came back home and immediately started drinking in protest. He was angry about being committed against his will.</p><p>About 2 years after, I remember I was sleeping in my parent&#39;s room with my father, and my mother was sleeping in my room. This was the arrangement as my father complained about my mother’s snoring, and she did not see it as a problem. It was early in the morning, about 6.30. My father was awake, and watching TV. I was sleeping, but aware that he was up and aware that the TV was on. I heard a violent shaking and looked up to see my father having a seizure.</p><p>We immediately called an ambulance and took him to the hospital. His liver was severely damaged, and we had to be extremely careful and take every measure to keep him alive. He couldn’t smoke in the hospital (oh did I tell you he was a smoker too?), so he had severe withdrawal symptoms from nicotine, and as a result, was constantly annoyed, and annoying everyone around him. He was weak, incapable of logic and was basically a toddler throwing tantrums. One day, when it was my turn to spend the night at the hospital with him, I heard him calling out for me from the bathroom. I went in to see my father without pants, on the floor incapable of getting himself to stand up. My idol was literally crumbling in front of my eyes, and yet I could not help but <strong>NOT</strong> feel sympathy. I was angry, he had treated my mother, my family and me wrong. I helped him up and walked him back to bed.</p><p>Remarkably this was not the end, he somehow recovered a little and was discharged from the hospital. To his credit, he did listen to our (me, mother and other members of our family) advice and quit drinking, and I do commend him for at least trying (handing out consolation prizes).</p><h4>His Ego…</h4><p>But Alas! this last effort of quitting drinking would be undone by his own ego. I was sitting outside my hostel in college, talking on the phone to my dad. And he was telling me how he was not going to take his meds because of some argument he had with my mom. I don’t remember what the argument was, but I wasn’t emotionally mature enough, to tell the man I looked up to my whole life, to stop being a BITCH. So instead, I tried my best attempt at conflict resolution but was unsuccessful. A week later he passed away.</p><h4>Back to the promise</h4><p>Now he had a chance at redemption, promised my mother one trip that was more than 20 years overdue, and fell short one more time, just to disappoint one more time.</p><h3>Why am I writing this?</h3><p>Honestly, I don’t know. When I heard the story about the promised trip from my aunt, my heart broke. I could not contain my emotions, I was so severely heartbroken that I sobbed thinking about the broken promise, and that led me to think of what a shitty father he was, never giving us time. Even now I could not write this without crying my eyes out. I simply do not have the tools required to handle these emotions yet.</p><p>But I can learn things. I idealised my father because I thought he was smart, smarter than everyone, smarter than my mom. This was enforced by everyone that knew him lauding his smarts. It was also reinforced by my childhood conditioning. Coming from a scholarly family, I was told intelligence was the paramount trait, and I believed it. This led me to idolise my father. His emotional unavailability also made his attention a scarce valuable commodity to me, and I did everything in my power to get him to pay attention to me, recognize me, hopefully, spend time with me.</p><p>My mother on the other hand was always there for me, supported me emotionally, financially and morally. She taught me what was right, what was wrong. She helped me study, she fed me, she even occasionally took me to my cricket and swimming classes (which my father never did!). And I took her attention for granted. I, <strong>very wrongly</strong>, did not value her attention and opinion.</p><blockquote><strong>I realised I had been idolising the wrong parent.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d188c835e213" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 neural network architectures you need to know for NLP!]]></title>
            <link>https://medium.com/data-science/3-neural-network-architectures-you-need-to-know-for-nlp-5660f11281be?source=rss-567a94bbd3d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5660f11281be</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Akash Shastri]]></dc:creator>
            <pubDate>Wed, 25 Nov 2020 00:52:02 GMT</pubDate>
            <atom:updated>2020-11-25T00:52:02.688Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this article, I will discuss what I think are the three most important architectures to be aware of for NLP.</h4><h3>Recurrent Neural Network</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0JSn8gH7bCKLA7WI-pUqw.png" /><figcaption>Recurrent Neural Network (RNN). Image from <a href="https://en.wikipedia.org/wiki/Recurrent_neural_network#/media/File:Recurrent_neural_network_unfold.svg">Wikipedia</a> under <a href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a> License.</figcaption></figure><p>Recurrent neural networks are special architectures that take into account temporal information. The hidden state of an RNN at time t takes in information from both the input at time t and activations from hidden units at time t-1, to calculate outputs for time t. This can be seen in the image above. This gives the RNN memory, or the ability to remember previous inputs and their outputs.</p><p>This is extremely important for Natural language processing, as in NLP the input data does not have a fixed size, and the next word is highly dependent on previous words. Context is very important in NLP. The size of each sentence varies, and the output of each sentence varies too. Hence the ability to take variable input sizes and compute outputs of variable size is highly beneficial, and RNNs are capable of this. RNNs also have memory and can remember contextual information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kje9TpsSvMGeBF6vIv6k5Q.jpeg" /><figcaption>The many relations of RNNs. Image from <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/">Andrej Karpathy’s Blog</a>.</figcaption></figure><p>RNN architectures can facilitate multiple types of input and output shapes.</p><ul><li>A one to one architecture can be used for predicting the next word in a sentence for example, where the input is the current word and the next word is the output, and both input and output are 1 word long. When the word predictor is chained multiple times, we can generate sentences and even text, and this is called a language model.</li><li>An example of one input to many outputs can be image captioning. For a single image, if we want to generate a sentence caption, this requires a one to many model.</li><li>If we want to predict the sentiment of a sentence or a review, then we can use a many to one model. We can pass the many words of our review as input and get one output (sentiment: positive or negative).</li><li>Many to many models can be used for machine translation. If we have a sentence in English and want to convert it to a sentence in Kannada (my mother tongue from Karnataka, India), we want multiple words in English to be converted to multiple words in Kannada, however, the number of words might not be the same or in the same order.</li></ul><h3>Long short term memory network (LSTM)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7bEceNfH6X_N75HA9kyoA.png" /><figcaption>LSTM architecture. Image from <a href="https://en.wikipedia.org/wiki/Long_short-term_memory#/media/File:LSTM_cell.svg">Wikipedia</a> under <a href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a> License.</figcaption></figure><p>LSTM was first introduced by Hochreiter et al. in their paper “LONG SHORT-TERM MEMORY” in 1997. You can read the original paper <a href="https://www.bioinf.jku.at/publications/older/2604.pdf">here</a>. The original paper’s architecture was different from what is popular today, and after many iterations (which you can read <a href="https://en.wikipedia.org/wiki/Long_short-term_memory#History">here</a>), we got the version that is popular today.</p><h4>Fall of the RNN</h4><p>But why did we need this complicated architecture? Why were RNNs not enough?</p><p>RNNs had one glaring downside that made it nearly impossible to train larger versions, they were extremely prone to Gradient explosion and vanishing problems. I have discussed this issue in other articles (<a href="https://towardsdatascience.com/all-ways-to-initialize-your-neural-network-16a585574b52">here</a>), and you can find other resources for this problem. But very briefly, the exploding and vanishing gradient problem is caused by repeated multiplications (In our case, multiplication of the input and weight-matrix). Numbers just greater than 1 explode to infinity when multiplied by themselves, and numbers smaller than 1 vanish to zero when multiplied by themselves (you can test this by calculating 1.01¹⁰⁰ in python).</p><p>In an RNN, the same weight matrix is being multiplied with inputs and previous outputs, and hence the gradients explode and vanish. Also, the path for gradient flow is very long from the last iteration of the RNN to the first. This means the amount of contextual information the RNN can maintain in memory before gradients explode or vanish, is small. Hence the memory of vanilla RNNs is low, and the size of the reference window (the number of words before the current word, from which RNNs can draw contextual information ) is small.</p><h4>Rise of LSTM</h4><p>LSTM addresses the issues of the RNN. It does this by maintaining a cell state, which is the state at any given time. This cell state is updated with relevant information at each time step. The output at each time step is derived both from the input, the previous output and the updated cell state.</p><p>The cell state is updated using 3 gates, the input gate, forget gate and candidate gate (also sometimes called gate gate). The output is calculated with the input passed through the output gate and the updated cell state. Each gate is simply either a sigmoid or tanh of input and previous output, followed by either a product or sum. The gates and their processes have been explained too many times, so I will not reinvent the wheel here. But if you want an amazing resource, you can find it <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">here</a>. Also, I will be happy to help clarify doubts in the comment section.</p><p>The main advantage of using a cell state is that the cell state can be maintained and updated with minimal computation and processing, and the cell state creates a gradient highway for gradients to backpropagate, hence avoiding the vanishing and exploding gradient problem.</p><h3>Transformer Network</h3><p>RNNs had the issue of vanishing and exploding gradients, so memory was severely short term. Think of it this way, the more vanilla RNNs you stacked, the more likely the gradients exploded or vanished and outputs did not get better. This means the long term memory of RNNs was very small.</p><p>With the introduction of LSTMs and their ability to remember cell state, this improved long term memory, however, it was still limited. Also, LSTMs had to be fed input data sequentially as they needed outputs from the previous time step to calculate current outputs. This did not make full use of modern GPUs. Also, LSTMs were significantly slower than RNNs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*8bHO7EMfrCp_fhkRNFygkg.png" /><figcaption>Transformer architecture. Image from the <a href="https://arxiv.org/abs/1706.03762">original paper</a>.</figcaption></figure><p>The Transformer Network was introduced to address these issues. It was introduced in 2017 by Ashish Vaswani et al. in their paper “Attention Is All You Need” which you can read <a href="https://arxiv.org/abs/1706.03762">here</a>. They used an encoder-decoder network similar to RNNs, with a key difference. They introduced attention blocks.</p><p>Attention blocks calculated how each word in the input relates to other words in the input. The higher the value, the more attention is paid to those words, and the more dependent the set of words are. However, as most words have the highest relation to themselves, a single attention block might not be very helpful. This is why a multi-head attention block is used. This calculates attention multiple times and takes the weighted average to calculate overall attention.</p><p>Attention increases the number of contextual connections the network can make, and the network can learn relations and context from large datasets. Also as the attentions for each word are independent of other words, the attentions for each word can be calculated in parallel and be further processed in parallel, greatly increasing the computation time of these networks.</p><blockquote>The details of the attention block and the nuances of Transformer network are beyond the scope of this article. If you are interested in learning the details of the transformer network, the original paper and <a href="https://towardsdatascience.com/transformers-141e32e69591">this</a> TDS article are very good resources.</blockquote><p>Transformers have garnered a lot of attention (pun intended) in recent days due to 2 amazing models, BERT (by google) and GPT (by openAI). I recommend further reading on these topics if you find transformers interesting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5660f11281be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/3-neural-network-architectures-you-need-to-know-for-nlp-5660f11281be">3 neural network architectures you need to know for NLP!</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[Tax Jargon for Millennials.]]></title>
            <link>https://akashgshastri.medium.com/tax-jargon-for-millennials-79818f03c19c?source=rss-567a94bbd3d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/79818f03c19c</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[workforce-development]]></category>
            <category><![CDATA[millenials]]></category>
            <category><![CDATA[taxes]]></category>
            <dc:creator><![CDATA[Akash Shastri]]></dc:creator>
            <pubDate>Tue, 24 Nov 2020 20:40:45 GMT</pubDate>
            <atom:updated>2020-11-24T20:40:45.714Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is a beginner blog post for people who don’t know anything or know very little about the tax system.</h4><p>I have recently started working in the USA, and I knew nothing about taxes. I did not know when to pay them, or how to pay them. My time for reckoning came when I came across a video on youtube about how I could save on taxes if I registered as an LLC. Although I am not that well versed, from my research, yet to help you figure out if and why you should register as an LLC, I will help you understand, as best as I have understood, the <strong>Tax Jargon</strong> for the USA.</p><p>In this article, I will discuss only the <strong><em>Income Tax</em></strong>. I will discuss some of the basic terminologies. I will give a basic introduction on how to file for taxes.</p><blockquote><em>PS:- I am not an accountant, and you should consult a professional for your needs. I am simply giving you a platform to understand what your accountant is talking about.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bSPIDXFoGWcxC7fm.jpeg" /><figcaption>Image by The New York Public Library from uplash.</figcaption></figure><h3>Components of taxes.</h3><h3>Federal Taxes</h3><p>Federal taxes are taxes you owe the federal government. This is also collected by the IRS. The federal tax rate is the same throughout the country, and you must pay it every year. The rate of tax varies from year to year. The current tax code can be found <a href="https://www.irs.gov/privacy-disclosure/tax-code-regulations-and-official-guidance">here</a>.</p><h3>State Taxes</h3><p>Apart from federal taxes, most states require you to pay an additional state income tax. This state tax depends on the state you live in and earn your income in. <em>If you work and reside in different states things get a little complicated and extra research is due.</em></p><p>The tax rate of each state varies. You can find the state tax rate <a href="https://taxfoundation.org/2020-sales-taxes/">here</a> as of 2020.</p><blockquote><em>Interesting fact: As of 2020, 9 states have no state income tax. These states are </em><strong><em>Alaska</em></strong><em>, </em><strong><em>Florida</em></strong><em>, </em><strong><em>Nevada</em></strong><em>, </em><strong><em>New Hampshire</em></strong><em>, </em><strong><em>South Dakota</em></strong><em>, </em><strong><em>Tennessee</em></strong><em>, </em><strong><em>Texas</em></strong><em>, </em><strong><em>Washington,</em></strong><em> and </em><strong><em>Wyoming. </em></strong><em>However, you are still required to pay federal income taxes in these states.</em></blockquote><h3>Tax Slabs</h3><p>Tax slabs are how income tax is calculated. You can think of it as steps, and you divide your money and put them on each step. Each step is associated with a percentage.</p><p>For each step, you pay the percentage of tax denoted by the step on the amount you place on that step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uCZc74U9ULv4Y8KS.jpeg" /><figcaption>Fig 1: Simplified Tax slab. Image by the author.</figcaption></figure><p>Assume a simplified tax slab as shown in the picture above. And let’s say you earn 700,000 $ a year. You <strong><em>DO NOT </em></strong>have to pay 40 % on the entire 700,000$. You will have to pay 10% on the first 1000$ you earn, 20% on the next 9,000$ you earn, 30% on the next 90,000 $ you earn, and finally 40% on the remaining 600,000$ of your income.</p><p>This will come out to be:<br>0.1*1000+0.2*9000+0.3*90000+0.4*600000 = 268900</p><p>This means according to our fictitious simplified tax code, you will owe 268,900 $ in income tax annually. This is lesser than the 280,000 $ you would’ve paid had you paid 40% on the entire amount.</p><p>The tax slabs for 2020 USA can be found <a href="https://taxfoundation.org/2020-tax-brackets/">here</a>.</p><h3>Deductions and Credits</h3><h3>Deductions.</h3><p>A tax deduction is an amount you can reduce from your total annual income, so you pay Income tax only on the reduced total Income. An example would be the interest on your mortgage. If you earn 200,000 $ annually but pay 10,000 $ annually on the interest for your house mortgage, Then you can apply for tax deductions, and subtract 10,000$ from the 200,000$ income. Now you pay taxes only on 190,000$ rather than the full 200,000$.</p><p>There are 2 types of deductions, standard and itemized deductions. I will not get into these now, maybe in another blog post.</p><h3>Credits.</h3><p>Tax credits are reductions you can make in the amount of tax you pay. This is an extremely powerful tool. Think about the following situation:</p><p>You pay 50,000$ in taxes. And let’s assume there is only one tax slab at 10%.<br>Now if you get a tax deduction of 1,000$, that means you pay a 10% tax on 49,000$. Which comes out to 4,900$ of taxes paid. However, if you got a 1,000$ tax credit, now you pay 1,000$ lesser in taxes. So in this scenario, you pay only 4,000$ in taxes. In our particular scenario, the tax credit saved 900$ over the same amount in deductions.</p><blockquote><em>The numbers are not important, just remember tax credits reduce the tax amount, while deductions reduce the taxable Income amount.</em></blockquote><p>You can qualify for tax credits in a number of ways, I will not get into it now. Maybe in another blog post. :)</p><h3>Filing for taxes</h3><p>Filing taxes refers to filling out the correct forms required by the IRA and your state, to pay the taxes that you owe. Most employers will deduct pay to account for taxes, this way you have been paying taxes throughout the year instead of in one lump sum at the end. Even though you may have only one source of income (ex. Wages), and your employer has withheld taxes from your paycheck, and paid them to the IRA, you may still want to look into filing taxes. These can be either because you have earned extra income, or you think you are eligible to tax deductions and credits. There are 3 major ways you can file your taxes.</p><ol><li>The first method is to Learn the IRS and state tax code and fill the forms manually.<br>The <strong><em>Pros </em></strong>of this method are:- it’s free, you know your tax situation best and might be able to get the best returns and pay lesser.<br>The <strong><em>Cons </em></strong>of this method are:- it’s relatively complicated and time-consuming.</li><li>The second method is to hire a tax professional, either a certified personal accountant or a licensed member from the IRA.<br>The P<strong><em>ros </em></strong>of this method are:- you get personalized attention and solutions to help you save. This method is also particularly helpful if you have a complicated tax situation.<br>The <strong><em>Cons </em></strong>of this method are:- It’s the most expensive approach. You also have to do research on your accountant to find a well-qualified accountant.</li><li>The third method is to use tax software. These are a good in-between method, that has some qualities of both previously mentioned methods.<br>The <strong><em>Pros </em></strong>of this method are:- It’s cheaper than hiring a professional and easier than learning the tax code. It’s fast and efficient.<br>The <strong><em>Cons </em></strong>of this method are:- It’s not very personalized and is a more generic approach. If your tax situation is complicated, this might not be the best option for you.</li></ol><blockquote><em>Most software offers free services when your annual gross income is lesser than a certain value. Check out different software and their features and pricing before making a decision.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79818f03c19c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 decision tree-based algorithms for Machine Learning]]></title>
            <link>https://medium.com/data-science/3-decision-tree-based-algorithms-for-machine-learning-75528a0f03d1?source=rss-567a94bbd3d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/75528a0f03d1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Akash Shastri]]></dc:creator>
            <pubDate>Wed, 18 Nov 2020 01:23:45 GMT</pubDate>
            <atom:updated>2020-11-18T01:23:45.629Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this article, I will discuss some of the most widely used DecisionTree-based algorithms for machine learning.</h4><h3>Decision Trees</h3><h4>What are they?</h4><p>Decision trees are a tree algorithm that split the data based on certain decisions. Look at the image below of a very simple decision tree. We want to decide if an animal is a cat or a dog based on 2 questions.</p><ol><li>Are the ears pointy?</li><li>Does the animal bark?</li></ol><p>We can answer each question and depending on the answer, we can classify the animal as either a dog or a cat. The red lines represent the answer “NO” and the green line, “YES”.</p><p>This way the decision process can be laid out like a tree. The question nodes are called <strong>root nodes</strong> and the answer/terminal nodes are called <strong>leaf nodes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q28Ep1APaH6i3Hs3NvtSXA.png" /><figcaption>Simple Decision Tree. Image by the author.</figcaption></figure><h4>Which division comes first?</h4><p>When we have a table of data with multiple columns, Decision trees split the result based on columns. For the above DecisionTree, if we had a table like shown below, how do we decide which split comes first? Do we split first based on pointy ears or barking?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*ghSsirTnQHK1AMSPmrYiiQ.png" /><figcaption>Cat or dog table. Image by the author.</figcaption></figure><p>We can use certain metrics to decide which column is the best classifier. There are 3 popular metrics that are used.</p><ol><li>Gini Impurity.</li><li>Information Gain.</li><li>Variance reduction.</li></ol><p>Gini impurity as far as I have seen is the most popular, so let’s take a look at it.<br>Classifying based on a single variable, we have the following <strong>stumps </strong>(single node trees).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ijrhesoe255bWuyJoL5xyQ.png" /><figcaption>Decisions and correctness. Image by the author.</figcaption></figure><p>Look at the above decisions and the number of correct and incorrect predictions they made. At each leaf node, the Gini impurity is calculated as below:</p><p>Gini at leaf = 1 -(“yes” probability)² -(“No” probability)²</p><p>So Gini for the first Node’s leaves will be:<br>Leaf 1: 1 -(3/5)² -(2/5)² = 0.48<br>Leaf 2: 1 -(4/5)² -(1/5)² = 0.32</p><p>The Gini impurity for the entire node is the weighted sum of the Gini at each leaf node. So the Gini for the first node is:<br>(0.48)*(5/10) + (0.32)*(5/10) = 0.4</p><blockquote>The weights for the sum, in this case, is the same as both classes contain 5 elements each. This is not usually the case and that is when the weighted sum of Gini is important.</blockquote><p>Similarly, the Gini impurity for the second node will be: 0</p><p>As the Gini Impurity is lower for the second node, that should be our first split. This way, we decide the order in which features are used to split data.</p><h4>How to split based on continuous variables?</h4><p>How do we split continuous variables or multicategory variables? Continuous variables are a little trickier, the key idea is to arrange the continuous variable in order, and at each data point, take the average between the previous and the current data point and split the data based on the average, and calculate the Gini impurity. After going through the entire data, select the split with least Gini Impurity.</p><blockquote>Example: Consider a list of heights and a classification as tall or short. At each data point (height), we split based on average of the current and previous data. Say the average at step i is 150 cm, then we assume all data less than 150 cms is short and greater than 150cm is tall. Then we calculate the gini impurity based on how many correct and incorrect predictions we made. Then we choose another split and check the gini impurity of that split, till we find the split with lowest impurity.</blockquote><p>A similar strategy is used for categorical variables with more than 2 classes.</p><blockquote>If this explanation is a little confusing, or you need further clarification, watch this <a href="https://www.youtube.com/watch?v=7VeUPuFGJHk&amp;ab_channel=StatQuestwithJoshStarmer">amazing video</a> by <strong>Statquest</strong> on youtube.</blockquote><h4>Decision Trees for Regression</h4><p>So far we have only discussed decision trees for classification, but they can also be used for regression. The process for selecting decision-splits and important features is very similar to that of classification trees. The difference is how the impurity is calculated and how the output is predicted.</p><p>Consider a tree with 1 node (also called stump) and 2 leaf nodes. After the data is split, all the values of each of the leaf nodes are averaged, and that average is the prediction for that leaf node.</p><p>The difference between the prediction of each data point and the actual value is called the <strong>residual</strong>. The sum of squares of all the residuals after the split is the impurity metric. The split with the lowest impurity or the split with the lowest sum of squared residuals is chosen.</p><h3>Random Forests</h3><p>The problem with Decision trees is that they overfit the data. They learn to split the training data to lower the metric but end up doing so in such a way that it overfits the data and the model does poorly on unseen data.</p><p>There are 2 main ideas to fix the overfitting of Decision Trees.</p><ol><li>Bootstrapping</li><li>Ensembling</li></ol><h4>Bootstrapping</h4><p>Bootstrapping can be thought of as a sampling method. The main idea is to randomly select a subset of the data, on which the decision tree is trained. This makes the Decision tree overfit less (because it sees lesser data), however, it does nothing to increase the validation accuracy. This is only part of the solution.</p><h4><strong>Ensembling</strong></h4><p>We reduced overfitting by bootstrapping, and now our tree fits only on a subset of data, but how does this help?</p><p>This is where the second part of Random Forests comes in. The idea of random forests is to make the decision tree a weaker predictor but to have many predictors and consider a central tendency (mean-average or mode-highest votes) of the set of predictors.</p><p>Random forests combine bootstrapping and ensembling. The data is randomly sampled, and a decision tree is trained on each of the sets of randomly sampled data. This way there are many decision trees each trained on a different random subset of the data.</p><p>As no tree has seen the entire data, they cannot overfit the data, and as there are a lot of trees, the errors in prediction are driven lower by averaging the outputs of all the trees.</p><p>This way with ensembling and bootstrapping, random forests achieve far superior performance as compared to any single Decision tree.</p><h3>Gradient boosted Decision Trees</h3><p>Gradient boosting has a similar approach to random forests, in that it chooses weaker predictors, but multiple in number to both avoid overfitting and achieve top tier performance. Gradient boosted trees can be used for both classification and regression.</p><h4>Mechanism</h4><p>Consider a regression problem. Gradient boosted trees have the following approach.</p><p>Step one is to always predict the average of all the target values. This is a baseline prediction of the target value. Once we have a baseline, each target variable is subtracted by the baseline prediction, this gives the residuals for step one.</p><blockquote><strong>residuals = target — prediction</strong></blockquote><p>Step two is to fit a decision tree for the residuals, where the output of each leaf node is the average of residuals in the leaf node. Now to predict the target, we scale the output by a value called learning rate (lr) and add this scaled value to the previous prediction. The sum is the new prediction, and we can repeat the above steps by calculating a new set of residuals.</p><p>Pred ᵢ = Pred ₍ᵢ₋₁₎ + lr * output</p><p><em>Where </em><strong><em>output</em></strong><em> is the </em><strong><em>average of residuals</em></strong><em> in the leaf node</em></p><p>The residual is analogous to the derivative of the loss function in neural networks. As the residual is the difference between the target and the prediction, if the residual is positive it means our prediction was lower than the target, and adding a scaled residual to our prediction will make it closer to the correct target. Similar idea for negative residuals.</p><p>When multiple steps of gradient boosted trees are stacked, the prediction will be remarkably close to the prediction, and the model will perform very well on unseen data as well.</p><blockquote>If you are a visual learner, I highly recommend <a href="https://www.youtube.com/channel/UCtYLUTtgS3k1Fg4y5tAhLbw">StatQuest</a> on youtube. It is an amazing resource where Josh explains these algorithms and more with animations and quirky songs.</blockquote><blockquote>Also, the best way to practice is to download a kaggle dataset, open a jupyter notebook, dive in and just explore :))</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75528a0f03d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/3-decision-tree-based-algorithms-for-machine-learning-75528a0f03d1">3 decision tree-based algorithms for Machine Learning</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[5 Neural network architectures you must know for Computer Vision]]></title>
            <link>https://medium.com/data-science/5-neural-network-architectures-you-must-know-for-computer-vision-31d2991fe24e?source=rss-567a94bbd3d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/31d2991fe24e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Akash Shastri]]></dc:creator>
            <pubDate>Tue, 10 Nov 2020 21:31:13 GMT</pubDate>
            <atom:updated>2020-11-10T21:31:13.118Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>In this article, I list my top 5 neural network architectures for computer vision in no particular order</h4><h3>Convolutional Neural Networks</h3><h4>History</h4><p>The idea of convolutions was first introduced by <a href="https://en.wikipedia.org/wiki/Kunihiko_Fukushima">Kunihiko Fukushima</a> in <a href="https://www.rctn.org/bruno/public/papers/Fukushima1980.pdf">this paper</a>. The <a href="https://en.wikipedia.org/wiki/Neocognitron">neocognitron</a> introduced 2 types of layers, convolutional layers and downsampling layers.</p><p>Then next key advancement was by <a href="https://en.wikipedia.org/wiki/Yann_LeCun">Yann LeCun</a> et al. when they used back-propagation to learn the coefficients of the convolutional kernel from images. This made learning automatic and not laboriously handcrafted. According to Wikipedia, this approach became a foundation for modern computer vision.</p><p>Then came “ImageNet Classification with Deep Convolutional Neural Networks” in 2012, by <em>Alex Krizhevsky, Ilya Sutskever, Geoffrey E. Hinton, </em>which is widely regarded as the most influential paper on convolutional neural networks. They created Alexnet and won the 2012 Imagenet competition with their model.</p><h4>Mechanism</h4><p>I will not dive deep into the mechanism of CNNs but want to give a brief overview of how it works.</p><p>Where regular vanilla neural networks were trained on layers that computed WX + b, Where W is the weight matrix that is learned through backpropagation, convolutional neural networks use weights called filters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*ror4mkfhRV-DbEFoo4m09w.gif" /><figcaption>Convolution operation. Image from <a href="https://giphy.com/explore/convolution">https://giphy.com/explore/convolution</a>.</figcaption></figure><p>You can think of a convolutional <a href="https://en.wikipedia.org/wiki/Kernel_(image_processing)">kernel </a>or filter, like a sliding window over the input matrix. In the above gif, the filter is the orange shaded matrix with red numbers. The input matrix is the green matrix with black numbers. At each stage, the filter is multiplied with the overlapped section of the input matrix element-wise, and the values are summed. This gives the first output. Then the filter is moved one step to the left, and so on as shown in the gif. <br>The loss can be calculated for the output and label with respect to the filter values, and with backpropagation, we can learn the values of the filter.</p><p>Convolutional neural networks are actually just matrix multiplications when you unroll the kernel and input. This is shown in <a href="https://towardsdatascience.com/a-comprehensive-introduction-to-different-types-of-convolutions-in-deep-learning-669281e58215">this very good blog post</a>. CNNs are extremely powerful for 2 main reasons.</p><ol><li>They have significantly fewer parameters per layer, and hence can be stacked to form deeper layers.</li><li>They address the locality of input. The locality of pixels in an image is maintained, as the kernel acts on parts of the image at a time, and close pixels in the input create output values that are also close. This is different from traditional networks that do not take locality into consideration.</li></ol><h3>Residual Networks (ResNet)</h3><p><a href="https://arxiv.org/abs/1512.03385">Residual networks</a> were introduced by <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=He%2C+K">Kaiming He</a> et al. in their massively influential paper, “Deep Residual Learning for Image Recognition”. The paper from the Microsoft research team won the 2015 Imagenet competition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*2oCKA9vEqldBDjZSlgkvQA.png" /><figcaption>Skip connections. Image by the author.</figcaption></figure><p>ResNets have an extremely simple yet extremely elegant idea. The idea was to add skip connections or shortcut connections, that created a gradient highway. This enabled gradients to flow better during the backward step, and greatly increased convergence, time of training and reduced gradient explosion and vanishing.</p><p>The subtle beauty of Resnets is that the best-case scenario is when the skip connection actively adds to the output and computes useful information, and the worst-case scenario is when it simply ignores the skipped connection and is at worst the same as a network without a skip connection. <strong>So skip connections add so much value and have no downside!</strong></p><h3>U Net</h3><p>U-Nets were introduced by Olaf Ronneberger, Philipp Fischer, and Thomas Brox in their paper “U-Net: Convolutional Networks for Biomedical Image Segmentation”, which you can read <a href="https://arxiv.org/pdf/1505.04597.pdf">here</a>. This 2015 paper was revolutionary for image segmentation. Image segmentation is the task of labelling each pixel in an image with its category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*soHtXw7ROtXMBQBJMgD_cQ.png" /><figcaption>U-Net architecture. Image is taken from the <a href="https://arxiv.org/pdf/1505.04597.pdf">original U-Net paper</a>.</figcaption></figure><p>U-Nets have 2 parts, the contracting path (downsampling path) and the expansive path (upsampling path). In a traditional image classification convolutional network, the image is fed into a network which performs convolutions and pooling operations, both of which reduce the height and width of the output but increase the depth of the output. With a loss in height and width, the depth gained adds features to the classification output.</p><p>However, in segmentation tasks, we want the output to be the same shape as the input image and the added features for labelling pixels. So the downsampling of a traditional Conv architecture is supplemented by an upsampling path, to add back the height and width of the image to the output, while maintaining the features. There are many upsampling methods, but the most common one used in most libraries is Transpose convolution upsampling. You can read about this method <a href="https://naokishibuya.medium.com/up-sampling-with-transposed-convolution-9ae4f2df52d0">here</a>.</p><h3>YOLO</h3><p>YOLO was first introduced by <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Redmon%2C+J">Joseph Redmon</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Divvala%2C+S">Santosh Divvala</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Girshick%2C+R">Ross Girshick</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Farhadi%2C+A">Ali Farhadi</a> in their paper “You Only Look Once: Unified, Real-Time Object Detection” which you can read <a href="https://arxiv.org/pdf/1506.02640.pdf">here</a>. The paper was proposed as a fast, state of the art model for object detection in 2015. Over the years, YOLO has had 4 official versions (where papers were published). The first 3 were by the original authors and the last one was by a different author. I will not discuss the versions of YOLO now, maybe in another post ;-)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*949cCfDSdpyV0F3DHjgikw.png" /><figcaption>YOLO architecture. Image is taken from the <a href="https://arxiv.org/pdf/1506.02640.pdf">original YOLO paper</a>.</figcaption></figure><p>YOLO stands for you only look once. When the paper was released, the popular method for object detection was to reuse classifiers to classify local regions of an image and use a sliding window approach to check if each region of an image has an object. YOLO shifted the paradigm by proposing object detection as a regression problem, where they only use a single network for the entire pipeline and process the whole image at once rather than in regions.</p><p>YOLO divides the input image into an SxS grid. And for each grid predicts if the centre of an object is present within the grid. If the centre of the object is in the grid, the grid will then predict a bounding box with 5 values, x,y,w,h,c. (x,y) are the coordinates of the centre of the object relative to the grid, (w,h) is the width and height of the object relative to the whole image and (c ) is the class of the object.</p><blockquote>“YOLO has 3 main benefits. Loosely Quoted from the <a href="https://arxiv.org/pdf/1506.02640.pdf">original paper [1]</a>.</blockquote><blockquote>First, YOLO is extremely fast. Since the paper frames detection as a regression problem, it doesn’t need a complex pipeline.</blockquote><blockquote>Second, YOLO reasons globally about the image when making predictions. Unlike sliding window and region proposal-based techniques, YOLO sees the entire image during training and test time so it implicitly encodes contextual information about classes as well as their appearance.</blockquote><blockquote>Third, YOLO learns generalizable representations of objects. Since YOLO is highly generalizable it is less likely to break down when applied to new domains or unexpected inputs.”</blockquote><h3>Generative adversarial networks</h3><p>Generative adversarial networks or GANs for short were introduced by <a href="https://arxiv.org/search/stat?searchtype=author&amp;query=Goodfellow%2C+I+J">Ian J. Goodfellow</a>, <a href="https://arxiv.org/search/stat?searchtype=author&amp;query=Pouget-Abadie%2C+J">Jean Pouget-Abadie</a>, <a href="https://arxiv.org/search/stat?searchtype=author&amp;query=Mirza%2C+M">Mehdi Mirza</a>, <a href="https://arxiv.org/search/stat?searchtype=author&amp;query=Xu%2C+B">Bing Xu</a>, <a href="https://arxiv.org/search/stat?searchtype=author&amp;query=Warde-Farley%2C+D">David Warde-Farley</a>, <a href="https://arxiv.org/search/stat?searchtype=author&amp;query=Ozair%2C+S">Sherjil Ozair</a>, <a href="https://arxiv.org/search/stat?searchtype=author&amp;query=Courville%2C+A">Aaron Courville</a>, <a href="https://arxiv.org/search/stat?searchtype=author&amp;query=Bengio%2C+Y">Yoshua Bengio</a> in their paper “Generative Adversarial Networks” which you can read <a href="https://arxiv.org/pdf/1406.2661.pdf">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRcEh3S_YBrQHshaGhzh4A.png" /><figcaption>GAN Image. Image by the author.</figcaption></figure><p>GANs are a neural network pair that are trained through an adversarial process. The 2 parts of a GAN are a Generator and a Critic/Discriminator. The role of the generator is to generate high-quality data that is similar to training data, and the role of the critic is to differentiate between the generated data and the real data. The objective function of the generator is to maximise the loss of the critic, and the objective function of the critic is to minimize its loss.</p><p>Think of this process as analogous to a thief and the police. The thieves want to fool the police and keep improving their tools and techniques, and the police want to catch the thieves so they improve too. The generator is like the thief and the critic is like the police.</p><p>There are numerous applications for GANs and many new applications are coming out all the time. But since this article is about computer vision, two extremely interesting applications of GANs are:</p><ol><li><strong>Super-resolution</strong><br>Super-resolution refers to taking a low-quality image and generating a high-quality image from it. Nvidia’s new DLSS could be using this technique.<br> Jeremey Howard from <a href="https://www.fast.ai/">fast.ai</a> has an extremely interesting approach called the noGAN approach for super-resolution. This process is a sort of pretraining for GANs, where high-quality images are converted to lower quality images for training data of the Generator, and the critic is pre-trained on the generated images. This way, both the generator and critic have a head start, and this method is found to significantly improve training time for GANs.</li><li><strong>Deep fakes<br></strong>I’m sure everybody has heard of deep fakes from the media. Deep fakes are also GANs where the generator is trained to perform the faking operation, and the critic is tasked with detecting the fake. The generator can be trained for long enough to fool most humans. This is a somewhat dangerous technology and something to be aware of on the internet.</li></ol><h3>References</h3><p>[1] <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Redmon%2C+J">Joseph Redmon</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Divvala%2C+S">Santosh Divvala</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Girshick%2C+R">Ross Girshick</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Farhadi%2C+A">Ali Farhadi</a>, “You Only Look Once: Unified, Real-Time Object Detection” (2015), <a href="https://arxiv.org/abs/1506.02640"><br>arXiv:1506.02640</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31d2991fe24e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/5-neural-network-architectures-you-must-know-for-computer-vision-31d2991fe24e">5 Neural network architectures you must know for Computer Vision</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[Why I use Fastai and you should too.]]></title>
            <link>https://medium.com/data-science/why-i-use-fastai-and-you-should-too-a421f6c99508?source=rss-567a94bbd3d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a421f6c99508</guid>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Akash Shastri]]></dc:creator>
            <pubDate>Tue, 10 Nov 2020 00:13:23 GMT</pubDate>
            <atom:updated>2020-11-10T00:13:23.245Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is part 1 of a multipart series: The things I love the most about my favourite deep learning library, fastai.</h4><h3>This episode: Learning rate (LR)</h3><h4>LR before fastai</h4><p>The general consensus on finding the best LR was usually to train a model fully, until the desired metric was achieved, with different optimizers at different LRs. The optimal LR and optimizer are picked depending on what combination of them worked best in the picking phase. This is an ok technique, although computationally expensive.</p><blockquote>Note: As I was introduced early in my deep learning career to fastai, I do not know a lot about how things are done without/before fastai, so please let me know if this was a bit inaccurate, also take this section with a grain of salt.</blockquote><h3>The fastai way</h3><p>The fastai way to LRs is influenced by Leslie Smith’s Paper [1]. There are mainly 3 components to finding the best LR, find an optimal LR for training (explained in LR find section), As training progresses, reduce the LR (explained in LR annealing section), and a few caveats for transfer learning (explained in discriminative LR) and one cycle training (part of LR annealing).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5zGROIoKOXwjQ2fy2T7NrQ.png" /><figcaption>LR and consequences. Image by the author.</figcaption></figure><p><strong>What should our learning rate be?<br></strong>This is an important question to ask, as the learning rate is what drives the parameters of our model to optimal solutions. Too low and the learning will take too long. Too high and the model will <em>NOT EVEN</em> learn. We need a learning rate in a range of values that drives parameters to convergence while doing so at a reasonable pace.</p><h4>LR find</h4><p>LR find is fastai’s approach to finding a good learning rate. They do this by selecting a very low LR at first, training one mini-batch at this LR, and calculate the loss. The next mini-batch is trained at an incrementally higher LR, and this process continues till we reach an LR where the model clearly diverges.</p><p>LR is plotted against loss, and we can see our graph below. There is a certain LR where loss is minimum, after which increasing LR any more will worsen loss.</p><p>Picking the LR where loss is lowest is erroneous. We need the LR for which loss decreases the fastest. This is also the steepest part of the graph. Fastai implements a function to find both the steepest and the minimum LR divided by 10 (which is also a good LR to train on)</p><pre>learn.lr_find() <a href="https://docs.fast.ai/callback.schedule#Learner.lr_find">[docs]</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*nt29NXRRF-LvpXuCzHqclQ.png" /><figcaption>LR find. Image from <a href="https://github.com/fastai/fastbook">fastiai’s fastbook</a>, GPL-3.0 License</figcaption></figure><blockquote>This method is computationally cheaper and faster, as we need only 1 epoch (not even that) to find the optimal LR, whereas traditionally we would train 1 epoch for each logical range of LR (definitely more than 1 epoch in total).</blockquote><h4>LR annealing</h4><p>The next step of the puzzle is LR annealing. Initially, our parameters are imperfect. They are very far from optimal parameters. But as we train, the parameters get closer to the optimal values.</p><p>When our parameters are very far from optima (beginning) we want to take larger, more imprecise steps, in the general direction of optima. But as we get closer, we don’t want to take large steps and accidentally overshoot optima, we want to take smaller steps to get a precise perfect parameter set.</p><blockquote>This is analagous to golf. You don’t attempt a hole in one, (you could but that’s more luck than skill) you simply try to lob the ball as far as possible in the general direction of the hole. And as you get closer, you change your clubs to gain more precision and control, and look for smaller steps, each inching you closer to the hole.</blockquote><p>This is why at the beginning of training, we want large learning rates, that push us hard and fast towards optimal parameters, but as we get closer, we want to lower the learning rate. As our loss decreases, we want to take smaller steps, and hence use a smaller LR.</p><p>This process of altering LR during training is called LR decay/ LR annealing. The figure below shows the large initial steps contrasted with the smaller final steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hsp6I5_ezQUJH6FSdGjgww.png" /><figcaption>Lr annealing. Image by author</figcaption></figure><h4>Fit one cycle</h4><p>The current general consensus on the difficulty of GD (gradient-descent) based training is that the optimizer can get stuck in saddle points. This is different from what we used to think was the main issue ( local minima). Leslie Smith shows in [3] that increasing the LR helps escape saddle points and get to a good region of the loss function, after this, we once again reduce the LR for reasons explained in LR annealing. However, there’s one final step to the fit one cycle approach as explained by Sylvain Gugger <a href="https://sgugger.github.io/the-1cycle-policy.html">here</a>, which is to reduce the LR to one-hundredth of the minimum LR for the last few iterations. Also known as annihilation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzkfkJBMk6pnX5OVYedR-A.png" /><figcaption>Saddle point. Image By Nicoguaro — Own work, CC BY 3.0, <a href="https://commons.wikimedia.org/w/index.php?curid=20570051">https://commons.wikimedia.org/w/index.php?curid=20570051</a></figcaption></figure><p>The steps are simple, pick an LR as explained in the LR find section of this article. That is the maximum acceptable LR. We also choose a minimum LR which is, as suggested by Sylvain, to be one-tenth the maximum LR. Now we cycle between this range, where the cycle length is slightly lesser than the total number of epochs. And in the last part, we reduce LR to one-hundredth of the minimum LR.</p><pre>fit_one_cycle(<strong>learn</strong>:<a href="https://fastai1.fast.ai/basic_train.html#Learner">Learner</a>, <strong>cyc_len</strong>:int, <strong>max_lr</strong>:Union[float, Collection[float], slice]=<strong><em>slice(None, 0.003, None)</em></strong>, <strong>moms</strong>:Point=<strong><em>(0.95, 0.85)</em></strong>, <strong>div_factor</strong>:float=<strong><em>25.0</em></strong>, <strong>pct_start</strong>:float=<strong><em>0.3</em></strong>, <strong>final_div</strong>:float=<strong><em>None</em></strong>, <strong>wd</strong>:float=<strong><em>None</em></strong>, <strong>callbacks</strong>:Optional[Collection[<a href="https://fastai1.fast.ai/callback.html#Callback">Callback</a>]]=<strong><em>None</em></strong>, <strong>tot_epochs</strong>:int=<strong><em>None</em></strong>, <strong>start_epoch</strong>:int=<strong><em>None</em></strong>) [<a href="https://fastai1.fast.ai/train.html#fit_one_cycle">docs</a>]</pre><p>There are 2 main parameters to use when scheduling LR, which is what we’re doing during the one cycle policy. And these are momentum and step size. For more information and further reading on how LR is scheduled, check <a href="https://fastai1.fast.ai/callbacks.one_cycle.html#The-1cycle-policy">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmgYmIAcYd18mqX5Oegc3w.png" /><figcaption>One cycle LR. Image by fastai course, Apache-2.0 License.</figcaption></figure><h4>Discriminative LR (during Transfer learning)</h4><p>Transfer learning is the process of using a neural network trained for one task, to do a different task after minimal training. This is extremely useful for reasons I will explain now.</p><p>Zeiler and Fergus published an amazing paper called Visualizing and Understanding Convolutional Networks [2], In which they show what different layers of a neural network learn, and they visualize what is learned by different layers. From the image below, we can see the first layer recognizes basic lines, colours, and colour gradients. The second layer recognizes more complex shapes like edges and circles, and then by the third layer, the network starts recognizing patterns.</p><p>Now consider you have a cat detector, which can recognize a cat. And you want to make a bear detector. A cat is much more similar to a bear than random noise, and most layers have of a cat detector have already learned very useful parameters. So we only need to fine-tune the model and change the last few layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*9_7xjaHD-5Pad926afsrHA.png" /><figcaption>What different layers of a neural net see. Source: <a href="https://arxiv.org/pdf/1311.2901.pdf">Visualizing and Understanding Convolutional Networks</a>.</figcaption></figure><p>And fastai is perfect for doing this. The fastai approach to transfer learning is basically 2 steps.</p><ol><li>We first freeze our model, meaning stop gradient calculations for earlier layers, and train only the last 2 layers.</li><li>We then unfreeze the model, so gradients flow back all the way. However, we already know that the earlier layers don’t need a lot of learning, as they have already learned important parameters (common attributes like lines for images). So we need lower learning rates for earlier layers and higher ones for later layers. Fastai has this functionality built-in.</li></ol><p>The 4 lines of code to do transfer learning with fast ai are</p><pre>learn = cnn_learner(dls, resnet34, metrics=error_rate) <br>#import a model of your choice, pretrained on imagenet (default)</pre><pre>learn.fit_one_cycle(3, 3e-3) <br>#train the last few layers of model</pre><pre>learn.unfreeze() <br>#unfreeze the model, so we can train all layers</pre><pre>learn.fit_one_cycle(12, lr_max=slice(1e-6,1e-4))<br># use a lr_max, which uses lowest value of LR for first layer<br># and increments LR for later layers</pre><p>The graph below is a graph of LR plotted against loss after the model is unfrozen. As we can see, there’s no steep descent of loss, this is in line with our idea that initial layers have learned useful information. Hence the low loss even at the start, and gradual decline.</p><blockquote>The method for selecting LR remains same, minima/10 or point of steepest descent</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*TuCAZJMN-0_GcC7yd8MhnA.png" /><figcaption>LR during fine-tuning. Image from <a href="https://github.com/fastai/fastbook">fastiai’s fastbook</a>, GPL-3.0 License</figcaption></figure><h3>References</h3><p>[1]. <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Smith%2C+L+N">Leslie N. Smith</a>, A disciplined approach to neural network hyper-parameters: Part 1 — learning rate, batch size, momentum, and weight decay (2018<em>), </em><a href="https://arxiv.org/abs/1803.09820">arXiv:1803.09820</a></p><p>[2]. <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Zeiler%2C+M+D">Matthew D Zeiler</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Fergus%2C+R">Rob Fergus</a>, Visualizing and Understanding Convolutional Networks (2013), <a href="https://arxiv.org/abs/1311.2901">arXiv:1311.2901</a></p><p>[3]. <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Smith%2C+L+N">Leslie N. Smith</a>, Cyclical Learning Rates for Training Neural Networks (2017), <a href="https://arxiv.org/abs/1506.01186">arXiv:1506.01186</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a421f6c99508" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/why-i-use-fastai-and-you-should-too-a421f6c99508">Why I use Fastai and you should too.</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[All the ways to initialize your neural network]]></title>
            <link>https://medium.com/data-science/all-ways-to-initialize-your-neural-network-16a585574b52?source=rss-567a94bbd3d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/16a585574b52</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[weight-initialization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Akash Shastri]]></dc:creator>
            <pubDate>Fri, 30 Oct 2020 22:51:30 GMT</pubDate>
            <atom:updated>2020-10-30T22:52:10.325Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this article, I evaluate the many ways of weight initialization and current best practices.</h4><h3>Zero Initialization</h3><p><strong>Initializing weights to zero DOES NOT WORK. </strong>Then Why have I mentioned it here? To understand the need for weight initialization, we need to understand why initializing weights to zero <strong>WON’T </strong>work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*C-Q_WOX7y58CplVET_QVcg.png" /><figcaption>Fig 1. Simple Network. Image by the Author.</figcaption></figure><p>Let us consider a simple network like the one shown above. Each input is just one scaler X₁, X₂, X₃. And the weights of each neuron are W₁ and W₂. Each weight update is as below:</p><p>Out₁ = X₁*W₁ + X₂*W₁ + X₃*W₁<br>Out₂ = X₁*W₂ + X₂*W₂ + X₃*W₂</p><p>As you can see by now, if the weight matrix W = [W₁ W₂] is initialized to zero, then both out1 and out2 are exactly the same.</p><p>Even if we add a non zero random bias term to both, The weights are updated to non-zero, However, they will remain identical, hence both neurons of the hidden unit are computing the same thing. In other words, they are <strong><em>Symmetrical</em></strong>.</p><p>This is highly undesirable as this is wasted computation. This is why zero initialization does not work.</p><h3>Random Initialization</h3><p>Now that we know the weights have to be different, the next idea was to initialize these weights randomly. Random initialization is much better than zero initialization, but can these random numbers be <strong><em>ANY </em></strong>number?</p><p>Let’s assume you are using sigmoid non-linearity. The function is drawn below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*tRUSpGBEXsFh8nwE8qgJuQ.png" /><figcaption>Sigmoid. Image by the author.</figcaption></figure><p>We can see that even for values as big as 6 the value of sigmoid is almost 1, and for values as small as -6 the value of sigmoid is zero. This means if our weight matrix is initialized to values that are either too big or too small, all useful information is lost in the sigmoid function.</p><p>This is not as important if we use a ReLu non-linearity, but there are other problems with weights being initialized to large or small values. There are better ways to initialize our weights.</p><h3>Xavier Initialization</h3><p><a href="http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf">Xavier Initialization</a> was proposed by Xavier Glorot and Yoshua Bengio in 2010. The main objective of this paper was to initialize weights such that the activations have a mean of zero and a standard deviation of 1. Consider a function computed as shown below.</p><blockquote>Z = WX + b</blockquote><p>Here W is the weight matrix, X is the input from the previous layer and b is the bias. Z is the output computed by a layer also called activations. We want Z to have a mean of 0 and a standard deviation of 1. (Technically Z is the result after a non-linear activation like ReLu)</p><p>Why is a mean of zero and a standard deviation of 1 important?<br>Consider a deep neural network with 100 layers. At each step, the weight matrix is multiplied with the activations from the previous layer. If the activations of each layer are greater than one, When they get multiplied repeatedly 100 times, they will keep getting larger and <strong>explode </strong>to infinity. Similarly, if the activations are less than one, They will <strong>vanish </strong>to zero. This is called the <strong><em>exploding and vanishing gradient </em></strong>problem. <br>We can see this in the image below. Values even a little greater than 1 explode to very large numbers and values even a little lesser than 1 vanish to zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*rQnzf2cZsRIwX6gPusQhxg.png" /><figcaption>Image by the author.</figcaption></figure><p>To avoid exploding and vanishing of gradients and activations, we want activations on average having mean 0 and standard deviation 1. We can achieve this with careful selection of our weights.</p><p>During the time this paper was released, the best practice for weights was to select them randomly from a <a href="https://en.wikipedia.org/wiki/Continuous_uniform_distribution"><strong><em>uniform distribution</em></strong></a> of [-1,1] and divide them by the square root of input dimensions. As it turns out, This is not such a good idea and gradients vanish and training is very slow if at all possible.</p><p>This was fixed with the Xavier initialization who proposed we initialize weights randomly from a uniform distribution as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*Yd4GwOVX1c2Y-6hDZdOZFQ.png" /><figcaption>Xavier Init Uniform Distribution. Image by the author.</figcaption></figure><p>Nowadays Xavier Initialization is done by choosing weights from a <a href="https://en.wikipedia.org/wiki/Normal_distribution#Standard_normal_distribution"><strong><em>standard normal distribution</em></strong></a> and each element is divided by the square root of the size of input dimensions. In PyTorch, the code is as below.</p><pre>torch.randn(n_inp, n_out)*math.sqrt(1/n_inp)</pre><p>Xavier Initialization works fairly well for symmetric nonlinearities like sigmoid and Tanh. However, it does not work as well for ReLu which is now the most popular nonlinearity.</p><h3>Kaiming Initialization</h3><p>He et al. wrote a paper called Delving <a href="https://arxiv.org/pdf/1502.01852.pdf"><em>Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification</em></a><em> </em>in 2015, in which they introduced what is now popularly known as Kaiming Init.</p><p>But why do we need Kaiming Init? What was the issue with Xavier Init for ReLu nonlinearities?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*5LBPVw7XiVrM6YDXqqNkvg.png" /><figcaption>ReLu. Image by the author.</figcaption></figure><p>As you can see from the above graph, ReLu gives 0 for all X&lt;0 and Y=X for all X&gt;0. ReLu is not well defined at 0, but most modern programs assign it a close to zero approximation like <a href="https://en.wikipedia.org/wiki/Machine_epsilon#:~:text=Formal%20definition,-Rounding%20is%20a&amp;text=For%20a%20number%20system%20and,of%20the%20chosen%20rounding%20procedure.&amp;text=%2C%20so%20machine%20epsilon%20also%20is,rounding%20to%20the%20unit%20value%22.">machine epsilon</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*_CmkCZTworAcAqioMTtNhg.png" /><figcaption>Left: A normal distribution with mean 0 and standard deviation 1. Right: The normal distribution after being passed through ReLu. Image by the author.</figcaption></figure><p>Above we can see 2 scatter plots, on the left is data before ReLu and on the right is after ReLu. It is clear from the images that the variance is almost half and the mean is slightly higher, after ReLu. This changes the activations and the variance is halved, so we need to double the variance to get the original effect of Xavier Init. Hence we multiply the weights by an additional <br><strong>√2</strong>. So in PyTorch, Kaiming Init is as shown below.</p><pre>torch.randn(n_inp, n_out)*math.sqrt(2/n_inp)</pre><blockquote>In case you are still confused:<br> variance = (Standard deviation)²<br>Hence if you want to double variance, you multiply data by <strong>√2</strong></blockquote><h3>Fixup Initialization</h3><p><a href="https://arxiv.org/abs/1901.09321">Fixup</a> was an initialization proposed by Zhang et al. in 2019. Their observation was that Kaiming init and other standard initialization did not work well for networks with residual branches (AKA <a href="https://arxiv.org/abs/1512.03385">Residual networks</a>). They found that residual networks with standard initialization <strong>worked well only with </strong><a href="https://arxiv.org/abs/1502.03167"><strong>BatchNorm</strong></a>.</p><p>Let us see why Kaiming Init does not work on Residual networks. Consider the skip connection shown in Image below. <strong>X2 = f(X1)</strong> and <strong>X3 = f(X2) + X1</strong>. We know that Kaiming init chooses weights such that the activations after each layer have 0 mean and 1 variance. So we know X1 has variance 1 and X2 has variance 1. But Kaiming init does not account for skip connections. Hence by the law of total variance, the variance of X3 is doubled. This extra variance added by a residual branch is not accounted for in Kaiming Init. Hence Residual networks do not work well with standard init unless they have BatchNorm. Without BatchNorm, the output variance explodes exponentially with depth.</p><blockquote>Var[Xₗ₊₁] ≈ 2Var[Xₗ ]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*2oCKA9vEqldBDjZSlgkvQA.png" /><figcaption>Skip connection in a residual network. Image by the author.</figcaption></figure><p>The authors in the paper made an important observation that <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_descent">SGD</a> updates to weights of each residual branch updated the network output in a highly correlated direction. This means if residual branch weights are all updated by X, the network output also changed proportionally to X in the same direction of weight updates.</p><p>The authors defined the change in network output desired, to be Θ(η). As we know the residual branch updates each on average contribute equally to output update, And if we call the number of residual branches L, then on average each residual branch should change the output by Θ(η/L) to achieve a total change of Θ(η) on output.</p><p>Next, the authors show how they can initialize the residual branch of m layers so that it’s SGD update changes the output by Θ(η/L). The authors show that this can be done by rescaling the standard init of these weight layers by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/1*e-cD-sDO4b1qNge6gfq20g.png" /><figcaption>Weight Scale factor. Image by the author.</figcaption></figure><p>The authors also discuss the utility of biases and multipliers. They found adding a bias layer initialized at 0 before every convolution, linear layer and element-wise activation lead to significant improvement in training. They found that adding one multiplicative scaler per residual branch helped mimic the weight norm dynamics of a network with normalization.</p><p>To summarize fixup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oO7DWZITmJfxsiLF3xclwg.png" /><figcaption>Fixup summary. Image is taken from the fixup paper Zhang et al.</figcaption></figure><blockquote>Fixup is a little confusing, so if you have any questions feel free to ask in the comments and I will be happy to answer to the best of my ability.</blockquote><h3>LSUV Initialization</h3><p>LSUV was introduced in a 2016 paper by Mishkin et al. called <a href="https://arxiv.org/abs/1511.06422"><strong><em>All you need is a good Init</em></strong></a>. LSUV Init is a data-driven approach that has minimal calculations and very low computational overhead. The initialization is a 2 part process, first initializing weights to orthonormal matrices ( as opposed to Gaussian noise, which is only approximately orthogonal). The next part is to iterate with a mini-batch and scale the weights so that the variance of activations is 1. The authors assert that the influence of mini-batch size on variance is negligible in wide margins.</p><p>In this paper, the authors lay out the steps for initialization as follows.</p><ol><li>Initialize weights to Gaussian noise with unit variance.</li><li>Decompose them to orthonormal basis with either <a href="https://en.wikipedia.org/wiki/Singular_value_decomposition">SVD</a> or <a href="https://en.wikipedia.org/wiki/QR_decomposition">QR</a>.</li><li>Iterate through the network with first mini-batch and on each iteration scale the weights to make the output variance closer to 1. Repeat till output variance is 1 or maximum iterations have taken place.</li></ol><blockquote>In the paper, the authors propose the scaling factor to be<strong> √Var(BL)</strong>, Where <br>BL — its output blob</blockquote><blockquote>The authors also propose a value for maximum iterations to prevent infinite loops, However, in their experiments, they found that unit variance was achieved in 1–5 iterations.</blockquote><p>LSUV Init can be thought of as a combination of orthonormal initialization and, BatchNorm performed only on the first mini-batch. The authors, in their experiments, show that this method is highly computationally efficient compared to full BatchNorm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8FQ3PtzJ8I_eZBsAxeGYQ.png" /><figcaption>LSUV Algorithm. Image is taken from LSUV paper.</figcaption></figure><h3>Transfer Learning</h3><p><a href="https://en.wikipedia.org/wiki/Transfer_learning#:~:text=Transfer%20learning%20(TL)%20is%20a,when%20trying%20to%20recognize%20trucks.">Transfer learning</a> is the method of using weights from an already trained model that was trained for a similar task, in our new model. These weights have already learned a lot of useful information, we can simply fine-tune it for our specific goal and <em>VOILA</em>! We have an amazing model without the hassle of Initialization.</p><p>Using pre-trained weights from another model is the best approach every time. The only times we would have to initialize our own weights is if we were working on a network that nobody has ever trained before. And in most practical scenarios, this is hardly the case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16a585574b52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/all-ways-to-initialize-your-neural-network-16a585574b52">All the ways to initialize your neural network</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[Regularization. What, Why, When, and How?]]></title>
            <link>https://medium.com/data-science/regularization-what-why-when-and-how-d4a329b6b27f?source=rss-567a94bbd3d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4a329b6b27f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Akash Shastri]]></dc:creator>
            <pubDate>Sat, 24 Oct 2020 02:20:44 GMT</pubDate>
            <atom:updated>2020-10-24T02:20:44.179Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>In this article, I want to take an in-depth look at regularization.</h4><h3>What?</h3><p><strong>What is regularization?</strong></p><p>Regularization is a method to constraint the model to fit our data accurately and not overfit. It can also be thought of as penalizing unnecessary complexity in our model. There are mainly 3 types of regularization techniques deep learning practitioners use. They are:</p><ol><li>L1 Regularization or Lasso regularization</li><li>L2 Regularization or Ridge regularization</li><li>Dropout</li></ol><blockquote><strong>Sidebar</strong>: Other techniques can also have a regularizing effect on our model. You can prevent overfitting by also having more data to constraint the search space of our function. This can be done with techniques like data augmentation, that create more data to train, hence reducing overfitting.<br>There are many other solutions to overfitting such as ensembling and stopping early, that can help prevent overfitting but are not considered regularization as they do not constraint the search space or penalize complexity. Although you should keep these in mind as regularization is not the only way to cure overfitting.</blockquote><h3>Why?</h3><p><strong>Why do we need regularization?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkJjUzk4BeCt7JoRU7WL3Q.png" /><figcaption>Fig 1: Underfit v overfit. Image by the author. Inspired by <a href="https://www.youtube.com/channel/UCcIXc5mJsHVYTZR1maL5l9w">Andrew Ng</a></figcaption></figure><p>In Fig 1, we see 3 curves. The one on the left is doing a poor job of predicting the points, and the one on the right is doing a <strong>“TOO GOOD”</strong> job of predicting the points. We can intuitively tell the left graph isn’t right, but why is the right one bad? Isn’t it good that our model predicts points exactly where they are?</p><p>The answer is <strong>NO</strong>, and here’s why. Our data contains some noise, we do not want our model to predict noise, as noise is random. So the graph on the right is not ideal either, we want something like the graph in the middle.</p><p>Underfitting is caused due to our model being too simple, or not being trained long enough. Overfitting is a harder problem.<br>Overfitting can be caused either due to an overly complex model that’s learning noise, or the search space for our model function is large and we do not have enough data to constraint the search.</p><p>So regularization is a way to stop overfitting.</p><h3>When?</h3><p><strong>When do we use regularization?</strong></p><p>We use regularization whenever we suspect our model is overfitting. The biggest signs of overfitting are the poor performance of validation metrics. The validation set is part of our dataset that the model has not yet seen.</p><p>As we want to detect if our model is learning just from the data, or is being heavily influenced by noise, we use the validation set which has different noise than our training set. So if our model were to overfit the training data, it would predict poorly on our validation set.</p><p>During training, we also constantly measure validation metrics. If we see the validation metrics not improving significantly, or worsening, this is a telltale sign that our model is overfitting. We need to then apply regularization techniques.</p><blockquote><strong>Note</strong>: Some regularization techniques have no downside, and should be used <strong>ALL </strong>the time. An example of this is data augmentation. There’s no downside to using data augmentation and should be used regardless of whether model is overfitting.</blockquote><h3>How?</h3><p><strong>L1 Regularization</strong></p><p>L1 regularization works by adding a penalty based on the absolute value of parameters scaled by some value l (typically referred to as lambda).</p><p>Initially our loss function was: <strong>Loss = f(preds,y)<br></strong>Where <em>y is the target output, and preds is the prediction</em><strong><br></strong><em>preds = WX + b</em>, where <em>W is parameters, X is input and b is bias.</em></p><p>With L1 regularization we add an extra term of l*|W|, where W is the weight matrix (parameters). So our loss function after L1 regularization is</p><blockquote>Loss = f(preds, y) + l*abs(W)</blockquote><p><strong>L2 Regularization</strong></p><p>L2 regularization is very similar to L1 regularization, except the penalty term is the square of the parameters scaled by some factor l (lambda)</p><blockquote>Loss = f(preds, y) + l*(W)²</blockquote><p><strong><em>Difference between L1 and L2 regularization</em></strong></p><p>The difference between L1 and L2 regularization is that the gradients of the loss function with respect to parameters for L1 regularization are <strong>INDEPENDENT </strong>of parameters, so some parameters can be set all the way to zero, hence completely ignored.</p><p>But in L2 regularization, the gradients of the loss function are <strong>DEPENDENT </strong>linearly on the parameters, so the parameters can never be zero. They only asymptotically approach zero. This means that no parameter is entirely ignored, and every parameter always has at least a very minimal effect on predictions.</p><p>This difference is key to choosing the type of regularization, if you know you have useless features, L1 might be a better choice. If you want to consider all features, the L2 might be a better choice.</p><blockquote>Nuance: There is one nuance in deep learning where you can use a best of both worlds approach, by using both L1 and L2 regularization. This is called Elastic net Regularization.</blockquote><p><strong>Dropout</strong></p><p><a href="https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf">Dropout</a> is an amazing regularization technique that works only on neural networks (as far as I know). The amazing idea of dropout is to randomly zero some elements of the input tensor with probability p (p is a hyperparameter).</p><p>The intuition behind why this would work is simple, overfitting occurs when our model is too complex, so how can we simplify the model? Just don’t use some neurons and BAM!! a simpler model achieved.</p><p>Dropout is found to work very well in practice and is simple to implement. I definitely recommend giving it a try.</p><p><strong>Data Augmentation</strong></p><p>Data augmentation is our final “how” for regularization. The idea behind data augmentation is very simple, yet extremely elegant.</p><p>We know overfitting is caused by a lack of constraint in the search space of our optimal function. How do we add more constraint? More data. <br>But collecting more data for our problem can be a time consuming and arduous task. This is where data augmentation comes in.</p><p>The idea of data augmentation is to create more data from the data we already have. The way this is done is by applying a few transformations to our image, that change the image to make multiple versions of the same image that are different. And magically (NOT) we have more data.</p><p>The list of data augmentations my favorite deep learning library (<a href="https://www.fast.ai/">fastai</a>) provides can be seen <a href="https://docs.fast.ai/vision.augment">here</a>.</p><h3>Conclusion</h3><p>Check if your model overfits, use one of the above regularization methods to save it from overfitting. ALWAYS USE DATA AUGMENTATION!! Fin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4a329b6b27f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/regularization-what-why-when-and-how-d4a329b6b27f">Regularization. What, Why, When, and How?</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[Cross-Entropy Demystified.]]></title>
            <link>https://medium.com/data-science/cross-entropy-demystified-f0886a64883f?source=rss-567a94bbd3d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0886a64883f</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Akash Shastri]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 23:21:39 GMT</pubDate>
            <atom:updated>2020-10-08T17:58:18.293Z</atom:updated>
            <content:encoded><![CDATA[<h4>An in-depth look at Cross-Entropy, the intuitions, and reasoning behind its necessity and utility.</h4><h3>Introduction.</h3><p>For the longest time, I had not completely understood Cross-Entropy loss.<strong> Why did we take exponents (softmax)? Why did we then take the log? Why did we take negative of this log? How did we end up with a positive loss that we have to minimize?</strong></p><p>These questions and more boggled my mind, to the point where I just accepted that I just had to use cross-entropy for multilabel classification and didn’t think about it much.</p><p>Recently I started going through fastai’s 2020 Course, where Jeremy was explaining Cross entropy, and even though I think he did a good job, my previous questions were not well answered. So I began pondering and playing with the notebooks, and finally figured it out.</p><p>In this article, I will ask a few simple questions which I will then answer, hopefully after which you will not have any more mind-boggling questions about cross-entropy.</p><h4>What is the goal of a loss function?</h4><p>The goal of a loss function is to simply output one number (how we arrive at this number will soon be clear), and this number has 2 requirements.</p><ol><li>The number has to be positive.</li><li>The number should be greater the more inaccurate our model is.</li></ol><p>Our goal is to minimize this number, The closer our loss is to zero, the more accurate our model is.</p><blockquote>Note: I will not get into why this is the case, I assume you know the objective of neural nets is to minimize loss. If you want to learn more, go to fast.ai and follow along Jeremy’s amazing deep learning course. This applies for all non cross entropy related questions, however I am willing to answer them in the comments.</blockquote><h4>First stop, Activations.</h4><p>Our first stop is activations. These are the last layer outputs of a neural network and are the guesses our network makes to the label of our image. The closer the activations are to the labels, The more accurate our model is.</p><p>let&#39;s consider an image of a tennis ball, We are trying to find out whether the image is one of three things,, either :</p><ol><li>basketball</li><li>tennis ball</li><li>football</li></ol><p>The label of the tennis ball will be [0,1,0]. These are the predictions that would be 100% accurate. The guesses respectively correspond to 0% basketball, 100% tennis ball, 0% football.</p><p>Now lets say our activations are [0.001, 4.334, 2.90]. These are just random numbers I pulled out of my imagination. However, if we assume these are the activations, we can clearly see the activation for the tennis ball is highest, however, how do we quantify this? Or how do we put it in terms of percentage probability?</p><p>Also if we had a different set of activations, say [4.334, 2.90, 0.01], now the highest activation is for basketball, But our image is a tennis ball, how do quantify how wrong our model is?</p><h3>This is where cross-entropy comes in.</h3><p>Cross entropy is a loss function, that quantifies how wrong our model is.</p><p>There are mainly 3 steps to this madness (although once you understand its super easy and intuitive).</p><h4>1. Softmax</h4><p>The first step is to make our activations values between 0 and 1. We do this all values of activations correspond to a probability of image belonging to a certain class, now we can simply maximize the one value corresponding to the correct class, which will automatically reduce the values corresponding to the wrong class. This process would’ve been much harder if we were working with raw activations.</p><blockquote>Note: Do not get confused when I say we want to maximize activations. WE DO WANT TO MAXIMIZE ACTIVATIONS, we want to MINIMIZE only the loss. <br>ACTIVATIONS ARE THE GUESSES OUR MODEL MAKES, LOSS IS THE MEASURE OF WRONGNESS OF OUR MODEL.<br>We want to reduce wrongness (Loss) and increase the correct prediction (activation corresponding to correct label).</blockquote><p><strong><em>How do we do softmax? </em></strong><br>FOR EACH ITEM, Take the exponent of each item and divide by the sum of exponents of all item.</p><p>For our activations [4.334, 2.90, 0.01], lets calculate exponent of each item.</p><p>acts = [4.334, 2.90, 0.01]</p><p>exp_acts = [76.2487, 18.1741, 1.0101]</p><p>sum(exp_acts) = 95.4329</p><p>acts_softmax = [0.7990, 0.1904, 0.0106]</p><p>See how the highest activation corresponds to the highest probability, that&#39;s why we do softmax</p><blockquote>Sidebar: Why don’t we simply do acts = acts/sum(acts) ?<br>Lets try it:<br>acts/sum(acts) = [0.5983, 0.4003, 0.0014]<br>compare this with the softmax, the higher activation corresponds to waaay higher probability with softmax than with normalization. This feature is desirable MOST of the time in classification, hence we use softmax.</blockquote><h4>2. Log</h4><p>Consider 2 cross-entropy values, one is 0.99 and the second is 0.999. They seem relatively close, and if we calculate our loss based on softmax, the loss for the two won’t be far apart. However, this is not desirable. <br>Consider 10,000 items, with the first softmax of 0.99, 100 items are misclassified, but with the second softmax of 0.999, only 10 items are misclassified. In essence, softmax of 0.999 is 10 times better, not just a little better. This difference in quality is best expressed with the log.</p><p>log (0.01) = -4.6051<br>log (0.001) = -6.9077</p><p>The cast difference in log values despite the close softmax values is very useful. <br>Also log(1) = 0, So when softmax probability is 100% for the correct class, the loss (if just log(softmax) is 0).</p><p>The way we calculate loss is, where label ==1, we take the -log(softmax), which is the loss.</p><h4>3. Why the negative log loss?</h4><p>In our case where softmax is 1, log softmax is 0, so the loss is zero. This is correct.</p><p>But when our softmax is 0.01, our log softmax is -<strong>4.6, </strong>but we know our loss has to be a high positive number that we have to minimize, so we take the negative of it, making our -log(softmax) positive, which is the correct value for loss to be.</p><p>Log is negative due to the nature of the curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gTWdst1BI1J2F0e-8QLZA.png" /><figcaption>Log values for x &lt; 1 are negative. Image by <a href="https://saylordotorg.github.io/text_intermediate-algebra/s10-03-logarithmic-functions-and-thei.html">Saylor Academy</a> under license <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/">CC BY-NC-SA 3.0</a></figcaption></figure><p>And because softmax values are always less than or equal to one, the log is always negative, hence -log(softmax) is positive.</p><p><strong>Just to reiterate: -Log(softmax) is our loss value. We take the mean of each loss value in a dataset or minibatch to get overall loss, which we try to minimize.</strong></p><h3>Takeaway thoughts</h3><ol><li>We take the exponent of activations to make the gap between predicted probabilities larger.</li><li>We take the log of softmax to equate small differences in softmax with a large difference in loss, which should exist. <strong>In a sense, we smush the activations with softmax to help predict, but we un-smush them with log to evaluate loss accurately.</strong></li><li>We take negative of the log to get a positive loss, as log return negative values for values lesser than 1 (which is the case with softmax values).</li></ol><h3>Credits</h3><ol><li>A lot of the ideas here were taken from Jeremy Howard’s Fastai course, I simply attempted to explain what I understood better, and added a few ideas of mine.</li><li><a href="https://saylordotorg.github.io/text_intermediate-algebra/s10-03-logarithmic-functions-and-thei.html">https://saylordotorg.github.io/text_intermediate-algebra/s10-03-logarithmic-functions-and-thei.html</a> , is where I got the logarithm image from.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0886a64883f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/cross-entropy-demystified-f0886a64883f">Cross-Entropy Demystified.</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[Easiest Fastai installation for windows]]></title>
            <link>https://akashgshastri.medium.com/easiest-fastai-installation-for-windows-d30e5e4a6f99?source=rss-567a94bbd3d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d30e5e4a6f99</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[fastai]]></category>
            <dc:creator><![CDATA[Akash Shastri]]></dc:creator>
            <pubDate>Sun, 04 Oct 2020 20:15:48 GMT</pubDate>
            <atom:updated>2020-10-04T20:15:48.575Z</atom:updated>
            <content:encoded><![CDATA[<p>The easiest installation of windows I have found is with Anaconda. Anaconda is a Package manager that helps you install and maintain the correct versions of packages, and also allows you to make virtual environments.</p><h4>Steps to install Fastai</h4><ol><li>Install Anaconda</li><li>Install Cudatoolkit</li></ol><blockquote>conda install -c anaconda cudatoolkit</blockquote><p>3. Install pytorch, you can find instructions at <a href="https://pytorch.org/">https://pytorch.org/</a>. Make sure to select the newest version of CUDA, and select CONDA as your package.</p><p>4. Install fastai with the git clone + pip install method.</p><blockquote>git clone https://github.com/fastai/fastai<br>pip install -e &quot;fastai[dev]&quot;</blockquote><p>Note: As of now, num_workers has to be 0 for fastai. So whenever you’re making a dataloader, make sure to set num_workers =0.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d30e5e4a6f99" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>