<?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 Shreya on Medium]]></title>
        <description><![CDATA[Stories by Shreya on Medium]]></description>
        <link>https://medium.com/@shreyasingh18?source=rss-f3927efcae1d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eCqT7eGao-EfNlEPwoTIow.jpeg</url>
            <title>Stories by Shreya on Medium</title>
            <link>https://medium.com/@shreyasingh18?source=rss-f3927efcae1d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:42:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shreyasingh18/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[The Kill List — review]]></title>
            <link>https://medium.com/@shreyasingh18/the-kill-list-review-6b34bc24d73f?source=rss-f3927efcae1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b34bc24d73f</guid>
            <dc:creator><![CDATA[Shreya]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 23:03:04 GMT</pubDate>
            <atom:updated>2026-01-11T23:03:04.017Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Kill List — review</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*tbsgrAop7SP-pssylrGCAw.png" /></figure><p>Over 50 years after writing the gripping thriller, “The Odessa Files” and known for other award-winning novels such as, “The Fourth Protocol” and, “The Dogs of War”, Frederick Forsyth has once again brought it with his 2013 novel, “The Kill List.”</p><p>If you like non-fictional characters and historical events enveloped in a fictional mystery then this writer should be your first choice. Informative in nature with details mapped out meticulously, Forsyth’s novels are educational as well as a great read for those who enjoy the occasional thrillers.</p><p>With its major focus on the theme of espionage, the Kill List follows the story of a US Marine Corps officer who tracks down a terrorist termed, “the preacher” famous for giving sermons on the internet and inciting acts of violence in the west. The motive becomes very personal for this individual called, “the tracker” when his own father becomes a victim of this violence.</p><p>The actual scene of the attack on the preacher’s establishment in Somalia is covered in only the last 40 pages of the novel as the majority of the novel covers the strategy, techniques, and collaboration between the United States, England, and Israel to track down this individual in question.</p><p>A lot of information is provided on how the US has formerly tracked down terrorists using their state-of-the-art equipment and technology and the military equipment and drones used for doing so. Its interaction with its allied countries in today’s world is powerfully highlighted across the novel.</p><p>The novel has also brought in themes of cyber security and warfare to adapt it to scenarios plaguing the world today.</p><p>For an author whose major thriller work was written mostly in the 1970s, the Kill List is a captivating read for all ages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b34bc24d73f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Liability and the Cost of Bias in AI-Driven Credit Scoring System]]></title>
            <link>https://medium.com/@shreyasingh18/liability-and-the-cost-of-bias-in-ai-driven-credit-scoring-systems-12886e843331?source=rss-f3927efcae1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/12886e843331</guid>
            <dc:creator><![CDATA[Shreya]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 22:04:12 GMT</pubDate>
            <atom:updated>2025-03-15T16:33:52.175Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZNRIQ24bCzbHOD31a7NgA.png" /><figcaption>Dall-E</figcaption></figure><p>Paper written for the Law and Governance of AI course at Northwestern as a final paper assignment.</p><p><strong>Introduction</strong></p><p>The adoption of artificial intelligence (AI) in credit scoring systems has transformed how financial institutions assess creditworthiness. By analyzing vast datasets, these systems promise faster and more efficient lending decisions, ostensibly broadening access to credit. However, reliance aon AI also introduces significant risks. When these systems embed biases from historical data, they disproportionately impact marginalized communities, raising questions about fairness and legality. Moreover, financial institutions operating biased systems risk legal penalties and reputational damage. This dual threat underscores the urgent need for regulatory accountability to ensure fairness and inclusivity in credit scoring.</p><h3>Background on AI in Credit Scoring</h3><p>AI credit scoring systems analyze diverse data points beyond traditional credit history — such as utility bills, social media activity, and even online purchasing behavior. By incorporating these alternative data sources, AI models aim to create a holistic credit profile, particularly for individuals with limited credit history. Financial institutions benefit from reduced processing times and operational costs, while borrowers potentially gain increased access to credit.</p><p>Despite these advantages, the datasets used to train AI models often contain historical inequities. For example, historical lending practices have excluded certain demographic groups, leading to underrepresentation in financial data. When AI models learn from such datasets, they risk perpetuating discriminatory practices, whether intentional or not.</p><h3>Equal Credit Opportunity Act</h3><p>When AI systems discriminate in such ways, it violates the<a href="https://www.justice.gov/crt/equal-credit-opportunity-act-3"> Equal Credit Opportunity Act</a> of 1974. The <strong>Equal Credit Opportunity Act (ECOA)</strong> is a cornerstone of anti-discrimination law in the United States, aimed at ensuring fairness in lending practices. Enacted in 1974, the ECOA prohibits creditors from discriminating against applicants based on protected characteristics such as race, color, religion, national origin, sex, marital status, or age. The law also extends protections to individuals receiving public assistance and mandates that creditors provide reasons for adverse credit decisions upon request.</p><p>On September 19th, 2023, the Consumer Financial Protection Bureau (CFPB) issued a statement saying that consumers must receive accurate and specific reasons for credit denial. This was concerning lenders’ obligations when using artificial intelligence (AI) and other complex technologies to make consumer credit decisions.</p><p>Under ECOA and Regulation B, a creditor taking an adverse action against a credit applicant must provide the applicant with a statement of reasons for the action taken that is “specific” and includes the “principal reason(s) for the adverse action.”</p><h4>Existing Gaps in the ECOA</h4><ol><li><strong>Algorithmic Discrimination </strong>While the ECOA prohibits discrimination, it does not specifically address the nuances of AI-driven decisions. Algorithms trained on biased historical data may produce discriminatory outcomes even without explicit intent, creating a gray area in determining violations of the act. <strong>Apple Credit Card case of 2019 </strong>— In 2019, allegations of algorithmic discrimination were made against Apple Card’s AI-based credit system. Reports showed that women were often granted significantly lower credit limits than men, even when they had similar credit histories and financial profiles.</li><li><strong>Lack of Transparency<br></strong>The ECOA does not mandate transparency in credit decision-making processes. AI systems often operate as “black boxes,” making it difficult for regulators to scrutinize the factors influencing a lending decision. Without clear explanations, consumers face challenges in identifying potential discrimination or errors. In June, 2023, CFPB commissioner Rohit Chopra issued a <a href="https://www.consumerfinance.gov/about-us/blog/algorithms-artificial-intelligence-fairness-in-home-appraisals/">statement</a> in which he said that organizations should include Local Interpretable Model-agnostic Explanations (LIME) or Shapley Additive exPlanations (SHAP) values to convey the rationale behind credit denial decisions. LIME/SHAP are interpretability-enhancing methods which harness statistics to <a href="https://ff06-2020.fastforwardlabs.com/#why-are-some-models-uninterpretable%3F">increase</a> the transparency of black-box AI models. They reveal determinative factors that lead to a credit denial decision, with some limitations. While this seems like a potential solution, with the advancement of AI models and their complexity, it seems harder to implement these in practice.</li><li><strong>No Bias Mitigation Requirements<br></strong>The ECOA lacks provisions requiring financial institutions to conduct proactive bias audits or implement safeguards against algorithmic discrimination. As a result, biases embedded in AI systems can remain undetected until harm occurs.</li></ol><p><strong>Impact of Bias on Consumers and Society</strong></p><ol><li><strong>Societal Impacts</strong></li></ol><p>The consequences of bias in AI credit scoring systems are far-reaching. Marginalized groups, particularly low-income communities and racial minorities, are disproportionately affected. A 2021 study revealed that African American and Hispanic borrowers were more likely to be denied loans or charged higher interest rates due to biased algorithms.</p><p>These disparities exacerbate existing socio-economic inequalities by limiting access to essential financial services, such as mortgages, car loans, and small business financing. Over time, this entrenches financial exclusion, creating a cycle of disadvantage for vulnerable populations.</p><p><strong>2. Legal and Reputational Risks for Financial Institutions</strong></p><p>Operating biased AI systems exposes financial institutions to significant legal and reputational liabilities. Financial institutions found in violation of anti-discrimination laws face lawsuits, regulatory penalties, and reputational damage. In addition to legal repercussions, public exposure of biased practices can result in a loss of consumer trust. In today’s digital age, where information spreads rapidly, reputational harm can have lasting consequences for a company’s bottom line.</p><h3>Need for Regulatory Accountability</h3><p>The legal frameworks governing credit scoring, such as the ECOA and the Fair Credit Reporting Act (FCRA), were designed for traditional credit assessment methods. These laws do not account for the complexities of AI-driven systems, leaving significant gaps in regulatory oversight. For instance, current laws do not mandate transparency in how AI models make lending decisions or require regular audits to detect bias.</p><p>Several jurisdictions have begun addressing these gaps. The European Union’s proposed AI Act, for example, introduces strict regulations for high-risk AI applications, including credit scoring. However, similar efforts in the U.S. remain fragmented and insufficient to address the scale of the issue.</p><h3>Proposed Solutions for Accountability and Fairness</h3><p>To modernize the ECOA and ensure it remains effective in the era of AI, several solutions can be implemented:</p><ol><li><strong>Amend the ECOA to Include AI-Specific Provisions<br></strong>Update the ECOA to and include what constitutes “indirect discrimination” in the context of AI models and requiring institutions to demonstrate that their algorithms comply with fair lending practices.</li><li><strong>Mandate Transparency in AI Decision-Making<br></strong>Financial institutions should be required to provide clear explanations of how AI models reach credit decisions. This could involve providing consumers with accessible summaries of the data inputs and reasoning behind a decision. Transparency enhances accountability and helps consumers identify potential issues.</li><li><strong>Introduce Mandatory Bias Audits<br></strong>Regular audits by independent third parties should be mandated to detect and address biases in AI models. These audits would ensure that training data and algorithms comply with anti-discrimination laws, creating an additional layer of oversight.</li><li><strong>Establish Clear Guidelines for AI Use in Lending<br></strong>Regulatory agencies, such as the CFPB, should develop detailed guidelines on the permissible use of AI in credit scoring. These guidelines should cover data collection practices, model development, and ongoing monitoring requirements.</li></ol><p><strong>Legal Analysis of Proposed Solutions</strong></p><p>The proposed solutions align with existing anti-discrimination laws while addressing their limitations in the context of AI. implementing these reforms requires careful consideration of legal and technical challenges. For example, mandating transparency in AI models may conflict with intellectual property laws or expose sensitive trade secrets. Policymakers must balance the need for accountability with the protection of proprietary information.</p><p>Similarly, bias audits raise questions about who should bear the cost of compliance. Smaller financial institutions may struggle to afford regular audits, potentially creating an uneven playing field. Subsidies or public-private partnerships could help address this issue.</p><h3>Conclusion</h3><p>Bias in AI-driven credit scoring systems poses a dual threat to consumers and financial institutions. To address these challenges, regulatory accountability is essential. By updating existing laws policymakers can ensure fair and inclusive lending practices. Through proactive reforms, we can harness the potential of AI while safeguarding against its risks.</p><p><strong>Footnotes</strong></p><ol><li><a href="https://www.cnbc.com/2023/06/23/ai-has-a-discrimination-problem-in-banking-that-can-be-devastating.html#:~:text=%E2%80%9CThis%20can%20result%20in%20automatic,perpetuate%20discrimination%2C%E2%80%9D%20she%20said.">“AI Has a Discrimination Problem in Banking That Can Be Devastating,” <em>CNBC</em>, 2023.</a></li><li><a href="https://diposit.ub.edu/dspace/bitstream/2445/201366/1/TFM-INTBUS_Antonevics_2023.pdf">Antonevics, “Reducing Bias in AI-Based Financial Services,” University of Barcelona Dissertation, 2023.</a></li><li><a href="https://www.europarl.europa.eu/news/en/press-room/20240308IPR19015/artificial-intelligence-act-meps-adopt-landmark-law">https://www.europarl.europa.eu/news/en/press-room/20240308IPR19015/artificial-intelligence-act-meps-adopt-landmark-law</a></li><li><a href="https://www.technologyreview.com/2021/06/17/1026519/racial-bias-noisy-data-credit-scores-mortgage-loans-fairness-machine-learning/">https://www.technologyreview.com/2021/06/17/1026519/racial-bias-noisy-data-credit-scores-mortgage-loans-fairness-machine-learning/</a></li><li><a href="https://www.goodwinlaw.com/en/insights/blogs/2024/03/interpretable-algorithms-as-a-potential-solution-to-cfpbs-guidance-on-ai-driven-credit-denials">https://www.goodwinlaw.com/en/insights/blogs/2024/03/interpretable-algorithms-as-a-potential-solution-to-cfpbs-guidance-on-ai-driven-credit-denials</a></li><li><a href="https://www.mofo.com/resources/insights/231002-cfpb-issues-guidance-on-ai-use-in-credit-decisions">https://www.mofo.com/resources/insights/231002-cfpb-issues-guidance-on-ai-use-in-credit-decisions</a></li><li><a href="https://www.consumerfinance.gov/about-us/newsroom/cfpb-issues-guidance-on-credit-denials-by-lenders-using-artificial-intelligence/">https://www.consumerfinance.gov/about-us/newsroom/cfpb-issues-guidance-on-credit-denials-by-lenders-using-artificial-intelligence/</a></li><li><a href="https://www.bdo.com/insights/advisory/fair-lending-in-the-era-of-artificial-intelligence">https://www.bdo.com/insights/advisory/fair-lending-in-the-era-of-artificial-intelligence</a></li><li><a href="https://digital-strategy.ec.europa.eu/en/policies/regulatory-framework-ai">https://digital-strategy.ec.europa.eu/en/policies/regulatory-framework-ai</a></li><li><a href="https://www.justice.gov/crt/equal-credit-opportunity-act-3">https://www.justice.gov/crt/equal-credit-opportunity-act-3</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12886e843331" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cilka’s Journey by Heather Morris — A review]]></title>
            <link>https://medium.com/@shreyasingh18/cilkas-journey-by-heather-morris-a-review-a46644537775?source=rss-f3927efcae1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a46644537775</guid>
            <dc:creator><![CDATA[Shreya]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 08:54:02 GMT</pubDate>
            <atom:updated>2023-02-20T08:54:02.017Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cilka’s Journey by Heather Morris — A review</h3><p>A rare find and unlike anything I have read, I came across a book called Cilka’s Journey written by novelist Heather Morris a while ago. She is known for her best-selling novel called, “The Tattooist of Auschwitz”; however Cilka’s Journey which narrates the harsh living conditions of a 16-year-old girl post her release from the concentration camp of Auschwitz-Birkenau in 1945 is a gripping narrative.</p><p>A hard-to-put-down novel with powerful storytelling capabilities, Cilka’s Journey is a rollercoaster of emotions for the reader who hopes that life after the concentration camps would only get better for the young Cilka Klein, but the reality is far from it.</p><p>A rare insight into the lifestyle and conditions of a survivor’s journey, Cilka once again finds herself in another concentration camp-like atmosphere called the Vorkuta Gulag, a place north of the Arctic Circle. She was sentenced by the Russians to this gulag for conspiring with the Nazis during their regime, with many other people who were falsely accused or accused with little to no evidence of the same. The reason for the sentence was that she was raped by one of the Nazi officers which was considered conspiratory by the Russians.</p><p>The gulag highlights Cilka’s Journey to stay alive amongst the harshest of conditions with almost little to no lifestyle change from the camps that dissolved in 1945. Taking up the position of the nurse at a hospital she is able to provide basic food and amenities to her fellow camp members.</p><p>The heart-wrenching moment comes when Cilka gives up the opportunity to leave the camp for her best friend Josie, who just had a newborn baby and does not want to part with the child.</p><p>After serving 8 years in the gulag, Cilka is finally released and goes on to live with her husband, a life that can only be considered normal, especially after everything she had been through.</p><p>While Morris had no personal interview with Cilka, the book is written from the many interviews she conducted with people who knew or had personally known about Cilka Klein. The indomitable spirit, her willingness to go through all odds to survive, and the small ray of hope carried by this young girl makes for a powerful and unique read.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a46644537775" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Silent Patient — A Review]]></title>
            <link>https://medium.com/@shreyasingh18/the-silent-patient-a-review-56949e101b43?source=rss-f3927efcae1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/56949e101b43</guid>
            <dc:creator><![CDATA[Shreya]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 09:26:50 GMT</pubDate>
            <atom:updated>2023-01-31T09:26:50.893Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Silent Patient — A Review</h3><p>It’s been a while since I’ve picked up a bestselling thriller novel; but I had heard some great reviews about a particular book called, “The Silent Patient.” Generally a reader of classics, science, murder mysteries, and thrillers based on missions carried out by secret services, this is the first psychological thriller novel that I have read.</p><p>The book is explored through a perspective of a psychotherapist, Theo Faber who tries to understand the silence of a woman who shot her husband five times and then paints a portrait depicting a reference to a similar Greek Mythology, post the murder.</p><p>My expectations were the same as I would have from any thriller novel written by Fredrick Forsyth, Desmond Bagley, or Robert Ludlum, where the novel unfolds in the final stages of the book but keeps you hooked at every twist and turn.</p><p>On the contrary, the Silent Patient has minimal twists and turns in the first half of the novel leading to a slow buildup. The novel is meant for the reader to come to their own conclusions on why Alicia Berenson has gone silent and the author has provided several clues for doing so.</p><p>Similar to an Agatha Christie murder mystery story where the reader is given the opportunity of solving the mystery along with the concerned detective, the author provided similar clues into the mind of the psychotherapist appointed to treat Alicia.</p><p>Reading from here on may contain some spoilers;</p><p>At first, there is incriminating evidence that psychotherapist, Theo Faber had something to do on a more personal note with the patient, Alicia Berenson. The very fact that he quit a previous secure job to move to a place that might close down that contained Alicia indicated a very personal motive with the patient right from the start. Moving to a new job that might not hold a future seemed like a risky decision. Even though Theo mentions it is mostly to help her because of his childhood trauma, it is difficult for the reader to believe that it is the sole motive.</p><p>Moreover, the book concentrates much of Theo’s time and resources to only Alicia whilst there are several other patients in the ward who he does not seem to treat or with whom he has minimal interaction.</p><p>A major part of the book reflects on Theo’s own marriage and childhood and his lack of courage to confront his wife about her infidelity. This leaves the reader with a major clue that his failing marriage had some sort of connection to Alicia, the patient he was treating in the ward.</p><p>Gripping as the novel is towards the end, it holds a lot of clues to Alicia’s silence and unfolds in a way that can be guessed by the reader. The twists and turns are dramatic and persuasive in encouraging the reader to carry on with the novel. This novel is more about enabling the reader to understand why and dive into the mind of the characters involved as opposed to an ordinary thriller that presents the facts at the end</p><p>It is a good read for someone starting with this genre!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56949e101b43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2b : Backpropagation in the LSTM Network.]]></title>
            <link>https://medium.com/@shreyasingh18/part-2b-backpropagation-in-the-lstm-network-535a61cec396?source=rss-f3927efcae1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/535a61cec396</guid>
            <dc:creator><![CDATA[Shreya]]></dc:creator>
            <pubDate>Fri, 07 Oct 2022 09:47:14 GMT</pubDate>
            <atom:updated>2022-10-07T09:47:14.371Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 2b : Backpropagation in the LSTM Network.</h3><p>In the <a href="https://medium.com/@shreyasingh18/part-2a-long-short-term-memory-a-detailed-walkthrough-of-the-lstm-algorithm-93ac6c782221">previous blog</a>, we saw how the LSTM processes sequential information and the working mechanism of the LSTM cell. Similar to a neural network, the LSTM network also backpropagates its errors to tune its parameters, and just like the Recurrent Neural Network, it backpropagates through time (BPTT).</p><p>Here we will look at how the parameters are tuned in an LSTM during backpropagation.</p><p>Firstly, as we recall from the previous blog, the LSTM cell contains three gates and states. This is also shown in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*Y8V978OWLZ06sN3m66PHlw.png" /><figcaption><strong>Fig 1: LSTM Cell</strong></figcaption></figure><p>The three gates are represented by the equations below ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*93dO-68kM2n3zkyPOdM2mQ.png" /><figcaption><strong>Equation (i) — forget gate</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*7m-w2QMMVDKrT8zm-MucUg.png" /><figcaption><strong>Equation (ii) — input gate</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*SY8UXKum5W8IR6hmkCFZCg.png" /><figcaption><strong>Equation (iii) — output gate</strong></figcaption></figure><p>The LSTM cell also consists of the cell states which are given by the following equations ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*axPTdjQ5st5CpxT4wlB6KA.png" /><figcaption><strong>Equation (iv)-Candidate gate</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*YVqb9hEf3w1Bp8_YU4hGow.png" /><figcaption><strong>Equation (v) — Update cell state</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*1OFaAExELRK4lpAO2w7m4Q.png" /><figcaption><strong>Equation (vi) — Update hidden state</strong></figcaption></figure><p>Now that we have the equations for the gates and states of the LSTM, we need to know the derivatives of the activation functions used. The LSTM uses only two activation functions</p><ol><li>Tanh activation</li><li>Sigmoid activation</li></ol><p>The following equations represent the derivatives of the above activations which will be helpful while computing our derivatives in further steps :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*PU85tjdSKCOF_3ip1twcgA.png" /><figcaption><strong>Equation (vii) — Derivation of tanh activation</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*_weCH8PW9vf1rAbyh2MCXQ.png" /><figcaption><strong>Equation (viii) — Derivation of sigmoid activation</strong></figcaption></figure><p>In this backpropagation, we will consider a binary classification task, where the loss is computed by the Categorical crossentropy loss function.</p><p>The equation for loss function is given as ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*HZf_3N69ZO3c6EhOMiFySg.png" /></figure><p>where L is final loss, which is the sum of the losses at each individual timestep t, <em>y(t)</em> is the actual label and <em>yhat(t)</em> is the predicted label.</p><p>We have the relevant equations all in place. As we backpropagate through the network, we want to update the weights which in this case are the tunable parameters.</p><p><strong>Wii</strong><em>, </em><strong>Wff , Woo, Wcc, Whh, Wi<em>x</em></strong><em>, </em><strong>Wfx , Wox, Wcx, Whx</strong></p><p>We will be using the gradient descent equation to update the weights parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*EaNYv2Ytfkv_Wxj3myKXdw.png" /><figcaption><strong>Equation (x) — Weight update using gradient descent</strong></figcaption></figure><p>Before we compute the gradients with respect to weights, we will be calculating some intermediate derivatives to make our finalderivation easier.</p><p>First, we will derive the equations with respect to the three states of the LSTM as given in equation (iv), (v) and (vi).</p><p>Let us compute the loss with respect to the hidden state <em>h(t),</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*-dnlLmP6eFRpdHkTvwc-Wg.png" /></figure><p>We need to find the relevant equations to compute the above derivative. To identify which equations are relevant, we find the equations containing <em>L</em> and <em>h(t) </em>as parameters<em>. </em>Therefore, we plug in the equations,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*HZf_3N69ZO3c6EhOMiFySg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*CNvoSHAPWQR8rI2tzVy_fQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*pDm4aiRlTLm47TPjXMUw8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*289s1rNjnptBkHbXg4PWZg.png" /></figure><p><em>Wₕₕ </em>is the weight matrix multiplied with the output from the final hidden state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*FEMN0zYGq6azBAyy4omTeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*T-HjOhKmhUFi9JcHGTVxvw.png" /><figcaption><strong>Equation (xi) — Derivative of Loss w.r.t to hidden state h(t)</strong></figcaption></figure><p>[<em>yhat(t) − y(t</em>)] is the softmax derivative.</p><p>Now that we have the derivative computed with respect to the hidden state, it is easier to obtain the derivative w.r.t the candidate state (<em>ˆC(t)</em>) and cell state (<em>C(t)</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*lC5kcWezydWlZpdxutCHcw.png" /></figure><p>To compute the above derivative we find the relevant equations. Along with the previous equations containing Loss (<em>L</em>) and <em>yhat(t), </em>we take Equation (vi) which contains the parameter <em>C(t).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*1OFaAExELRK4lpAO2w7m4Q.png" /><figcaption><strong>Equation (a)</strong></figcaption></figure><p>The derivative for the Loss w.r.t <em>C(t)</em> is given as ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*HSPB9xZ4mb-v68MZ-UQxrg.png" /><figcaption><strong>Equation (xii)</strong></figcaption></figure><p>The derivative of the first two terms can be obtained by referring to the Equation (xi)</p><p>The derivative of term three is given by differentiating equation a,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*holdbrFeApOXWpIj_ga0fg.png" /></figure><p>We can substitute the terms computed from equation (xi) and the above equation to calculate the final derivative of the Loss (<em>L</em>) w.r.t <em>C(t).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*f2z83-g_splX3OQh6kimTA.png" /><figcaption><strong>Equation (xiii) — Derivative of Loss w.r.t updated cell state C(t)</strong></figcaption></figure><p>Finally, we calculate the derivative w.r.t the last state which is the candidate state <em>ˆC(t)</em></p><p>To compute this, in addition to the equations used to compute the previous two hidden states, we will need one final equation which contains the parameter <em>ˆC(t). </em>This is given by the equation ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*YVqb9hEf3w1Bp8_YU4hGow.png" /><figcaption><strong>Equation (b)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*-u45KnCX4AvXLEHsM4eBrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*idfj85e7DhyGJkktDvlrkw.png" /></figure><p>Terms 1, 2 and 3 can be computed by the Equation (xiii). Term 4 can be obtained by differentiating equation b ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*w3brx5APiPruSh5YwI0vjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*aXp2fAJ2EBwpMBYQ7YDEqg.png" /><figcaption><strong>Equation (xiv) — Derivative of Loss w.r.t candidate state ^C(t)</strong></figcaption></figure><p>We have calculated all the derivatives w.r.t. the states of the LSTM cell represented by equations xi, xiii, xiv.</p><p>Continuing, we will now calculate all the derivatives w.r.t the three gates of the LSTM.</p><p>The derivative w.r.t the output gate is given as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*GsaOT8OefVQUz0Hmm2HM-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*339QNFsZj-EpoU7GR1woFQ.png" /></figure><p>The first two terms can be obtained from equation (xi). The third term can be computed by differentiating the equation of the output gate as given in equation (iii) where ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*D_k77n9pYU-WzssKto34XQ.png" /><figcaption><strong>Equation c — Derivative of h(t) w.r.t output gate</strong></figcaption></figure><p>The differentiation of the Loss w.r.t o(t) is given by ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*u_Dh3JNLz2MxhvotUv5QHw.png" /><figcaption><strong>Equation (xv)</strong></figcaption></figure><p>We have computed the derivative of the output gate, the derivatives for the input and forget gate can be obtained in a similar manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*w3brx5APiPruSh5YwI0vjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*wg_iQAFgy-TOFiyAoEQWCw.png" /></figure><p>The first three terms of the equation can be obtained from equation (xiii) and term 4 can be computed by differentiating cell state w.r.t. input gate where ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*iJViSN5HRr8Ff5atS9m39w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*d0i8HILNTMSGOXWNWfGd_w.png" /><figcaption><strong>Equation xvi — di(t) =Derivative of Loss w.r.t input gate</strong></figcaption></figure><p>The forget gate equation is given as ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*tz8Aboc1Vlsx8WCSqJJjGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*1DZiJbvfB_9zqQ0UEbk6eA.png" /></figure><p>The first terms again can be taken from equation (xiii) and the final term is computed by differentiating the cell state w.r.t forget gate given by the equation ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*GoTWnZfYwPS5QN-OSTilPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*R53uinN1GPKgIcFLvYTG6g.png" /><figcaption><strong>Equation xvii — di(t) =Derivative of Loss w.r.t forget gate</strong></figcaption></figure><p>Now that we have all the intermediate equations in place, we can compute the final gradients w.r.t the weights.</p><p>The loss wrt <strong>Wii</strong><em>, </em><strong>Wff , Woo, Wcc, Whh</strong>, is given as.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*cKoOAY5zU6xMh99U8aIucQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*uA8rwP7rwprRxzn0m-oqZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*2npOIBIASqgJctwI3MhCrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*pJc1nit449WNYlnhSVelTw.png" /></figure><p>We have already calculated the first term of all the above equations in the intermediate equations above. We will compute the second partial derivative for these terms which are given as ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*Wjoc8NOzBe9FZD4mPltr0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*JFLQ0_Q0zwjspK7AgpA6tg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*Bxf5wEKuMc7SSHQ5vQH9LA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*NFw7_cUwPXrELk0lJjglaw.png" /></figure><p>Therefore using these derivatives above we arrive at the final terms by simple multiplication ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*fOvpAM4m0RFao3xT4Asn9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*Eduavwgukfofg84_Zm3HXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*malNXtJAJU_sameoXSJ0-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*hurvL0AEOD6IyJgMQJedyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*T0WPSMKeCMZw1MeZx3qWhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*p8wWIa6D9geDjpqSBoucZw.png" /></figure><p>In a similar fashion, we can compute the final tunable parameters <strong>Wi<em>x</em></strong><em>, </em><strong>Wfx , Wox, Wcx, Whx</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*JHeXcbxMDdkj84pKLq4dpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*gU11ca0cbWefZ7XG7QlEXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*RoywbITwkMqe6bo3X8LZrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*Otp1RHGxEo4PgfoU3DA3_Q.png" /></figure><p>The only parameter change is that instead of h(t-1) we have x(t)</p><p>Therefore, all these parameters get tuned during the backpropagation of the LSTM. We can use gradient descent to update these weights.</p><p>I understand that this blog might have been technically heavy, but I hope that I could provide an understanding of LSTM backpropagation!</p><p>Stay tuned for the next blog!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=535a61cec396" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2a: Long Short Term Memory: A detailed walkthrough of the LSTM algorithm.]]></title>
            <link>https://medium.com/@shreyasingh18/part-2a-long-short-term-memory-a-detailed-walkthrough-of-the-lstm-algorithm-93ac6c782221?source=rss-f3927efcae1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/93ac6c782221</guid>
            <dc:creator><![CDATA[Shreya]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 06:29:02 GMT</pubDate>
            <atom:updated>2022-09-19T06:29:02.541Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@shreyasingh18/part-1-recurrent-neural-networks-a-detailed-walkthrough-of-the-rnn-algorithm-cde6a7d1f282">part 1</a>, we saw the drawbacks of the traditional RNN architecture; its inability to handle what is known as long range dependencies as well as gradient problems. While capturing past information in the RNN, all the inputs were mapped to a 1*H dimensional vector as discussed.</p><p>Therefore it was hard for the RNN to discern which information is from the past and which is from the current input, introducing difficulty in remembering longer sequences.</p><p>A solution was proposed by <a href="http://www.bioinf.jku.at/publications/older/2604.pdf">Hochreiter and Schmidhuber</a> in 1997 to solve this problem using the concept of Gating. Gating was introduced to help in the memoizing process in the conventional RNN.</p><p><strong>What are gates?</strong></p><p>Gates are neural networks that were introduced in Long Short Term Memory (LSTM) networks and Gated Recurrent Units (GRUs) to regulate the flow of information. While regulating, it makes a decision on which information is relevant and must be passed forward and information which has to be discarded. By keeping relevant information we can increase the accuracy of our predictions.</p><p>But what constitutes relevant information in a sequence?</p><p>Consider a longer sequence with the goal of sentiment prediction. In this case, we will take the example of a book review.</p><p><em>“This tale has all the elements of a most exciting story: an impenetrable riddle; the ambition and frustration of generations of hopefuls; and the genius who worked for years in secrecy to realise his childhood dream.</em></p><ul><li><em>Express on Simon Singh’s book — Fermat’s Last Theorem”</em></li></ul><p>In the above example if we had to conclude the sentiment of the reviewer on the book we would remember certain keywords such as exciting story, impenetrable riddle, genius etc.</p><p>This would correspond to a positive sentiment. Words such as “this”, “has”, “all” would be termed as irrelevant information.</p><p>The above example is the intuition behind what gates try to do. They discern these keywords from sequences to help in prediction whether it is the task of language translation, sentence completion, or sentiment prediction, among various other tasks.</p><p><strong>Introducing the Long Short Term Memory</strong></p><p>The LSTM network was introduced as an upgrade to the RNN architecture. Like the Recurrent Neural Network, it processes data sequentially i.e. each word in the sequence is fed into the network at a timestep <em>t.</em></p><p>The difference lies in the operations which are taking place within the LSTM cell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aMoKgJrywvRaUqWHJM9YOw.png" /><figcaption><strong>Fig 1: Comparison between the cell architecture of the RNN vs LSTM</strong></figcaption></figure><p>As shown in the diagram above, the RNN contains an activation function that is mostly tanh in its nature i.e. it squishes the input values from the current time step <em>xₜ </em>and previous timestep <em>hₜ</em>-₁ to a range of -1 to 1. This represents the updated hidden state <em>hₜ </em>that is passed on as input in the next timestep.</p><p>Similar to the RNN, each state or cell state of the LSTM is a snapshot of the same cell across multiple timesteps.</p><p>The internal mechanism of the LSTM however is more sophisticated in nature. It contains three gates in one cell ;</p><ol><li>Forget Gate</li><li>Input Gate</li><li>Output Gate</li></ol><p><strong>Activation functions in the LSTM</strong></p><p>These gates as mentioned above are simple neural networks which contain one node. This node is activated by functions which are generally sigmoid or tanh activation functions.</p><p>But why do these gates contain sigmoid or tanh functions as opposed to other options for activation functions which are present?</p><p>First lets talk about the need for activation functions in any neural network.</p><p>They are used to introduce a component of non linearity in the network. The output from a node without an activation function is linear is nature where ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*RYcAOya3lzRl1ZRF2eIujA.png" /></figure><p>Therefore, without activation functions, the network will try to estimate linear patterns in the data and may not capture important non-linear patterns. This is where the tanh and sigmoid functions come in.</p><p>The tanh function squishes the values obtained from -1 to 1 therefore preventing any input vector values from becoming astronomical as it is propagated across the network. Therefore in addition to serving their purpose of introducing the component of non-linearity these activation functions also help scale vector values as they move across the timesteps.</p><p>These activation functions are also crucial during backpropagation to eliminate the problem of vanishing and exploding gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*C4g49va1ktHOpmd-T0VAew.png" /></figure><p>The sigmoid function on the other hand squishes values between 0 and 1 and is an important component in the forget gate of an LSTM. An output value of zero indicates that the information must be discarded, while that of 1 implies that the information is important and must be kept.</p><p>Now lets deep dive into the internal mechanism of the LSTM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*Y8V978OWLZ06sN3m66PHlw.png" /><figcaption><strong><em>Fig 2: LSTM Cell state</em></strong></figcaption></figure><p>The figure above represents an LSTM cell. Let’s break it down one by one and try and understand the flow of information.</p><p>The LSTM cell takes in two inputs</p><ol><li>Previous cell state (<em>Cₜ-</em>₁) — which is associated with Long term memory</li><li>Previous hidden state (<em>hₜ</em>-₁) — which in combination with the current input <em>xₜ</em> is associated with the short term memory.</li></ol><p>The previous hidden state (<em>hₜ</em>-₁) is more associated with the information from only the previous timestep while the previous cell state (<em>Cₜ-</em>₁) carries forward the information from all previous timesteps or cell states forward into the network. We will discuss this more in detail once we understand the flow of information through the gates</p><p><strong>In gating there are three main components ;</strong></p><p>Every cell state is evaluating information from the past, present and future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*wthppbcct4sUucxMozFpdQ.png" /><figcaption><strong><em>Fig 3: Three different components of gating in an LSTM</em></strong></figcaption></figure><p><strong>Gates of the LSTM</strong></p><ol><li><strong>Forget gate</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*rC3yMjrh6CwjLEpxDmQGrw.png" /><figcaption><strong>Fig 4: Forget gate of the LSTM</strong></figcaption></figure><p>The forget gate is the first gate of the LSTM cell. It serves the purpose of deciding which information is relevant from the past i.e. it has to do with past information from sequences.</p><p>The input to the forget gate is the current input from the timestep <em>xₜ </em>and the hidden state from the previous timestep <em>hₜ</em>-₁. This combined vector representation is fed into the sigmoid activation function which outputs values between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*Hg73Ra9Nf7oToDb1XUPnJw.png" /></figure><p>The output <em>f</em>ₜ is multiplied by the previous cell state <em>Cₜ-</em>₁. The resulting output helps us determine which information from the past is needed to update the current cell state.</p><p>While <em>hₜ</em>-₁ contains information to be carried into the future, <em>Cₜ-</em>₁ contains past information that is forgotten using forget gate 1 in the processing of the next timestep.</p><p>Therefore, forget gate 1 uses the current input <em>x</em>ₜ and <em>hₜ</em>-₁ to decide how the input from the current timestep will influence the past. To summarize, it helps in forgetting components of the long term memory given the previous hidden state and the new data point in the sequence.</p><p><strong>2. Input Gate</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*FOeHH0JQAt7yTH5MNh_h3A.png" /><figcaption><strong>Fig 5: Input gate of the LSTM as highlighted in blue</strong></figcaption></figure><p>The input gate is used to update the cell state of the LSTM. It is a combination of two networks that contains a tanh activation function and one which contains the sigmoid. The current timestep input <em>x</em>ₜ is fed into the input gate which is passed through the tanh to represent values between -1 and 1.</p><p>The same input is also fed to the sigmoid network which can be understood as forget gate 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*tZZGPaUzeR3wa0zDzMUVwQ.png" /></figure><p>This output from forget gate 2 is multiplied by the output values from the tanh activation to decide which information from the present is important.</p><p>Finally, we update the cell state by multiplying the following equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*_nJxuevVi60YWJlzmDi37w.png" /></figure><p>The above equation represents the updated cell state of the LSTM</p><p><strong>3. Output Gate</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*FOeHH0JQAt7yTH5MNh_h3A.png" /><figcaption><strong>Fig 6: Output gate of the LSTM cell as highlighted in red</strong></figcaption></figure><p>This is the final gate of the LSTM network and helps in arriving at the next hidden state at the consecutive timestep. The output gate is again coupled with two networks, one of a sigmoidal nature which we will call forget gate 3 and another tanh network.</p><p>The output of the updated cell state is passed through the tanh function. The input <em>x</em>ₜ and <em>hₜ</em>-₁ are given to forget gate 3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*NU8fod66-ZRd4Qc1ybVeCA.png" /></figure><p>Finally, to obtain the new or updated hidden state <em>hₜ</em> the output of the above two equations are multiplied. The vector from the current cell state is multiplied to see what information to be kept. When we perform vector multiplication with the output values from <em>Oₜ</em> we get a range of values from 0–1. Finally the ones which are 0 are not carried forward to the updated hidden state.</p><p>Hence as discussed above, we have the Long Term Memory which is the Cell state and the Short Term Memory in the form of the hidden state which is passed as input at the next timestep to the cell.</p><p>The line at the top of the figure 2 represents a highway that shows how the cell state is updated and key information is propagated across cell states of the LSTM.</p><p><strong>Sequential data processing in an LSTM</strong></p><p>How is sequential data processed in an LSTM? We will see it in the following two examples</p><p>Example 1: Sentiment prediction on a book review.</p><p><em>“The book was amazing. It lived up to its expectations”</em></p><p>Now the above review sounds positive. But which words made sure that the overall sentiment is positive?</p><p>“<em>Amazing</em>”, “<em>lived up</em>” are some of them.</p><p>These keywords as extracted above are stored in the long term memory <em>Cₜ </em>and is carried forward as shown in the figure below. Therefore, just before making the prediction using a softmax we have these keywords from long term memory to help us decide that the sentiment is positive.</p><p>Hence, the LSTM can pass the initial cell state all the way to the end and is good at memorizing values for a longer time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*PZyXnPp768rUtvAakmLAWA.png" /><figcaption><strong>Fig 7: Keywords passed through long term memory in an LSTM</strong></figcaption></figure><p>Example 2: Now let us consider the same review but let the sentence change in the second half.</p><p><em>“The first book was amazing. The sequel however was disappointing in comparison”</em></p><p>In this example, initially, the word “<em>amazing</em>” will be identified as a keyword by the LSTM cell. However, as we progress we see that the review gets negative. In such a case, the information held by the cell state <em>Cₜ</em> will have to be discarded in the next timestep and be replaced by “<em>disappointing</em>”.</p><p>The word “<em>amazing</em>” will be discarded with the help of the forget gate while the word “<em>disappointing” </em>will be passed into the updated cell state by means of the input gate. Now the LSTM will have enough context to know that the overall sentiment is negative.</p><p>In conclusion, the LSTMs were an improvement on the standard RNN because of the ability to hold data for many states. Short term data would be stored for longer periods of time making the overall architecture much more sophisticated and robust.</p><p>In the next sub part , I will cover how backpropagation works in an LSTM and how the weights of the different gates are updated.</p><p><strong>Meanwhile hope this was helpful and stay tuned for the next one!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93ac6c782221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: Recurrent Neural Networks: A detailed walkthrough of the RNN algorithm.]]></title>
            <link>https://medium.com/@shreyasingh18/part-1-recurrent-neural-networks-a-detailed-walkthrough-of-the-rnn-algorithm-cde6a7d1f282?source=rss-f3927efcae1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cde6a7d1f282</guid>
            <dc:creator><![CDATA[Shreya]]></dc:creator>
            <pubDate>Thu, 18 Aug 2022 12:17:40 GMT</pubDate>
            <atom:updated>2022-08-18T12:17:40.954Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>In part 1, I will cover</strong></p><ul><li><strong>Introduction to sequential data and the RNN</strong></li><li><strong>Single Forward Pass of the RNN</strong></li><li><strong>Concept of shared parameters</strong></li><li><strong>Backpropagation Through Time (BPTT)</strong></li><li><strong>Vanishing and Exploding gradients</strong></li><li><strong>Truncated Backpropagation Through Time (TBPTT)</strong></li><li><strong>Disadvantages of the RNN and why gating was introduced</strong></li></ul><p>Before we try and understand the Recurrent Neural Network, it is important to understand sequential data. In the past, Hidden Markov Models (HMMs) which are statistical models, were used for the processing and understanding of sequential data/information.</p><p>As the name suggests, a sequence contains information that is ordered in a particular way. These can be sentences, audio clips, videos, or DNA sequences as well.</p><p>Now when it comes to sequence prediction, the assumption lies that if we have certain past knowledge, it would be easier to complete the sequence. Take into consideration the standard example of the motion of a ball and the goal to predict which way the ball is going to move. If we only have knowledge of the current state of the ball, we could take into account the probability of it going in any direction, each guess or prediction would give us an equal probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*_RqJr44FDFTZX41X3d4Aww.png" /><figcaption>Fig 1: Predicting the direction of motion of the ball</figcaption></figure><p>But if you have past information about the motion of the ball, it is much easier to predict the direction it will move in. Similarly, if we have past information on sequences it is much easier to carry out tasks such as sequence prediction, language translation, sentiment analysis, and so on.</p><p>In HMMs, the assumption that the current state is dependent only on the previous step made longer sequences difficult to model.</p><h3>Introducing the Recurrent Neural Network</h3><p>The RNN is one of the first algorithms that remembers its input due to something called an internal memory. It also introduces an interesting concept of that of time which is not present in Feed Forward Neural Networks (FFNs).</p><p>But why is it called Recurrent?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*LELZbLHRDy_b0j3xvEdq9Q.png" /><figcaption>Fig 2: Feed Forward Network vs Recurrent Neural Network</figcaption></figure><p>The idea of the RNN being recurrent is in the way that information is channeled across the network. In the Feed Forward Neural Network as suggested by the name, the flow of information is in the forward direction, i.e. it is unidirectional in nature.</p><p>The same information never touches a node twice. However in an RNN as seen in figure 3, we see a loop feeding the output back into the node/neuron. At every timestep the same task is being performed for every element of the sequence in an RNN and the output is dependent on previous computations. However, not to get too ahead with the concept of timesteps and similar task computations, the word “<strong>recurrent</strong>” is purely due to the reason that an output generated is fed back into the neuron.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*x6ISbPnTt0yJlg0Z9FfTbw.png" /><figcaption>Fig 3: Rolled Recurrent Neural Network</figcaption></figure><p>The figure that you see above is that of a rolled RNN. A rolled RNN is the compact representation of the processing of different inputs in a sequence. One significant change in the RNN as mentioned above is the concept of time. Here the input sequence is processed by the same node at different timesteps. Information processed at these timesteps is fed forward so that the RNN can have information from the past as well as the present. To understand this in detail we will look at the unrolled RNN.</p><p>First, let us try and summarize the equation of the rolled RNN ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJ-Nvp9I1eDgkrrN2dzprQ.png" /></figure><p>On analyzing equation (i) we can see that the same parameter and function are used at every timestep. To get the output for a timestep we take into account the input vector at the current timestep which is denoted by <em>xₜ</em> and the information from the timestep previous to it which is denoted by <em>hₜ</em>-₁. The function <em>f(w)</em> is applied to these parameters to get the updated state / new state <em>hₜ</em>.</p><h4>Single forward pass of the RNN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*p1dXongZm-qDKkHQMaF9Eg.png" /><figcaption>Fig 4: Architecture of the unrolled RNN</figcaption></figure><p>The figure 4 shows what the unrolled structure of the RNN looks like. We will look at how a sequence is processed. Take any use case, in this example, I will take one of sentiment analysis to demonstrate sequential processing in the unrolled RNN.</p><p>Say my sequence is “I love cookies”. The word “I” will get processed at an input timestep of <em>x₀</em> at <em>t</em>=0. Next, the word “love” will be fed into the same neuron at an input timestep of <em>x₁</em> at <em>t=</em>1. Once the word “love” is fed into the neuron, the output of the processed word “I” from timestep t=0 is also fed along with the word “love” into the neuron. Therefore now we have past as well as present information where “I” from h₀ and “love” from <em>x₁</em> are being fed into the neuron. These are then mapped together into a vector of 1*H dimensional vector. Similarly while processing the last word “cookies” we have information about the input word “cookies” denoted by <em>x₂</em> as well as past information from the words “I” and “love” denoted by <em>h₁</em>. Now if I want to predict my sentiment towards cookies I can pass my output <em>h₁</em> to a softmax function and get my result.</p><p>Therefore the unrolled RNN consists of these layers, which are <strong>snapshots</strong> of the same cell/neuron of the RNN at different steps in time.</p><p>By channeling forward the outputs generated from sequences in the initial layers/timesteps, we are able to carry out sequential prediction much more robustly. The concept of the internal memory as well of the RNN is just the output from a timestep (t) being fed forward at a timestep (t+1) when the next word is also being fed into the same cell. The final output is therefore affected not only by the last word in the sequence but by those in the initial layers/timesteps as well.</p><h4>Concept of weights and shared parameters</h4><p>Unlike the Feed Forward Neural Network (FFN), the weights parameter of the Recurrent Neural Network is shared across time i.e. the same weight matrix is multiplied at every timestep.</p><p>These weights are adjusted during Backpropagation Through Time (BPTT). The multiplication of sequences by the weights is shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*LOq3lLIC9meEI_6M0W-5xw.png" /><figcaption>Fig 5: Weight matrices in the RNN</figcaption></figure><p>In an RNN, there are three major weight matrices that are of significance ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*VaE_jMYSIJbBNM16ZwjS0g.png" /></figure><p>There are outputs generated at intermediate layers or timesteps multiplied by the same weights which we will see further during backpropagation through time.</p><p>But why are weights shared across an RNN?</p><p>The practical answer relies on the generalization of sequences to unseen lengths and the computational costs associated with having different weights associated with different words in a sequence. In the case of having training data where sequence lengths consist of 10 words and test data consists of 5 words, a different weight being associated with these 10 words the RNN would find it difficult to generalize well on a sequence containing 5 words.</p><p>The assumption made during parameter/weight sharing, which is often used interchangeably in the case of the RNN, is that sequential information contains words or inputs related to each other. In such a case, it makes logical sense to multiply sequential information by the same weights.</p><p>In argument, consider the Feed Forward Neural Network of Housing Price Prediction with three features ;</p><ol><li>Area of the house</li><li>Number of Bedrooms</li><li>Number of Bathrooms</li></ol><p>Treat this as a classification task wherein the input features will determine whether or not a house is bought. Each feature independently goes as input feature vectors to the Neural Network. In the beginning, while feeding the data into the network, there is no prior assumption made that these features dependently affect the outcome of the classification problem. However, there are non-linear relationships between these features that we model in intermediate layers using activation functions, weights, and biases.</p><p>While not truly independent, there is no complete dependency established between the features going as input into a Feed Forward Neural Network (FFN).</p><p>If a sequence containing words is fed as individual features to an FFN it will be associated with different weights and will never truly capture the context. Two sentences conveying the same meaning such as ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*HnsUvg69U0ey7tW7xedRqg.png" /></figure><p>may have the same meaning but in an FFN different weights and biases allotted during the forward pass may not be able to capture the context of both sentences. While backpropagation as well, the adjustments of the weights and biases parameter, will be in a way to see how every individual word impacts the output of the classification/translation task.</p><p>Hence, in such a case it becomes ideal to process sequences at different stages in time with past and current information about the data.</p><h4><strong>Backpropagation Through Time (BPTT)</strong></h4><p>So far, we have seen a single forward pass of the RNN algorithm. Similar to Feed Forward Neural Networks, a backpropagation of the error occurs in the RNN as well to adjust the parameters. This parameter adjustment is done to minimize the error generated between the actual label versus the predicted label. In contrast, the Backpropagation in an RNN is done through time, hence the name Backpropagation Through Time.</p><p>BPTT is the training algorithm that is used to update weights in the Recurrent Neural Network.</p><p>If the forward pass is happening across timesteps t₀ to t₃, backpropagation will happen from t₃ to t₀. It will unroll on all input timesteps. Therefore BPTT is the backpropagation that happens on an unrolled RNN architecture.</p><p>Since we generate an input and output at every timestep, we calculate and accumulate the errors across each timestep. The network is then rolled up and the weights are updated.</p><p>Updated equation with the weights ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*krW5ZxYEZRdHiw0F-7A7Rw.png" /></figure><p>Equation (ii) is the expanded version of equation (i) with the multiplication of the weights demonstrated. The weights <em>wₕₕ</em> and <em>wₕₓ</em> remain the same and are multiplied with the input sequence at different timesteps from <em>t₀</em> to <em>tₙ</em> where n = the total number of input sequences.</p><p>The weight matrix <em>wₕₕ</em> is always multiplied by the output from the previous timestep i.e. <em>hₜ</em>-₁, while the weight matrix <em>wₕₓ</em> is multiplied with the input sequence at the current timestep which is <em>xₜ</em>.</p><p>How exactly is backpropagation done and which weights are updated?</p><p>Taking the same example of sentiment analysis, say you want to predict the sentiment of a sequence of input sentences. We pass the final output of the last timestep through a softmax function to get a predicted label denoted by P.</p><p>Softmax equation ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*uZJ6PDGJ-scIC-Yx1e11Jw.png" /></figure><p>The final timestep is multiplied with the weight matrix wᵧₕ to get the predicted label P.</p><p>Now consider 3 timesteps ;</p><p>Since we are doing a sentiment classification task of 1/0 let the Loss function be categorical cross-entropy.</p><p>Categorical cross entropy equation ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*SOZEJCB5v-oO8qcRlkB1wA.png" /></figure><blockquote>Note : P is the predicted label</blockquote><p>During backpropagation there are three parameters that are updated ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*5es9isxeZ_7F8SPKCapgMA.png" /></figure><p>Since it is a classification problem, the easiest weight to update is <em>wᵧₕ</em> since it appears only in the final timestep and hence the gradient is easier to derive.</p><p>The derivative of the Loss function (L) in equation (iv) with respect to <em>wᵧₕ</em> is computed ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*68wt7ayAvdkOe3923CNgyw.png" /></figure><p>We see from equation (iv) that the Loss is directly related to predicted label P, hence we can use the chain rule to derive the gradient above;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*AK5w8OVAmYUiU0TMWZFtcw.png" /></figure><p>Updation of the weight <em>wᵧₕ</em>;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*BGbII0NkyKWn6QIMwhbyDg.png" /></figure><p>Where is the learning rate.</p><p>The adjustment of weights <em>wₕₕ</em> and <em>wₕₓ</em> is slightly more complicated since these weights appear in every layer of the RNN.</p><p>The gradient of the loss with respect to <em>wₕₕ</em> can be denoted as;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*fJzU3ZMo5lnBugH3imN9cA.png" /></figure><p>similarly, the loss with respect to <em>wₕₓ</em> can be denoted as;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*CR7YKn3xR6r_EntTEE0HLw.png" /></figure><p>From equation (iv) we know that the categorical cross-entropy loss is related to the Predicted output (P), which in turn is related to the output of the last timestep in this case <em>h₃.</em> This in turn is also dependent on <em>h₂</em> and <em>h₁</em> and all these parameters are multiplied by the weight matrix <em>wₕₕ</em>.</p><p>The equation for updating the weight <em>wₕₕ</em>;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*4SnnMupFhCavk9KvDIgzEA.png" /></figure><p>This equation (vii) can be written as ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*er39isxX0RYS3XD-qDdX1Q.png" /></figure><p>The weight update for <em>wₕₓ</em> is similar to <em>wₕₕ</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*nPGhcjeN5nedfrYbizmKpg.png" /></figure><p>This equation (ix) can be written as ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*b58LEHpG9ho7KurisP5ZDg.png" /></figure><p>We now know how all weight matrices are updated during the backpropagation of the RNN.</p><p>The above use case was for sentiment classification and hence the loss from the outputs generated by the intermediate layers/timesteps were not considered. If we want to make a final classification prediction, we don’t need losses at every point. However, some may argue that taking the intermediate losses helps in training the earlier layers better. In use cases involving many to many predictions such as language translation, multiple losses can be considered such as <em>L₁, L₂, L₃</em> where;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*V-yRLEx6CWWqn3yu_Mgucw.png" /></figure><h4><strong>Vanishing and Exploding Gradients</strong></h4><p>We’ve explored the many different benefits of the RNN and how robust it is in modeling sequential data. But the RNN encounters problems during backpropagation which has been termed the vanishing gradient problem.</p><p>We know that the output of the RNN is affected by all input timesteps, no matter how much in the past they lie.</p><p>To get from <em>x₃</em> to <em>x₂</em> we have to multiply by the weight wₕₓ and similarly to backpropagate from <em>x₂</em> to <em>x₁</em> we multiply by the same shared weight which can also be called the recurring weight. The problem arises when all inputs <em>x</em> are multiplied by a relatively smaller weight matrix. The adjustment of all inputs will be small and since the earlier layers are dependent on the output from the final layers a small change in the final layers will cause the gradient to become even more smaller as it backpropagates to the initial layers. This will cause the gradient to vanish and the weight update will happen poorly.</p><p>The initial few words of the sequence will not get trained properly due to poor weight adjustment. A large number of epochs might be sufficient for a weight at <em>t</em> but insufficient at <em>t-3</em>, due to a low gradient. The output will be affected by untrained layers.</p><p>To overcome the vanishing gradient problem, several methods can be used</p><ul><li>Proper weight initialization such that gradient changes are not extremely small</li><li>Usage of Long Short Term Memory (LSTMs)</li></ul><p>The exploding gradient problem is inverse to the vanishing gradient problem. Since all input timesteps are multiplied by the same recurring weight wₕₓ, a large initial weight will start causing problems. The prior initialization of weights, if too high, may cause large changes in gradient as we backpropagate. This change will ultimately cause the gradient to explode. To curb the exploding gradient problem we can penalize the gradient, stop backpropagation after a certain duration especially if the weights are not getting updated, or keep a maximum limit.</p><p>Or, we can use the Truncated Backpropagation Through Time (TBPTT) algorithm.</p><h4><strong>Truncated Backpropagation Through Time (TBPTT)</strong></h4><p>The TBPTT was introduced not only to deal with the problem of the exploding gradient but also to reduce computational costs associated with backpropagation on long sequences.</p><p>In TBPTT, while the forward propagation happens for all <em>k1</em> timesteps, the backpropagation updates the weights for only a fixed number of timesteps [<em>k2</em> timesteps].</p><p>As suggested by the name, the input sequence is deconstructed into multiple subsequences. Those gradients not involved in a particular subsequence are dropped at the end of the subsequence as we move back in gradient computation. The hidden state of a subsequence is passed as input to the next subsequence.</p><p>The drawback of the TBPTT is that it favors short-term dependencies but it does not retrace the entire past data.</p><h4><strong>Disadvantages of the RNN and why gating was introduced</strong></h4><p>The major drawback of the RNN was the difficulty in capturing long-term dependencies in addition to encountering gradient problems. In the RNN while we capture past information, all the inputs are mapped to a 1*H dimensional vector. Therefore it is hard for the RNN to discern which information is from the past and which is from the current input.</p><p>A mechanism was needed to figure out relevant information from the current input and the previous hidden vector. Hence the concept of gates was introduced to make capturing long-term sequences more robust. The Long Short Term Memory (LSTMs) and the Gated Recurrent Units (GRUs) were introduced.</p><p><strong><em>I will cover this in my next blog. Stay tuned!!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cde6a7d1f282" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>