<?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 Mohammed Saim Quadri on Medium]]></title>
        <description><![CDATA[Stories by Mohammed Saim Quadri on Medium]]></description>
        <link>https://medium.com/@mohammedsaimquadri?source=rss-5aad7f3f4f6a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pdl1GPFzWhRF0NWfs78KTA.png</url>
            <title>Stories by Mohammed Saim Quadri on Medium</title>
            <link>https://medium.com/@mohammedsaimquadri?source=rss-5aad7f3f4f6a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 17:19:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohammedsaimquadri/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[How LSTMs Master Long-Term Dependencies]]></title>
            <link>https://medium.com/@mohammedsaimquadri/how-lstms-master-long-term-dependencies-ba3144480e4f?source=rss-5aad7f3f4f6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba3144480e4f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[lstm]]></category>
            <dc:creator><![CDATA[Mohammed Saim Quadri]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-06-17T14:01:03.443Z</atom:updated>
            <content:encoded><![CDATA[<p>In our last post, we exposed the fatal flaw of standard Recurrent Neural Networks (RNNs). While they brilliantly introduced the concept of processing sequences over time, they are plagued by the <strong>Vanishing Gradient Problem</strong>. As an error signal travels backward through a long sequence, it shrinks exponentially. The result? The network develops severe amnesia, completely forgetting the beginning of a sentence by the time it reaches the end.</p><p>If we want to process complex sequential data — like translating entire paragraphs or analyzing long documents — we need an architecture capable of learning <strong>long-term dependencies</strong>.</p><p>Today, we are looking at the ingenious engineering that fixed the RNN memory leak: the <strong>LSTM (Long Short-Term Memory)</strong> network.</p><h3>1. The Core Innovation: The Memory Cell</h3><p>Traditional RNNs suffer because their hidden state (h_t) is constantly being overwritten and squished through a tanh activation function at every single time-step.</p><p>LSTMs solve this by introducing a brand new, parallel pathway through the network called the <strong>Cell State (C_t)</strong>.</p><p>Think of the Cell State as a conveyor belt that runs straight down the entire length of the sequence with only minor linear interactions. It acts as an internal memory container that can hold information for an extended period without degrading.</p><p>Instead of a simple neural network layer, an LSTM node is a complex piece of machinery containing three distinct mechanisms called <strong>Gates</strong>. These gates selectively regulate the flow of information — deciding exactly what gets added to the conveyor belt, what gets deleted from it, and what gets read out.</p><h3>2. Dissecting the LSTM Gates</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPyW2W3Cx4rYmtY8XznwQA.png" /></figure><p>An LSTM utilizes four main parameters at any given time-step:</p><ul><li>x_t: The input at the current time-step.</li><li>h_{t-1}: The hidden state (output) from the previous time-step.</li><li>C_{t-1}: The memory cell value from the previous time-step.</li><li>C_t and h_t: The newly updated memory and hidden states that will be passed forward.</li></ul><p>Let’s walk through the exact mathematical sequence an LSTM uses to update its memory.</p><h3>Step 1: The Forget Gate (f_t)</h3><p>The first step is deciding what information from the past we no longer need.</p><p>The <strong>Forget Gate</strong> takes the previous hidden state (h_{t-1}) and the current input (x_t), concatenates them, multiplies them by a weight matrix (W_f), adds a bias (b_f), and passes the result through a Sigmoid activation function (sigma).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/0*rq7OWYY2ult_moIc" /></figure><p>Because the Sigmoid function outputs a value exactly between 0 and 1:</p><ul><li>A 0 means &quot;completely forget this piece of information.&quot;</li><li>A 1 means &quot;completely keep this piece of information.&quot;</li></ul><h3>Step 2: The Input Gate (i_t) &amp; Candidate Memory (tilde{C}_t)</h3><p>Next, the cell decides what <em>new</em> information needs to be added to the memory. This is a two-part process:</p><p>First, the <strong>Input Gate</strong> uses a Sigmoid function to decide <em>which</em> values we are going to update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/0*vWiikuJ3OpuORagQ" /></figure><p>Simultaneously, a tanh layer creates a vector of new candidate values, called <strong>Candidate Memory (tilde{C}_t)</strong>, that could potentially be added to the state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/0*C6F6-YYxsvLNuV9T" /></figure><h3>Step 3: Updating the Cell State (C_t)</h3><p>Now, we have everything we need to actually update the conveyor belt.</p><p>We take the old cell state (C_{t-1}) and multiply it pointwise by the Forget Gate (f_t). This officially drops the information we decided to forget in Step 1.</p><p>Then, we add the Input Gate (i_t) multiplied by the Candidate Memory (tilde{C}_t). This regulates and scales the new useful information before dropping it onto the conveyor belt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/0*vhkopN-6qTJ8oeGq" /></figure><h3>Step 4: The Output Gate (O_t) and New Hidden State (h_t)</h3><p>Finally, the LSTM must decide what to output for this specific time-step (which also serves as the hidden state passed to the next node).</p><p>The <strong>Output Gate</strong> uses a Sigmoid function to determine which parts of the newly updated cell state (C_t) are going to be output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*JyoLPTRSyKP4YxS3" /></figure><p>We then push the new cell state (C_t) through a tanh function (to push the values between -1 and 1) and multiply it by the Output Gate to get our final hidden state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/0*xEHNIyoSSbsy59P_" /></figure><h3>3. Notable LSTM Variants</h3><p>The standard LSTM architecture is highly effective, but researchers have tweaked it over the years to optimize specific flows of information:</p><ul><li><strong>Peephole Connections:</strong> Introduced by Gers &amp; Schmidhuber, this variant allows the gate layers (f_t, i_t, O_t) to “peek” directly at the cell state (C_{t-1}) when making their gating decisions, rather than relying solely on the hidden state and input.</li><li><strong>Coupled Input and Forget Gates:</strong> Instead of making separate decisions about what to forget and what to add, this variant ties them together. It only forgets information when it has something new to input in its place:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*L4Y_WiNqPsy812GY" /></figure><h3>4. The Gated Recurrent Unit (GRU): A Leaner Alternative</h3><p>While LSTMs successfully solved the vanishing gradient problem, they came with a cost: high computational complexity. Calculating four separate gates at every single time-step requires a massive amount of memory and processing power.</p><p>In 2014, researchers introduced a streamlined, highly efficient alternative: the <strong>Gated Recurrent Unit (GRU)</strong>.</p><p>The basic idea behind a GRU is to use gating mechanisms to selectively update the hidden state, just like an LSTM, but with a simplified architecture. The most significant difference? <strong>A GRU does not maintain a separate internal cell state (C_t).</strong> The long-term memory is incorporated directly into the standard hidden state (h_t), which is passed to the next unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udIAeW3SwCvklN71atQ3jA.png" /></figure><p>Instead of four gates, the GRU operates using only three:</p><h3>1. The Update Gate (z_t)</h3><p>Analogous to the Output Gate in an LSTM, the Update Gate determines exactly how much of the past knowledge needs to be passed along into the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/0*ZUaDXuM8d3rFsnug" /></figure><h3>2. The Reset Gate ($r_t$)</h3><p>Analogous to a combination of the Input and Forget gates in an LSTM, the Reset Gate determines how much of the past knowledge the network should forget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/0*mxAAakOYhqh_YQIY" /></figure><h3>3. The Current Memory Gate (tilde{h}_t)</h3><p>Just like the candidate memory in an LSTM, this sub-part introduces non-linearity to the input. However, it incorporates the Reset Gate (r_t) directly into its calculation to reduce the effect that previous information has on the current information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/0*zKg7MK1mnUrkD0C5" /></figure><h3>The Final Hidden State (h_t)</h3><p>To calculate the final output, the GRU elegantly balances the old hidden state and the new candidate state using the Update Gate (z_t):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*xCcttwicEu3-UYro" /></figure><p>Because they have fewer tensor operations, GRUs train significantly faster than LSTMs and perform exceptionally well on smaller datasets, making them a favorite for modern NLP tasks.</p><h3>5. Bidirectional RNNs: Reading the Future</h3><p>Up until now, every architecture we have discussed shares one fundamental limitation: they process text strictly sequentially from left to right. At time-step t, the network only has context from the words that came <em>before</em> it.</p><p>Imagine trying to understand the word “bank” in this sentence:</p><p><em>“I sat by the bank of the river.”</em></p><p>If the model is reading the word “bank,” it only knows the context <em>“I sat by the”</em>. It hasn’t seen the word <em>“river”</em> yet, so it might incorrectly assume you are at a financial institution. In language, context relies heavily on the words that come <em>after</em> the target word.</p><p>To solve this, we use a <strong>Bidirectional RNN (BRNN)</strong>.</p><h3>How BRNNs Work</h3><p>A BRNN processes the input sequence in both the forward and backward directions simultaneously. It achieves this by using <strong>two distinct recurrent layers</strong>:</p><ol><li><strong>Forward Layer:</strong> Processes the input sequence from start to finish (x_1 → x_T).</li><li><strong>Backward Layer:</strong> Processes the exact same input sequence in reverse (x_T → x_1).</li></ol><h3>The Mathematics of BRNNs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yI8CN9AIp5YI8iVWwIQdxQ.png" /></figure><p>At any given step, the network calculates two independent hidden states using non-linear activation functions (A):</p><p><strong>1. Forward Hidden State:</strong> Calculated using the current input (X_t) and the previous time-step’s forward hidden state (H_{t-1}).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0GavYpHkC_m8N8gD" /></figure><p><strong>2. Backward Hidden State:</strong> Calculated using the current input (X_t) and the <em>next</em> time-step’s backward hidden state (H_{t+1}).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KXiMzDEz_pRo0WwE" /></figure><p><strong>3. The Final Output (y_t):</strong></p><p>To make a prediction, the network combines both the forward and backward hidden states into a single, highly informed vector (H_t). This combined vector is multiplied by the output weights (W_{Hy}) and a bias (b_y) is added:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/0*ZwL3CIDwfi0ppyIJ" /></figure><p>By reading text in both directions, BRNNs, specifically Bidirectional LSTMs (BiLSTMs), became the absolute gold standard for Named Entity Recognition, sentiment analysis, and translation.</p><h3>Final Thoughts</h3><p>By evolving from standard RNNs to LSTMs and GRUs, and finally stacking them into Bidirectional layers, we gave neural networks the ability to possess long-term memory and read text with deep contextual understanding.</p><p>For years, this was the absolute peak of Natural Language Processing. But despite their brilliance, recurrent networks have a fatal flaw: <strong>they are incredibly slow.</strong> Because step t requires the output of step t-1, you cannot parallelize their training on modern GPUs. You have to wait for the sequence to process one word at a time.</p><p>To build the massive, billion-parameter models we see today, the AI community had to abandon recurrence entirely. They needed an architecture that could look at an entire paragraph all at once, understanding the context of every word simultaneously.</p><p>They needed <strong>Attention</strong>. The basics of which we will look into in the next blog, Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba3144480e4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Neural Networks (ANN) vs. Recurrent Neural Networks (RNN)]]></title>
            <link>https://medium.com/@mohammedsaimquadri/artificial-neural-networks-ann-vs-recurrent-neural-networks-rnn-79eaa59988bf?source=rss-5aad7f3f4f6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/79eaa59988bf</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Mohammed Saim Quadri]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-06-16T14:01:03.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xhfK3yxd4VoUXz1a" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=medium&amp;utm_medium=referral">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In our last post, we discovered a glaring issue with classical text vectorization methods like Average Word2Vec: they strip away the order of words entirely. By collapsing a sentence into a flat average, the sequence is lost, and in natural language, <strong>sequence is everything</strong>.</p><p>Standard Artificial Neural Networks (ANNs), also known as Feedforward Neural Networks , are fundamentally blind to sequences. To handle text, time-series forecasting, audio signals, or video frames, we have to transition to a completely different paradigm. Today, we will break down why traditional ANNs fail at sequential data, introduce the foundational mechanics of <strong>Recurrent Neural Networks (RNNs)</strong>, and look at how they use mathematical loops to maintain a memory.</p><h3>1. Why Standard ANNs Fail at Sequential Data</h3><p>To understand why we need RNNs, we first have to look at the structural limitations of a standard feedforward architecture.</p><pre>[Input Layer] ──&gt; [Hidden Layers] ──&gt; [Output Layer]</pre><p>Traditional ANNs operate on a few fixed rules:</p><ul><li><strong>Fixed Input and Output Sizes:</strong> An ANN requires its input vector to have a rigid, predefined dimension (e.g., exactly 784 pixels for an image or a fixed vocabulary size for text). However, real-world sequential data like sentences or time-series data fluctuate wildly in length. A tweet can be 5 words; a book chapter can be 5,000 words.</li><li><strong>Independent Processing (No Memory):</strong> Standard networks assume that every input is completely independent of the previous one. When an ANN processes a word in a sentence, it has zero context or memory of the word that came before it. It treats the text as a flat snapshot rather than a continuous stream.</li></ul><p>This lack of temporal awareness makes it impossible for an ANN to track context across time or sequence steps.</p><h3>2. Enter Sequential Data and Time-Steps</h3><p>Sequential data is any data where the order of the data points matters just as much as the values themselves. In machine learning, we represent this progression using <strong>Time-Steps (t)</strong>.</p><p>Instead of feeding an entire block of text into a model all at once, sequential models process data step-by-step over time.</p><ul><li>At t = 1, the model reads the first token (x_1).</li><li>At t = 2, the model reads the second token (x_2).</li><li>At t = 3, the model reads the third token (x_3).</li></ul><p>To successfully process this data, our network needs a mechanism that can carry information across these discrete intervals. It needs a <strong>Hidden State ($h_t$)</strong> that acts as its short-term memory.</p><h3>3. The RNN Architecture: The Hidden State Loop</h3><p>A Recurrent Neural Network solves the memory problem by introducing a <strong>recurrent loop</strong> into its hidden layers. Instead of information flowing strictly forward from input to output, the hidden layer feeds back into itself.</p><h3>The Compact Representation</h3><p>In its simplest visual form, an RNN node looks like a standard neuron but with a circular arrow looping back into the hidden state:</p><pre>    ┌───┐<br>    │ ↺ │ Weights (Whh)<br>    └───┘<br>      ▲<br>      │ Weights (Wxh)<br>    [x_t] (Input at time t)</pre><p>This loop means that the output of a hidden layer at time-step t is fed back into the exact same hidden layer as an additional input for the next time-step, t+1.</p><h3>Unrolling the Network over Time</h3><p>To truly understand how an RNN operates during training, we can “unroll” or “unfold” this recurrent loop across the entire sequence length. When unrolled, the architecture reveals a sequential chain of operations:</p><pre>Time t=1:             Time t=2:             Time t=3:<br>   x_1                   x_2                   x_3<br>    │                     │                     │<br>    ▼ (Wxh)               ▼ (Wxh)               ▼ (Wxh)<br> ┌─────┐   h_1         ┌─────┐   h_2         ┌─────┐<br> │ RNN │ ────────────&gt; │ RNN │ ────────────&gt; │ RNN │ ──&gt; h_t<br> └─────┘     (Whh)     └─────┘     (Whh)     └─────┘<br>    │                     │                     │<br>    ▼ (Why)               ▼ (Why)               ▼ (Why)<br>   y_1                   y_2                   y_3</pre><p>At every single time-step t, the hidden layer is processing two distinct inputs simultaneously:</p><ul><li>The current input token vector at that exact step (x_t).</li><li>The hidden state vector from the immediately preceding step (h_{t-1}), which carries the historical context of everything the network has processed so far.</li></ul><h3>4. The Mathematical Core of an RNN</h3><p>Let’s look at the actual math happening inside each unrolled cell. Every RNN layer utilizes three sets of shared, trainable weight matrices:</p><ul><li>W_{xh}: Weights applied to the incoming input vector (x_t).</li><li>W_{hh}: Weights applied to the historical hidden state vector (h_{t-1}).</li><li>W_{hy}: Weights applied to the hidden state to compute the final output prediction (y_t).</li></ul><h3>Calculating the Hidden State (h_t)</h3><p>To compute the updated memory state at time t, we multiply our current input and past hidden state by their respective weights, add a bias term (b_h), and pass the sum through a non-linear activation function (typically <strong>Tanh</strong> to keep the values bounded between -1 and 1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*AMX_Z_5J8e2Z_f-1" /></figure><p>Calculating the Output (y_t)</p><p>Once the hidden state is updated, the network computes the output for that specific time-step by multiplying the hidden state by the output weights and adding an output bias (b_y):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*U85SavZr4nHSiO0V" /></figure><p><em>(Note: Depending on the task, the output activation could be a Softmax for word prediction or a Linear activation for regression forecasting).</em></p><h3>5. The Flexibility of RNN Architectures</h3><p>Because standard ANNs require fixed input and output sizes, they are rigidly locked into a “One-to-One” configuration. RNNs, on the other hand, can be dynamically structured depending on the sequential task at hand.</p><p>By manipulating where we feed inputs (x) and where we extract outputs (y) along the unrolled chain, we can build four distinct architectures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Owt-Pjch0R98rDhWOO_eJg.png" /></figure><h3>1. One-to-Many (Sequence Generation)</h3><ul><li><strong>How it works:</strong> A single input is fed into the first time-step, and the network generates a sequence of outputs across multiple subsequent time-steps.</li><li><strong>Use Case:</strong> <strong>Image Captioning.</strong> You feed the network a single image (One), and it outputs a descriptive sentence word-by-word over time (Many).</li></ul><h3>2. Many-to-One (Sequence Classification)</h3><ul><li><strong>How it works:</strong> A sequence of inputs is fed into the network over multiple time-steps, but the network only outputs a single, final prediction at the very end of the sequence.</li><li><strong>Use Case:</strong> <strong>Sentiment Analysis.</strong> You feed the network a 20-word movie review (Many), and at the final time-step, it outputs a single probability: Positive or Negative (One).</li></ul><h3>3. Many-to-Many (Sequence-to-Sequence / Seq2Seq)</h3><p>This is the most complex and powerful configuration, and it comes in two variations:</p><ul><li><strong>Aligned (Synced) Many-to-Many:</strong> The network takes an input and generates an output at <em>every single time-step</em>.</li><li><em>Use Case:</em> <strong>Video Frame Classification</strong> (labeling every single frame in a video as it plays).</li><li><strong>Encoder-Decoder Many-to-Many:</strong> The network reads an entire input sequence first to build up context, and only after the sequence ends does it begin generating an output sequence.</li><li><em>Use Case:</em> <strong>Machine Translation.</strong> It reads a full sentence in English (Many), processes the context, and then generates the translated sentence in French (Many).</li></ul><h3>6. How RNNs Learn: Backpropagation Through Time (BPTT)</h3><p>In our previous posts, we saw how standard Backpropagation uses the Chain Rule to trace errors backward from the output layer to the input layer.</p><p>RNNs use a variation called <strong>Backpropagation Through Time (BPTT)</strong>. Because an RNN relies on a historical hidden state, the error at the final time-step (t=3) isn’t just the fault of the input at t=3. It is also the fault of the hidden state from t=2, which was influenced by the hidden state from t=1.</p><p>To calculate the gradient, BPTT mathematically “unrolls” the network across all time-steps. It calculates the error at each step, and then accumulates (sums) the gradients backward through time.</p><p>If we want to update our shared hidden weight matrix (W_{hh}), the gradient is the sum of the partial derivatives at every single time-step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/0*mxKV3NM78KYw4WeX" /></figure><p>This means the network assigns blame not just across the layers, but <em>backwards through time</em>.</p><h3>7. The Flaw: Short-Term Memory and Vanishing Gradients</h3><p>While BPTT is mathematically sound in theory, it completely breaks down in practice on long sequences.</p><p>Remember the <strong>Vanishing Gradient Problem</strong> from our deep ANN post? We saw that multiplying a chain of tiny fractions (like the derivative of the Sigmoid function) caused the error signal to fade to zero.</p><p>RNNs suffer from an incredibly aggressive version of this exact same problem.</p><p>Look back at our hidden state formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*D3Io3H16sntCFPTJ" /></figure><p>Notice that the exact same weight matrix (W_{hh}) is multiplied at <strong>every single time-step</strong>.</p><ul><li>If the values inside W_{hh} are slightly greater than 1, multiplying them repeatedly across 50 time-steps causes the gradients to grow exponentially. This triggers the <strong>Exploding Gradient Problem</strong>, causing the model to crash (NaN).</li><li>If the values inside W_{hh} are slightly less than 1, multiplying them repeatedly across 50 time-steps causes the gradients to shrink exponentially into microscopic fractions. This triggers the <strong>Vanishing Gradient Problem</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUO2jElUXIvMz5hmbVFljA.png" /></figure><h3>The Consequence: Amnesia</h3><p>Because the gradient vanishes as it travels backward through time, the RNN fails to update its weights based on early inputs.</p><p>If you feed a basic RNN a 100-word paragraph and ask it a question about the very first sentence, it will fail. It suffers from <strong>short-term memory</strong>. As the sequence gets longer, the context from the early time-steps is slowly overwritten and mathematically diluted until it is completely forgotten.</p><h3>Final Thoughts: Fixing the Memory Leak</h3><p>Basic Recurrent Neural Networks were a massive leap forward. They introduced the concept of time, sequence, and memory to AI. But their mathematical inability to capture <strong>long-term dependencies</strong> made them useless for reading long documents or translating complex paragraphs.</p><p>To solve this, the Deep Learning community had to literally redesign the internal plumbing of the RNN node. They needed a cell that could selectively choose what to remember, what to forget, and how to pass critical information down the timeline without the gradient vanishing.</p><p>In our next post, we will look at the masters of sequential memory: <strong>LSTMs (Long Short-Term Memory).</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79eaa59988bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Word2Vec Decoded: Building Semantic Understanding with CBOW and Skip-grams]]></title>
            <link>https://medium.com/@mohammedsaimquadri/word2vec-decoded-building-semantic-understanding-with-cbow-and-skip-grams-4c13b1bd29aa?source=rss-5aad7f3f4f6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c13b1bd29aa</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Mohammed Saim Quadri]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-06-15T14:01:03.366Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wLSodN3xai-d1LI5" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In our previous post, we explored how classical NLP techniques like Bag of Words and TF-IDF process text. While effective for basic tasks, they suffer from a fatal flaw: they treat words as isolated, independent tokens. In a One-Hot Encoded matrix, the mathematical distance between “king” and “queen” is exactly the same as the distance between “king” and “apple.” The semantic meaning is completely lost.</p><p>To capture the true relationships between words, we need to map them into a dense, multi-dimensional vector space where context dictates mathematical proximity. We achieve this using <strong>Word2Vec</strong>.</p><p>Word2Vec is not a single algorithm, but a framework of deep learning architectures designed to learn word embeddings from massive datasets. Today, we are breaking down its two primary models :<strong>CBOW</strong> and <strong>Skip-gram</strong> , and exploring how we can scale these embeddings to represent entire documents.</p><h3>1. Continuous Bag of Words (CBOW): The Intuition</h3><p>The Continuous Bag of Words (CBOW) model learns embeddings by attempting to predict a hidden <strong>target word</strong> based entirely on its surrounding <strong>context words</strong>.</p><p>Imagine reading a sentence with a blank space and guessing the missing word based on the words immediately before and after it. That is exactly what CBOW does. It relies on a sliding <strong>Context Window</strong> of a fixed size that moves systematically through your entire text corpus.</p><p><strong>Example Breakdown:</strong></p><p>Consider the sentence: <em>“The cat sat on the mat.”</em></p><p>If we set our context window size to 2 (meaning we look at 2 words before and 2 words after the target), we can extract the following training data:</p><ul><li><strong>Target Word:</strong> sat</li><li><strong>Context Words:</strong> [&quot;The&quot;, &quot;cat&quot;, &quot;on&quot;, &quot;the&quot;]</li></ul><p>As the window slides across the corpus, the model continuously learns which words tend to predictably surround other words.</p><h3>2. The CBOW Architecture: How It Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHlv3ho4_BJBUBiOuNYzmw.png" /></figure><p>Word2Vec is uniquely elegant because it uses a <strong>shallow neural network</strong> — meaning it has only a single hidden layer. Here is the step-by-step pipeline of how CBOW processes data:</p><h3>Step 1: Input Encoding</h3><p>Before entering the network, each word in our vocabulary is converted into a standard One-Hot Encoded (OHE) vector. If our vocabulary size is 10,000, each context word becomes a 10,000-dimensional vector containing a single 1 and 9,999 0s.</p><h3>Step 2: Aggregation</h3><p>CBOW does not feed these context vectors into the network one by one. Instead, it aggregates them. The individual one-hot vectors of the context words are summed or averaged together to create a single, unified vector representation of the context.</p><p>For our previous example, the combined input vector might look something like this (simplified):</p><p>Aggregated Input = [1, 1, 0, 1, 1, 0]</p><h3>Step 3: The Neural Network</h3><p>The aggregated vector is fed into the shallow network:</p><ol><li><strong>Input Layer:</strong> Receives the aggregated context vector.</li><li><strong>Hidden Layer:</strong> A dense set of neurons (the size of this layer dictates the final dimensions of your word embeddings, e.g., 300 dimensions).</li><li><strong>Output Layer:</strong> Contains one neuron for every single word in your vocabulary. It uses a <strong>Softmax</strong> activation function to convert the raw network scores into a probability distribution.</li></ol><h3>Step 4: The Training Objective</h3><p>The model’s objective is to maximize the likelihood of predicting the correct target word given the context. It calculates the error between its prediction and the actual target word, and uses <strong>Stochastic Gradient Descent (SGD)</strong> and backpropagation to iteratively adjust the weights.</p><blockquote><strong><em>The Magic Trick:</em></strong><em> &gt; Here is the secret of Word2Vec, once the model finishes training, </em>we throw away the output layer entirely<em>. We do not actually care about the model’s ability to predict words. We only care about the </em><strong><em>weights between the input layer and the hidden layer</em></strong><em>. Those optimized weights </em>are<em> our final, dense word embeddings!</em></blockquote><h3>3. The Flip Side: Skip-gram</h3><p>While CBOW predicts a target word from its context, the <strong>Skip-gram</strong> architecture does the exact opposite: <strong>it predicts the surrounding context words given a single target word.</strong></p><p>Using our previous example, if the input to the network is the word sat, the Skip-gram model will attempt to output the probabilities for The, cat, on, and the.</p><p>While structurally similar to CBOW, Skip-gram is uniquely powerful. Because it generates multiple context predictions from a single word, it is forced to learn highly nuanced representations, making it much more effective at capturing the meaning of rare words compared to CBOW.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYWMgtAsDqIRQHgaVoy7Ig.png" /></figure><h3>4. Pros and Cons of the Word2Vec Framework</h3><p>Before integrating Word2Vec into your pipeline, it is important to understand its constraints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*o4r4atBgxyFSMpbAib-wig.png" /></figure><h3>5. Scaling Up: Avg Word2Vec</h3><p>Word2Vec is brilliant for individual words, but what if you are building a sentiment analysis model that needs to classify an entire review or document?</p><p>We can scale this architecture using <strong>Avg Word2Vec</strong>. This is an extension of the framework that generates a single mathematical representation for an entire sentence or document by averaging the pre-trained Word2Vec vectors of every word inside it.</p><p>If we have the sentence <em>“The food is good”</em>, and we have a dense vector v for each word, the document vector D is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*Eeeq47T3A6KL5isI" /></figure><p>This method compresses the entire document into a single vector representation of the same dimension as your individual word embeddings, providing a clean, fixed-size input for downstream machine learning algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RW1By2gfCqc0pVgENzhnLA.png" /></figure><h3>Final Thoughts: The Limitation of Time and Memory</h3><p>Word2Vec was a massive paradigm shift in Natural Language Processing. By replacing sparse, independent matrices with dense, semantic vector spaces using <strong>CBOW</strong> and <strong>Skip-grams</strong>, we finally taught machines how to understand the relationships between words. Furthermore, by using <strong>Avg Word2Vec</strong>, we figured out how to compress entire sentences down into single, highly informative numerical arrays.</p><p>But there is still one fatal flaw in everything we have built so far.</p><p>Take a look at the <strong>Avg Word2Vec</strong> formula again. When we calculate the average of all the vectors in a sentence, <strong>we completely destroy the order of the words.</strong></p><p>To the Avg Word2Vec model, the sentence <em>“The food was good, not bad”</em> generates the exact same mathematical vector as <em>“The food was bad, not good.”</em></p><p>In language, sequence is everything. Standard Artificial Neural Networks (ANNs) have no concept of time, sequence, or memory. They look at inputs as a flat snapshot. To truly understand language, translate text, or predict the next word in a sentence, we need an architecture with a built-in memory — a network that remembers the word it just read while reading the next one.</p><p>In our next post, we are leaving standard ANNs behind and entering the world of sequential data. We will break down <strong>Recurrent Neural Networks (RNNs)</strong>, explore how they build an internal memory, and look at why they are the true foundation of modern generative AI. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c13b1bd29aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The NLP Foundational Blueprint: From Raw Text to Numerical Vectors]]></title>
            <link>https://medium.com/@mohammedsaimquadri/the-nlp-foundational-blueprint-from-raw-text-to-numerical-vectors-cf5b9a8fcfb4?source=rss-5aad7f3f4f6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf5b9a8fcfb4</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Mohammed Saim Quadri]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 16:01:01 GMT</pubDate>
            <atom:updated>2026-06-13T16:01:01.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jw1gOhMAvZqxPzv1" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When we build deep learning models for text, we face a fundamental obstacle: neural networks are giant calculators. They do not understand the word “cat,” “sat,” or “mat.” They only understand numbers, matrices, and vectors.</p><p>To make Natural Language Processing (NLP) possible, we have to build a rigorous preprocessing pipeline that translates human language into mathematical structures. Today, we are going to lay out the complete blueprint of how raw text is broken down, cleaned, standardized, and ultimately vectorized for machine learning.</p><h3>Part 1: Basic NLP Terminology</h3><p>Before rewriting strings into vectors, we need a common vocabulary to describe our data structures at different scales:</p><ul><li><strong>Corpus:</strong> The complete collection of all textual data used for training. This can span paragraphs, entire articles, or millions of books.</li><li><strong>Documents:</strong> The individual text records or blocks that comprise the corpus (e.g., a single sentence, a tweet, or a full essay).</li><li><strong>Vocabulary:</strong> The master list of all <em>unique</em> words present across the entire corpus.</li><li><strong>Words / Tokens:</strong> The absolute smallest building blocks or individual elements isolated within the corpus.</li></ul><h3>Part 2: Text Preprocessing Techniques</h3><p>Raw human text is noisy, cluttered with punctuation, and packed with redundant grammar. If you feed uncleaned text into a model, you bloat your vocabulary size with useless variants. We use three foundational steps to clean our text:</p><h3>1. Tokenization</h3><p>Tokenization is the process of breaking down a continuous sequence of text into smaller, discrete units called tokens.</p><p>Depending on your model’s granularity, you can tokenize text by characters, sub-words, or complete sentences. For most standard bag-of-words approaches, tokenization translates a raw sentence string directly into a list of individual words.</p><h3>2. Stopwords Removal</h3><p>Stopwords are words that appear frequently in a language but carry very little unique semantic information , such as “to”, “of”, “the”, “is”, and “and”. Stripping these out allows our vectorization algorithms to focus strictly on the high-value, meaningful terms in a document.</p><h3>3. Normalization: Stemming vs. Lemmatization</h3><p>To avoid treating different grammatical forms of the same word as entirely unique vocabulary features, we normalize them to a shared base form.</p><ul><li><strong>Stemming:</strong> A fast, crude heuristic method that chops off the prefixes or suffixes of a word. Because it operates using rigid rules without linguistic context, it frequently outputs non-dictionary words and causes a drop in exact semantic meaning.</li><li><em>Example:</em> The words final, finalized, and finally get aggressively chopped down to the non-word stem fina.</li><li><strong>Lemmatization:</strong> A slower, more sophisticated method that uses vocabulary and morphological analysis to return the true, dictionary-accurate base form (lemma) of a word.</li><li><em>Example:</em> The words final, finalized, and finally are mapped correctly back to the meaningful lemma final. While it is computationally slower than stemming, it strictly preserves the underlying semantic integrity of your data.</li></ul><h3>Part 3: Classical Word Encoding Techniques</h3><p>Once your text is clean, tokenized, and normalized, you must execute <strong>Word Encoding</strong>: translating those string tokens into numerical representations. Historically, this was handled using fixed frequency and counting methods.</p><h3>1. One-Hot Encoding</h3><p>One-Hot Encoding represents categorical tokens or words in a purely numerical format by creating a binary vector for each item. The length of the vector matches the exact size of your unique vocabulary.</p><p>If your dataset contains only three categorical values: [&#39;Red&#39;, &#39;Blue&#39;, &#39;Green&#39;], their one-hot representations look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/0*7YwsG_2vDst7I9qG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/0*e93bq4C54ySJ48op" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/0*FVEv8sALY-vvWXYb" /></figure><ul><li><strong>Advantages:</strong> Incredibly simple to implement and highly intuitive.</li><li><strong>Disadvantages:</strong> It results in massive, highly <strong>sparse matrices</strong> (vectors filled mostly with zeros), causing a huge waste of memory and space. It also creates an <strong>Out-Of-Vocabulary (OOV)</strong> issue, meaning it cannot adapt to non-fixed input sizes during modeling or training. Most importantly, it treats all words as completely independent orthogonal vectors, meaning <strong>zero semantic relationships are captured</strong>.</li></ul><h3>2. Bag of Words (BoW)</h3><p>The Bag of Words model moves from encoding single words to vectorizing entire documents based on word frequency.</p><p>The vectorization workflow follows a strict sequence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*waVp7ClCkkDRZSr5" /></figure><p>You can construct a BoW vector space using two distinct methodology choices:</p><ul><li><strong>Count Vectorization:</strong> Each element in the document vector represents the raw total frequency/count of that particular word in the text.</li><li><strong>Binary Vectorization:</strong> Each element is a simple binary flag indicating whether the word is present (1) or not present (0).</li></ul><h4>The Critical Extension: N-Grams</h4><p>Standard BoW completely ignores word order, meaning “Not bad, good” and “Good, not bad” yield identical vectors. To capture local context and semantic order, we use <strong>N-Grams</strong> : consecutive groupings of n words:</p><ul><li><strong>Bigrams (n=2):</strong> Considers pairs of consecutive words. For example, &quot;The cat sat on the mat&quot; is broken into [&quot;The cat&quot;, &quot;cat sat&quot;, &quot;sat on&quot;, ...].</li><li><strong>Trigrams (n=3):</strong> Considers triples of consecutive words ([&quot;The cat sat&quot;, &quot;cat sat on&quot;, ...]).</li></ul><p>N-Grams provide incredible flexibility for capturing longer sequences of text, but they drastically expand your vocabulary size, intensifying the matrix sparsity issue.</p><h3>3. TF-IDF (Term Frequency — Inverse Document Frequency)</h3><p>While BoW only cares about raw counts, <strong>TF-IDF</strong> calculates how <em>relevant</em> a word is to a specific document within a broader collection or corpus.</p><p>It balances two competing metrics:</p><ol><li><strong>Term Frequency (TF):</strong> The density of a word within a single sentence or record.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*XWkhX9AqJ7WU9eu3" /></figure><p><strong>3. Inverse Document Frequency (IDF):</strong> A logarithmic scale that dampens the score of words that appear everywhere across the entire corpus.</p><p>4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*77Ve7u8GTnM7md2S" /></figure><ul><li><strong>The Logic:</strong> Words that appear in almost every document (like “report” or “data” in a corporate corpus) are given a lower weight. Rare, highly specific keywords get a massive boost.</li><li><strong>Trade-offs:</strong> It captures exact word importance and maintains a fixed vocabulary size, but it still suffers from structural matrix sparsity and cannot parse novel out-of-vocabulary inputs.</li></ul><h3>Part 4: Word Embeddings</h3><p>To completely break free from the constraints of sparse count matrices, modern NLP relies on <strong>Word Embeddings</strong>. This technique maps individual word tokens to dense, continuous vectors in a multi-dimensional coordinate space.</p><p>The foundational law of embeddings is semantic proximity: <strong>words that are closer in meaning or appear in similar context positions are mapped to neighboring vectors in the vector space</strong>.</p><p>We divide word embedding techniques into two overarching categories:</p><ol><li><strong>Count/Frequency Methods:</strong> Statistical matrix factorizations like One-Hot, BoW, and TF-IDF.</li><li><strong>Deep Learning Trained Models:</strong> Advanced high-dimensional feature representations like <strong>Word2Vec</strong>, which trains continuous vectors using neural network objectives like Continuous Bag of Words (<strong>CBOW</strong>) and <strong>Skip-grams</strong>.</li></ol><p>By feeding these dense embedding layers as the absolute first step in a deep neural network architecture (using tools like tf.keras.layers.Embedding), we unlock complex downstream tasks like sentiment analysis, machine translation, and language modeling.</p><h3>Final Thoughts: The Evolution of Text Representation</h3><p>Navigating the pipeline from raw strings to mathematical vectors is the fundamental rite of passage for any NLP workflow. As we’ve seen, the journey always follows a structured progression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ypVzz61hLSgrkEKA" /></figure><p>The true evolution of NLP lies in how we handle that final vectorization step. Classical techniques like One-Hot Encoding, Bag of Words, and TF-IDF served as incredible starting points. They are intuitive, simple to implement, and highly effective for basic text classification tasks. However, their structural limitations; massive matrix sparsity, a vulnerability to Out-Of-Vocabulary words, and a complete inability to understand that “king” and “queen” are semantically related created a massive glass ceiling for language models.</p><p>By transitioning from sparse, high-dimensional count matrices to dense, continuous multi-dimensional <strong>Word Embeddings</strong>, we completely shifted the paradigm. We unlocked a world where the geometric distance between two vectors perfectly reflects the semantic relationship between two human concepts.</p><p>But a glaring question remains: <em>How exactly do we teach a machine to build these high-dimensional semantic spaces from scratch?</em></p><p>That is where neural-network-trained language representations come into play. In our next post, we will step into the modern era of Deep Learning for NLP and break down the internal mechanics of <strong>Word2Vec</strong> , exploring how the Continuous Bag of Words (<strong>CBOW</strong>) and <strong>Skip-gram</strong> architectures revolutionized how machines read the world. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf5b9a8fcfb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forceful Generalization: Mastering Dropout Layers in Deep Networks]]></title>
            <link>https://medium.com/@mohammedsaimquadri/forceful-generalization-mastering-dropout-layers-in-deep-networks-7b32fb5ccd35?source=rss-5aad7f3f4f6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b32fb5ccd35</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[dropout-regularization]]></category>
            <dc:creator><![CDATA[Mohammed Saim Quadri]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 14:01:04 GMT</pubDate>
            <atom:updated>2026-06-12T14:01:04.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DLg_0C7IaTxnWZPz" /><figcaption>Photo by <a href="https://unsplash.com/@nuarharuha?utm_source=medium&amp;utm_medium=referral">NHN</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When a fully connected neural network layer packs a large number of neurons, an insidious problem can develop during training: <strong>co-adaptation</strong>.</p><p>Neurons become overly dependent on the specific outputs of their neighbors to correct mistakes, rather than learning robust features independently. This reliance leads directly to <strong>overfitting</strong> , a scenario where your model performs exceptionally well on training data but completely flatlines on unseen test data.</p><p>To shatter this co-dependency, researchers introduced a highly effective regularization technique: <strong>Dropout</strong>.</p><h3>What is a Dropout Layer?</h3><p>Dropout is a regularization technique designed to combat overfitting by forcing the network to learn redundant representations of the same data.</p><p>During training, this method randomly “drops” or ignores a subset of neurons at each iteration step.</p><p>When a node is dropped, all of its forward and backward connections are temporarily severed. This action effectively alters the network topology, carving a brand-new sub-architecture out of the original parent network for that specific training batch.</p><ul><li><strong>The Dropout Rate (P):</strong> Neurons are dropped based on a predefined probability, P, which is typically applied at the layer level (meaning each layer can have its own custom dropout rate). For instance, a layer with P = 0.5 will deactivate exactly half of its units at random during any given step.</li></ul><h3>How Dropout Fixes Overfitting</h3><p>During standard training, a model’s core drive is simply to minimize its loss function. Without regularization, individual units begin to adapt in complex ways purely to offset the errors made by neighboring units. This resulting web of co-adaptations is highly fragile; it excels at memorizing the statistical noise of the training set but fails completely to generalize to new environments.</p><p>Dropout breaks this behavior by preventing units from relying on the presence of specific other units to cover up mistakes.</p><p>Because any given neighbor might vanish at the next moment, every neuron is forced to learn independently useful features. It can no longer pass the blame.</p><h3>Training vs. Inference: The Scaling Problem</h3><p>While Dropout is a powerful tool during training, the rules change completely during evaluation and deployment: <strong>We do not use dropout layers during inference.</strong></p><p>When testing or serving a model, we want to leverage the full, combined predictive power of all our trained neurons. However, this switch creates a major mathematical imbalance:</p><ul><li>If a layer used P = 0.5 during training, it was operating at only half capacity.</li><li>During inference, if all 100\% of the units are active, the raw accumulated signal hitting the next layer will be twice as large as what the network was trained to handle.</li></ul><p>To resolve this issue and keep the mathematical expectations aligned, the weights must be scaled by the chosen dropout rate prior to inference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*zY_-E-1wpIyBiEUt" /></figure><blockquote><strong><em>Example Breakdown:</em></strong><em> &gt; Suppose you have an architecture where Layer 1 has a dropout rate of P = 0.5 and Layer 2 has a dropout rate of P = 2/5 (0.4).</em></blockquote><blockquote><em>When transitioning the model to inference mode, the final trained weights originating from Layer 1 are scaled down by multiplying them by 0.5. Similarly, the weights coming out of Layer 2 are scaled down by a factor of 0.6 (1–2/5).</em></blockquote><p><em>(Note: Most modern deep learning frameworks like PyTorch handle this automatically using a technique called </em><strong><em>Inverted Dropout</em></strong><em>, where the scaling is performed during the training phase instead so that inference can run at full speed without modification).</em></p><h3>Summary Checklist</h3><ul><li><strong>When to use:</strong> Add dropout layers primarily to large, deep, fully connected (dense) layers that show signs of severe training overfitting.</li><li><strong>Common values:</strong> Keep your dropout probability P between 0.2 and 0.5. Setting it too high will starve the network of capacity, causing it to underfit.</li></ul><p>In the next blog we begin our journey into NLP, starting from the very basics of how text is handled in NLP. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b32fb5ccd35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Flip Side of the Coin: Exploding Gradients and Weight Initialization]]></title>
            <link>https://medium.com/@mohammedsaimquadri/the-flip-side-of-the-coin-exploding-gradients-and-weight-initialization-42a57d441c53?source=rss-5aad7f3f4f6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/42a57d441c53</guid>
            <category><![CDATA[weight-initialization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[exploding-gradient]]></category>
            <dc:creator><![CDATA[Mohammed Saim Quadri]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-06-11T14:01:03.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t5ISUV4ucafMNEhW" /><figcaption>Photo by <a href="https://unsplash.com/@mihaufy?utm_source=medium&amp;utm_medium=referral">Mihai Neagu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We previously broke down the <strong>Vanishing Gradient Problem</strong>, where an error signal shrinks down to zero as it travels backward through a deep network. But what happens when the exact opposite occurs?</p><p>If the fractions along our backpropagation chain turn into large whole numbers, the derivatives grow exponentially. This is the <strong>Exploding Gradient Problem</strong>, and the secret to solving it doesn’t lie in your activation function , it lies in how you initialize your weights.</p><h3>The Exploding Gradient Problem</h3><p>The issue of exploding gradients arises when, during backpropagation, the derivatives or slopes of the neural network’s layers grow progressively larger.</p><p>Unlike vanishing gradients, the root cause of this problem lies primarily in the <strong>initial weights of the network</strong>, rather than the choice of the activation function. High initial weight values lead to correspondingly high derivatives during the chain rule multiplication. This causes significant, volatile deviations in the new weight values during an update step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*E8oda3fUXEX_f8Tb" /></figure><p>As a result, the gradient completely <strong>fails to converge</strong> to the minimum. Instead, the model can end up oscillating violently around local minima or overshooting the valley entirely, causing the training metrics to read NaN (Not a Number).</p><h3>The Rules of Weight Initialization</h3><p>To stop gradients from vanishing or exploding, we must initialize our weights with extreme care. When setting up your parameters, keep these three key points in mind:</p><ol><li><strong>Weights should be small:</strong> To prevent early explosion or saturation.</li><li><strong>Weights should not be the same:</strong> If all weights are identical, every neuron in a layer will calculate the exact same output and gradient, destroying any architectural variance (known as symmetry breaking).</li><li><strong>They should have good variance:</strong> The variance of the outputs of a layer should equal the variance of its inputs so that the scale of the signal doesn’t distort as it passes deeper into the network.</li></ol><h3>1. The Baseline: Uniform Distribution</h3><p>A straightforward approach is to initialize weights randomly using a bounded uniform distribution. To keep the values reasonably scaled, the limits of the range are bound directly to the size of the input layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*dM6CFO_jowrrwWbd" /></figure><p>While this is an improvement over purely arbitrary random values, it does not account for the shrinking scale of the signal as it travels out of a neuron toward the next layer.</p><h3>2. Xavier / Glorot Initialization</h3><p>Designed specifically to stabilize networks using symmetric activation functions like <strong>Sigmoid</strong> or <strong>Tanh</strong>, Xavier (also called Glorot) initialization introduces two structural variables:</p><ul><li>fan_in: The number of incoming input paths to the neuron.</li><li>fan_out: The number of outgoing output paths from the neuron.</li></ul><p>Depending on your distribution preference, Xavier can be implemented in two ways:</p><h4>i) Xavier Normal</h4><p>Weights are drawn from a normal distribution with a mean of 0 and a specific standard deviation (σ):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/0*RXN-Zu3i6shMK9N6" /></figure><h4>ii) Xavier Uniform</h4><p>Weights are drawn uniformly from a tightly calculated range:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/0*xQyN5L2jT-zzQk1s" /></figure><h3>3. He Initialization</h3><p>While Xavier works perfectly for smooth, zero-centered curves, it fails when paired with modern non-linear functions like <strong>ReLU</strong>. Because ReLU cuts off half of your data distribution by turning negative inputs into absolute zeros, it effectively cuts the variance of the layer’s output in half.</p><p>To compensate for this variance drop, Kaiming He introduced <strong>He Initialization</strong>, which doubles the variance numerator to keep the signal active across deep ReLU networks:</p><h4>i) He Normal</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*tpZkBMQljjx-eIrR" /></figure><p>​</p><h4>ii) He Uniform</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/0*P0wNiTWaO0z7U_HM" /></figure><h3>Summary: Your Initialization Playbook</h3><p>When compiling your structural files, follow this definitive matching guide to keep your gradients stable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*4GZQuwsw9ZoPi1mWJrjhQg.png" /></figure><p>In the next blog we will move onto Dropout layers and why it is used, stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42a57d441c53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Guide to Deep Learning Optimizers: From Gradient Descent to Adam]]></title>
            <link>https://medium.com/@mohammedsaimquadri/the-complete-guide-to-deep-learning-optimizers-from-gradient-descent-to-adam-4c34e983dd47?source=rss-5aad7f3f4f6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c34e983dd47</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning-optimizers]]></category>
            <dc:creator><![CDATA[Mohammed Saim Quadri]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-06-10T14:01:03.982Z</atom:updated>
            <content:encoded><![CDATA[<p>When we train a neural network, backpropagation calculates the gradients to tell us <em>how</em> our weights should change to minimize error. But the mathematical algorithm that actually executes those changes is the <strong>Optimizer</strong>.</p><p>Optimizers tweak the parameters of the model iteratively based on a convex function to minimize the loss to its global or local minima.</p><p>Choosing the right optimizer can mean the difference between your model converging in ten minutes, flatlining entirely, or oscillating wildly out of control. Today, we will chart the evolutionary history of optimizers so you know exactly which one to select for your tech stack.</p><h3>1. Batch Gradient Descent (The Foundation)</h3><p>The classic optimization algorithm is <strong>Batch Gradient Descent (GD)</strong>. It iteratively reduces the loss function by calculating the gradient across the <strong>entire training dataset</strong> before making a single update to the weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*z8R6edTQyIsE23RD" /></figure><ul><li><strong>Advantages:</strong> It offers incredibly smooth, stable convergence because every step is calculated using the total consensus of the data. It is also simple to implement.</li><li><strong>Disadvantages:</strong> It is computationally expensive and requires a massive amount of memory. If you have a dataset with millions of rows, you have to load the entire set into memory just to take one tiny step down the error hill, resulting in slow calculation speeds.</li></ul><h3>2. Stochastic Gradient Descent (SGD)</h3><p>To solve the memory and speed limitations of classic GD, researchers introduced <strong>Stochastic Gradient Descent (SGD)</strong>. Instead of waiting to look at the whole dataset, SGD updates the model parameters/weights <strong>one single data point at a time</strong>. If your dataset has 10,000 data points, SGD will update the weights 10,000 times in a single epoch.</p><ul><li><strong>Advantages:</strong> It requires significantly less memory, allowing you to train on incredibly large datasets that would otherwise crash your system.</li><li><strong>Disadvantages:</strong> Because it updates based on individual, isolated data points, the path down the cost surface is highly volatile. These frequent updates lead to <strong>noisy gradients</strong> with high variance. This noise can cause the calculation to become time-consuming and can cause the error to increase rather than decrease over short intervals.</li></ul><h3>3. Mini-Batch SGD (The Sweet Spot)</h3><p><strong>Mini-batch SGD</strong> acts as the ultimate compromise. It splits the training dataset into small, manageable batches (e.g., sizes of 32, 64, or 256) and performs a weight update for each batch. This creates an ideal balance between the robustness of batch GD and the efficiency of standalone SGD.</p><ul><li><strong>Advantages:</strong> It provides a significantly more stable convergence path, effectively reducing the wild variance and noise seen in basic SGD. It optimizes computation speeds while keeping memory footprint low.</li><li><strong>Disadvantages:</strong> It does not unconditionally guarantee optimal convergence. If your global learning rate ($\eta$) is tuned too low, convergence becomes exceptionally slow.</li></ul><h3>4. SGD with Momentum</h3><p>Even with mini-batches, standard SGD struggles when navigating steep, narrow valleys on the cost surface, often bouncing uselessly between the walls. <strong>SGD with Momentum</strong> fixes this by simulating physical inertia. It retains a fraction of the direction from the previous update to help push the weight update forward smoothly.</p><p>To smooth out the noise, it relies on an <strong>Exponential Weighted Moving Average (EWMA)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*Vn19viI5QE-7o1HW" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/0*flNBmeBixYHDE399" /></figure><ul><li><strong>Advantages:</strong> The accumulation of momentum dampens oscillation noise and drives quicker, more stable convergence. The built-in kinetic inertia also helps the optimization path roll right over sub-optimal local minima.</li><li><strong>Disadvantages:</strong> It introduces yet another hyperparameter ($\beta$) that requires manual tuning.</li></ul><h3>5. Adagrad (Adaptive Gradient)</h3><p>Up until this point, every single weight in a network was forced to use the exact same, static learning rate ($\eta$). <strong>Adagrad</strong> changed the paradigm by introducing <strong>dynamic, adaptive learning rates</strong> scaled specifically for each individual parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*cc24hyslybQ6IZuE" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*uMv13GeatawA3ST5" /></figure><p><em>(Note: epsilon is a tiny positive constant like 10^{-8} added purely to avoid dividing by zero).</em></p><ul><li><strong>Advantages:</strong> Parameters that receive frequent, massive updates get their learning rate scaled down, while infrequent, sparse parameters get a larger learning rate. This makes it highly reliable and allows convergence at a higher initial speed.</li><li><strong>Disadvantages:</strong> Because alpha_t continuously accumulates squared gradients over time</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*dSqFfjknoIhjHp7x" /></figure><ul><li>, the denominator grows exponentially. This causes the dynamic learning rate (eta’_t) to drop drastically and monotonically until it becomes too small for the model to learn anything new.</li></ul><h3>6. Adadelta &amp; RMSProp</h3><p>To solve Adagrad’s fatal flaw of diminishing learning rates, both <strong>Adadelta</strong> and <strong>RMSProp (Root Mean Square Propagation)</strong> were developed independently. Instead of blindly summing up all historical gradients from step 1, they restrict the window size by using an <strong>Exponential Weighted Average of squared gradients</strong>.</p><h4>RMSProp Core Formulation:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/0*k-j3n0Xl1G-QB_-_" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*Oug7PGDiwYuns8k-" /></figure><p><em>(Where gamma acts as a decay rate or forgetting factor to keep historical gradient scaling under strict control).</em></p><ul><li><strong>Advantages:</strong> The learning rate adjusts automatically based on recent gradients, meaning it will never prematurely drop to zero. You no longer need to manually toggle default learning rates for Adadelta.</li><li><strong>Disadvantages:</strong> Adadelta can be computationally intensive to evaluate. If the hyperparameters are poorly chosen, RMSProp can suffer from slow training speeds.</li></ul><h3>7. Adam (Adaptive Moment Estimation)</h3><p><strong>Adam</strong> is the crown jewel of modern deep learning optimizers. The core concept behind Adam is to merge the advantages of both worlds: it utilizes the <strong>momentum</strong> concept from SGD with Momentum to track past gradients, and combines it with the <strong>adaptive learning rates</strong> from Adadelta/RMSProp to track past squared gradients.</p><p>It maintains two distinct exponential moving averages:</p><ol><li><strong>V_{dw} (First Moment):</strong> Tracks the exponential weighted average of past gradients to handle momentum.</li><li><strong>S_{dw} (Second Moment):</strong> Tracks the exponential weighted average of past <em>squared</em> gradients to handle the adaptive learning rate.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*O2SUhAGxG-7FN5M6" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/0*zl7-921SPl0JHQCT" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*qpzGP_Og8Ib7Fjy0" /></figure><ul><li><strong>Advantages:</strong> It is highly computationally efficient and requires very little memory. It excels at handling sparse gradients and noisy cost surfaces, making it the default industry standard optimizer for almost all modern Deep Learning architectures.</li></ul><h3>Summary: Which Optimizer to Choose?</h3><ul><li>If your data is incredibly sparse or you are building an initial baseline model: default directly to <strong>Adam</strong>.</li><li>If you are encountering major oscillation barriers or training complex vision systems, look into <strong>RMSProp</strong>.</li><li>Avoid basic <strong>Batch GD</strong> or <strong>Adagrad</strong> for deep networks due to high memory limitations and early stagnation pitfalls.</li></ul><p>In the next blog we will learn about the problem of exploding gradients and the weight initialization techniques. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c34e983dd47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Loss Function Manual: Matching Your Architecture to the Right Math]]></title>
            <link>https://medium.com/@mohammedsaimquadri/the-loss-function-manual-matching-your-architecture-to-the-right-math-74779983a7c3?source=rss-5aad7f3f4f6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/74779983a7c3</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Mohammed Saim Quadri]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-06-09T14:01:03.691Z</atom:updated>
            <content:encoded><![CDATA[<p>In our last post, we explored how activation functions act as the mathematical gates of a neural network. But once data passes through those gates and a network makes its final “guess,” how exactly do we grade it?</p><p>We use a <strong>Loss Function</strong> (or error function) to measure the exact difference between the model’s predictions (hat{y}) and the actual target values (y) for a single training example.</p><p>Choosing the wrong loss function will completely break your backpropagation loop. Today, we are breaking down the standard loss functions for both regression and classification, detailing exactly when to deploy them.</p><h3>Part 1: Regression Loss Functions</h3><p>When your model is predicting a continuous numerical value (like a price, temperature, or coordinate), you are dealing with a regression problem. Your main options are:</p><ul><li><strong>MSE (Mean Squared Error):</strong> Heavily penalizes large errors by squaring the differences, making it highly sensitive to outliers.</li><li><strong>MAE (Mean Absolute Error):</strong> Measures the average absolute distance, making it much more robust to outliers.</li><li><strong>RMSE (Root Mean Squared Error):</strong> Brings the scale of the error back to the original unit of your target data.</li><li><strong>Huber Loss:</strong> The best of both worlds. It acts as a hybrid combination of MSE and MAE.</li></ul><p>Huber loss uses a threshold parameter (delta) to dynamically switch its math based on how wrong the prediction is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*5VOyFd-e4y6JvXtt" /></figure><p>If the error is small (less than delta), it uses smooth MSE math to converge cleanly. If the error is massive, it switches to linear MAE math to prevent outliers from violently disrupting the weight updates.</p><h3>Part 2: Classification Loss Functions</h3><p>When your goal is to sort data into distinct categories, you must switch over to entropy-based loss functions.</p><h4>1. Binary Cross-Entropy (BCE)</h4><p>Used strictly for <strong>Binary Classification</strong> tasks where your output layer uses a <strong>Sigmoid</strong> activation function to yield a single probability between 0 and 1.</p><p>The general equation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/0*X0CuzUFdessj1y6H" /></figure><p>Because y can only ever be a hard 0 or 1, this equation elegantly collapses into two scenarios depending on the ground truth:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/0*2R8EZ6y4sp6qneQM" /></figure><p>If the true label is 1 and your model predicts a 0.01, the -log(0.01) penalty scales exponentially, aggressively punishing the network during backpropagation.</p><h4>2. Categorical Cross-Entropy (CCE) vs. Sparse Categorical Cross-Entropy (SCCE)</h4><p>When you scale up to <strong>Multiclass Classification</strong> (more than two distinct categories), your output layer will pass through a <strong>Softmax</strong> activation function to output an array of probabilities that sum to 1.</p><p>The mathematical goal remains the same, but how you format your target data determines whether you choose CCE or SCCE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/0*2Z0IiQoxA3PhFqKl" /></figure><ul><li><strong>Categorical Cross-Entropy (CCE):</strong> Expects your true target labels ($y$) to be <strong>One-Hot Encoded (OHE)</strong> arrays.</li><li><strong>Sparse Categorical Cross-Entropy (SCCE):</strong> Expects your true target labels to be simple <strong>integer category indices</strong>.</li></ul><blockquote><strong><em>The Difference by Example:</em></strong><em> &gt; Imagine a classification problem with 5 total classes. If the correct label is the second class, here is how the data formatting differs:</em></blockquote><ul><li><strong>If using CCE:</strong> Your target must be formatted as an array: [0, 1, 0, 0, 0]. The model might output class probabilities like [0.2, 0.5, 0.1, 0.1, 0.1].</li><li><strong>If using SCCE:</strong> Your target is simply a raw integer index: [1]. The model still outputs the identical probability array, but you save memory by avoiding massive, sparse one-hot matrices.</li></ul><h3>The Architecture Manual: What to Pair When</h3><p>To ensure your networks can actually compute stable gradients, save this master pairing table to your layout workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*zicHZuFubk5yTK5A5AuPgA.png" /></figure><p>In the next blog we will go over optimizers and their working. stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74779983a7c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Activation Function Cheat Sheet: Choosing the Right Gate for Your Neural Network]]></title>
            <link>https://medium.com/@mohammedsaimquadri/the-activation-function-cheat-sheet-choosing-the-right-gate-for-your-neural-network-cf89d32ba4df?source=rss-5aad7f3f4f6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf89d32ba4df</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mohammed Saim Quadri]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 13:13:19 GMT</pubDate>
            <atom:updated>2026-06-08T13:13:19.757Z</atom:updated>
            <content:encoded><![CDATA[<p>In our last post, we saw how the <strong>Vanishing Gradient Problem</strong> essentially starves deep neural networks of information. When we chain too many tiny fractions together, the error signal fades to zero, and the network forgets how to learn.</p><p>The culprit behind this mathematical bottleneck? The choice of our activation function.</p><p>Today, we are going to explore the mathematical “gates” that control our neural networks. We will look at why the classics failed us in deep networks, the modern heroes that fixed the problem, and a cheat sheet on exactly which function to use when building your own models.</p><h3>What Actually is an Activation Function?</h3><p>An activation function is a mathematical function applied to the output of a neuron. Before a neuron fires, it calculates the weighted sum of its inputs and adds a bias term:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*Jo0B3Myuwc6MVJly" /></figure><p>The activation function then decides whether that neuron should be activated based on this calculation. Most importantly, it introduces non-linearity into the model, allowing the network to learn and represent highly complex patterns in the data.</p><p>Without non-linearity, a deep neural network would just be a giant, computationally expensive linear regression model.</p><h3>Part 1: The Classics (And Their Flaws)</h3><h4>1. Sigmoid</h4><p>The Sigmoid function was the original standard for neural networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/0*QX3DvmXqky6ma32Y" /></figure><ul><li><strong>How it works:</strong> It squishes output values into the open interval (0, 1).</li><li><strong>Advantages:</strong> It provides a smooth gradient, preventing sudden “jumps” in output values. It also normalizes the output of each neuron and yields clear predictions.</li><li><strong>Disadvantages:</strong> It is highly prone to gradient vanishing (also known as gradient saturation or dispersion). Furthermore, the function output is not zero-centered, which reduces the efficiency of weight updates. Finally, it performs exponential operations, which are relatively time-consuming for computers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIJVJBMiXC01yNeqZngmQA.png" /></figure><h4>2. Tanh (Hyperbolic Tangent)</h4><p>To fix the zero-centered issue of Sigmoid, researchers shifted to Tanh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*aGV8TwxDmcS6jEg5" /></figure><ul><li><strong>How it works:</strong> The curves of the tanh and sigmoid functions are relatively similar, but the output interval of tanh is (-1, 1).</li><li><strong>Advantages:</strong> Unlike sigmoid, the whole function is zero-centered, which is better for network training. It also maintains a smooth gradient.</li><li><strong>Disadvantages:</strong> When the input is very large or small, the gradient becomes small, which is not conducive to weight updates. Therefore, the vanishing gradient problem still exists for Deep Neural Networks (DNNs). It also still requires intensive computation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtSANe-IudV2o2szCtO_3w.png" /></figure><h3>Part 2: The Modern Functions</h3><p>To solve the vanishing gradient problem, the Deep Learning community practically abandoned Sigmoid and Tanh in hidden layers and adopted a simpler, highly effective gate.</p><h4>3. ReLU (Rectified Linear Unit)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/0*ch0dnYom0zpboVUU" /></figure><ul><li><strong>How it works:</strong> It acts as a simple threshold. If the input is positive, it passes it through directly. If it is negative, it outputs exactly zero.</li><li><strong>Advantages:</strong> It directly solves the vanishing gradient problem. Because it only requires calculating max(0, x), it allows for very fast computation.</li><li><strong>Disadvantages:</strong> It is not zero-centered. More critically, it suffers from the “Dead Neuron” problem. If the derivative of ReLU(z) equals 0, we get a “dead neuron” where no weight updation occurs (W_{new} approx W_{old}).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*edzJgEu70deqIkUXAQwHEA.png" /></figure><h4>4. Leaky ReLU &amp; Parametric ReLU (PReLU)</h4><p>To stop neurons from dying, we give the negative side of the graph a slight slope instead of a flat zero.</p><ul><li><strong>Leaky ReLU:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/0*9lkSk9BqVB3ybF3w" /></figure><ul><li><strong>PReLU:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/0*PkIxgvdwdOjNfTxb" /></figure><ul><li><strong>How it works:</strong> To mitigate the dying ReLU problem, Leaky ReLU introduces a small gradient for negative inputs, preserving some activity in the neurons.</li><li><strong>Advantages:</strong> It has all the advantages of ReLU with no dead ReLU problem. PReLU goes a step further; it uses alpha as a hyperparameter that the model learns during training, making it more accurate and consistent than Leaky ReLU.</li><li><strong>Disadvantages:</strong> Leaky ReLU is not consistent due to its fixed slope throughout training. PReLU, while adaptable, can require manual trial and error to find the optimal value of alpha. Neither function is zero-centered.</li></ul><h4>5. ELU (Exponential Linear Unit)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/0*Odq19_c3owhs2bf5" /></figure><ul><li><strong>Advantages:</strong> It resolves the dead ReLU problem and is zero-centered.</li><li><strong>Disadvantages:</strong> Because of the exponential math, it is slightly more computationally intensive.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EnvLojIMJQMikgBNDcP6ng.png" /></figure><h3>Part 3: The Output Specialists</h3><p>While the functions above are used inside the “hidden layers” to transform data, the final output layer needs specific functions to give us human-readable answers.</p><h4>6. Softmax</h4><p>When you want your model to classify an image as a dog, cat, or bird, you use Softmax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*f7mX4UQAnlB3wDpf" /></figure><p><em>(Where z_i is the logit or output of the previous layer for the i^{th} class, and K is the total number of classes).</em></p><ul><li><strong>How it works:</strong> It is a mathematical function typically applied to the output layer of a network. It converts a vector of raw prediction scores (called logits) from the neural network into probabilities. These probabilities are distributed across classes such that their sum always equals 1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDw6Bf5AI3xiq9K3el5B4w.png" /></figure><h3>The Cheat Sheet: Which Function Should You Use?</h3><p>Generally, problems fall into two types: regression or classification. A linear activation function is convenient for regression problems, while non-linear functions are more suitable for classification problems.</p><p>Here is your decision tree for architecting your neural networks:</p><p><strong>1. For the Hidden Layers:</strong></p><ul><li>Always default to <strong>ReLU</strong>.</li><li>A differential non-linear function is more suitable here because it trains the NN model to work on more complex problems.</li><li><em>Tip:</em> If your model stalls and your neurons are dying, swap to Leaky ReLU or PReLU.</li></ul><p><strong>2. For the Output Layer:</strong></p><ul><li><strong>Regression</strong> (Predicting a continuous number, like house price): Use <strong>Linear Activation</strong>.</li><li><strong>Binary Classification</strong> (Yes/No, Spam/Not Spam): Use <strong>Sigmoid</strong>.</li><li><strong>Multiclass Classification</strong> (Is it a Dog, Cat, OR Bird?): Use <strong>Softmax</strong>.</li><li><strong>Multilabel Classification</strong> (Is this image a Dog AND playing outside?): Use <strong>Sigmoid.</strong></li></ul><p>In the next post we will cover Loss Functions, stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf89d32ba4df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Vanishing Gradient Problem: Why Deep Networks Forget How to Learn]]></title>
            <link>https://medium.com/@mohammedsaimquadri/the-vanishing-gradient-problem-why-deep-networks-forget-how-to-learn-6d047ca784e0?source=rss-5aad7f3f4f6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d047ca784e0</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[vanishing-gradient]]></category>
            <category><![CDATA[activation-functions]]></category>
            <dc:creator><![CDATA[Mohammed Saim Quadri]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 14:01:07 GMT</pubDate>
            <atom:updated>2026-04-20T14:01:07.347Z</atom:updated>
            <content:encoded><![CDATA[<p>In our last post, we saw how Backpropagation uses the Chain Rule to assign “blame” for errors, passing gradients backward through the network to update the weights.</p><p>It works beautifully for networks with one or two hidden layers. But in the early days of Deep Learning, researchers hit a massive wall. When they tried to build truly <em>deep</em> networks (adding 5, 10, or 50 layers to solve complex problems), the networks just… stopped learning. The accuracy flatlined.</p><p>This roadblock is known as the <strong>Vanishing Gradient Problem</strong>. To understand why it happens, we have to look at the math behind how neurons activate.</p><h3>What Actually is an Activation Function?</h3><p>Before a neuron passes its signal to the next layer, it calculates a weighted sum of its inputs and adds a bias:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*fu9D7SWS5PpXv48bdswA7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*AI458v8TzFpoPG22" /></figure><p>But it doesn’t just pass z forward. It passes z through an <strong>Activation Function</strong>. This is a mathematical gate that introduces non-linearity, allowing the network to learn complex, curved patterns instead of just straight lines.</p><p>For a long time, the default activation function was the <strong>Sigmoid Function</strong>. It takes any number and squishes it into a neat little range between <strong>0 and 1</strong>.</p><p>It sounds perfect, right? But Sigmoid has a dark side.</p><h3>The Math: A Chain of Tiny Fractions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*zIJUS4edpVDC3XK0gX8P-A.png" /></figure><p>Let’s look at what happens to our weights during Backpropagation. To update a weight in the very first layer (W_1) of a deep network, we use Gradient Descent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/0*zPZrEDf-69fRUpNg" /></figure><p>To find that gradient</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/105/0*GdaRVDKXQBqJue0_" /></figure><p>, the Chain Rule forces us to multiply the derivatives of all the layers that come after it. Let’s trace it back from layer 4:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*qZPabiNQWPb-xWTT" /></figure><p>Here is where the Sigmoid function ruins everything.</p><p>Every time we calculate the derivative of a layer’s output ,like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/0*_4rexq2zHFm1jTyB" /></figure><p>, we are taking the derivative of the Sigmoid function (sigma’(z)) and multiplying it by the weight.</p><p>Here is the fatal mathematical flaw: <strong>The maximum possible value for the derivative of a Sigmoid function is 0.25.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*MINTfkEiMSjLtSKdtCcl9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*NzkvqijCT00DGhmo" /></figure><p>Additionally, when we initialize our weights, we typically set them to small numbers between 0 and 1.</p><h3>The Telephone Game Effect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*inSmaTo10D_sm67SpGxx-A.png" /></figure><p>Let’s plug those maximum values back into our Chain Rule equation for our early weight W_1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*I0TXido4rQuwagQB" /></figure><p>What happens when you multiply a fraction by a fraction? It gets smaller.</p><ul><li>0.25 x 0.25 = 0.0625</li><li>0.0625 x 0.25 = 0.0156</li></ul><p>By the time the error signal travels backward through 4, 5, or 10 layers, the gradient has vanished into a microscopic number.</p><p>To make matters worse, we multiply this already tiny gradient by the Learning Rate (eta), which is usually another small decimal like 0.01.</p><p>The final result? The update value is virtually zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*qImOkNI3UcL9E7GC" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/0*MuVWRb2yFc-sUF27" /></figure><p>Because the gradient vanishes, the first layers of the network receive little to no updated information. They stagnate. And because the later layers rely on the early layers to extract basic features, the entire network’s ability to learn collapses.</p><h3>The Solution: Changing the Gate</h3><p>The Vanishing Gradient problem occurs because the Sigmoid function “saturates,” capping its derivative at 0.25.</p><p>So, how did the AI community fix this and unlock modern Deep Learning? They stopped using Sigmoid in the hidden layers.</p><p>They introduced a new activation function that doesn’t squish numbers and whose derivative doesn’t max out at a fraction. It’s called <strong>ReLU (Rectified Linear Unit)</strong>, and it changed the trajectory of AI forever.</p><p>In our next post, we will dive into ReLU, compare it to the other activation functions, and show you exactly how to choose the right mathematical gate for your models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d047ca784e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>