<?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 Surisetti Vamsi krishna on Medium]]></title>
        <description><![CDATA[Stories by Surisetti Vamsi krishna on Medium]]></description>
        <link>https://medium.com/@surisettikrishna17?source=rss-580bb06a49c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2t8HYO6iT7O7rp9x</url>
            <title>Stories by Surisetti Vamsi krishna on Medium</title>
            <link>https://medium.com/@surisettikrishna17?source=rss-580bb06a49c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:14:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@surisettikrishna17/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[NLP from Scratch — Part 4: The Transformer Architecture, Fully Explained]]></title>
            <link>https://medium.com/@surisettikrishna17/nlp-from-scratch-part-4-the-transformer-architecture-fully-explained-5fbf2c090717?source=rss-580bb06a49c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fbf2c090717</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Surisetti Vamsi krishna]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 12:31:01 GMT</pubDate>
            <atom:updated>2026-08-17T12:31:01.680Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 4 of the “BoW to Transformers” series. Part 3 ended on a real limitation: LSTMs and GRUs process sequences one step at a time — sequentially, slowly, and even their improved memory eventually dilutes over very long sequences. This part is the payoff of the whole series: the architecture that broke both limits at once, and became the foundation of BERT, GPT, and every modern LLM.</p><p>Table of Contents</p><ol><li>Why RNNs/LSTMs Weren’t Enough</li><li>2. Bird’s-Eye View of the Architecture</li><li>3. Input Embeddings + Positional Encoding</li><li>4. Self-Attention — Query, Key, Value</li><li>5. Multi-Head Attention</li><li>6. Masked (Causal) Attention</li><li>7. Add &amp; Norm — Residual Connections</li><li>8. Feed-Forward Network</li><li>9. The Full Encoder-Decoder Stack</li><li>10. End-to-End Worked Example</li></ol><h3>1. Why RNNs/LSTMs Weren’t Enough</h3><p>Quick recap from Part 3: LSTMs fixed the memory problem — they can carry context across long sequences without gradients vanishing. But they left two things unresolved:</p><p>Strictly sequential — to compute the state at word 50, you must first compute words 1 through 49, one at a time. No parallelization across a GPU. Training on large datasets was painfully slow.</p><p>One compressed memory vector — even with a protected cell state, the entire sequence’s context gets squeezed into one fixed-size vector. For very long inputs, something that matters at position 1 can still get diluted by position 500.</p><p>In 2017, the paper “Attention Is All You Need” asked a different question entirely:</p><p>What if, instead of compressing the whole sequence into one memory vector step by step, the model could look directly at every word at once, and learn for itself which words matter most to which other words?</p><p>No recurrence. No step-by-step memory. Just direct, parallel comparisons between every word and every other word. That’s the entire premise of the Transformer.</p><h3>2. Bird’s-Eye View of the Architecture</h3><p>The original Transformer has two halves: an Encoder (reads the input, builds a rich representation) and a Decoder (generates the output, one token at a time, using the encoder’s representation plus what it has generated so far).</p><p>Each block in the diagram below is one of the components in the table of contents — we’ll go through every one of them next: what it does, why it exists, the exact formula, and code.</p><p>(Note: models like BERT use only the encoder stack; models like GPT use only the decoder stack with masked self-attention. The original Transformer used both, for translation. Everything explained below applies to both halves — decoder-only pieces like masking are flagged clearly.)</p><p>INPUT SENTENCE</p><p>|</p><p>▼</p><p>Input Embeddings + Positional Encoding</p><p>|</p><p>▼</p><p>ENCODER (× N layers): Multi-Head Self-Attention → Add &amp; Norm → Feed-Forward Network → Add &amp; Norm</p><p>| (encoder output feeds into every decoder layer)</p><p>▼</p><p>DECODER (× N layers): Masked Multi-Head Self-Attention → Add &amp; Norm → Multi-Head Cross-Attention (attends to encoder output) → Add &amp; Norm → Feed-Forward Network → Add &amp; Norm</p><p>|</p><p>▼</p><p>Linear + Softmax → next word probabilities</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7cjqTypbwIIvo5lxEp5Qg.gif" /></figure><h3>3. Input Embeddings + Positional Encoding</h3><h4>Embeddings — nothing new here</h4><p>Each word/token is converted to a dense vector, exactly like Word2Vec from Part 2 — except in a Transformer, this embedding layer is trained end-to-end along with the rest of the model, not pre-trained separately.</p><p>X ∈ R^(n × d_model), where n = sequence length, d_model = embedding dimension (512 in the original paper, often 768+ in modern models).</p><p><strong>The Problem: Attention Has No Sense of Order</strong></p><p>Here’s something crucial that trips a lot of learners up: self-attention (covered next) treats a sequence as an unordered set. Feed in “dog bites man” versus “man bites dog,” and raw self-attention produces the exact same set of comparisons — zero built-in sense of word position. That’s a serious problem, since word order carries meaning.</p><p>Positional Encoding fixes this by injecting position information directly into the embeddings, before they enter the attention layers.</p><p><strong>The Formula</strong></p><p>The original paper uses fixed sine and cosine functions of different frequencies:</p><p>PE(pos, 2i) = sin(pos / 10000^(2i/d_model))</p><p>PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))</p><p>Where pos is the word’s position in the sequence (0, 1, 2, …) and i is the dimension index within the embedding vector.</p><p><strong>Why sine and cosine, specifically?</strong></p><p>Values are bounded between -1 and 1, so they don’t blow up the embedding’s scale.</p><p>Each position gets a unique pattern across the embedding dimensions.</p><p>The encoding for position pos + k can be expressed as a linear function of the encoding at position pos — this makes it easier for the model to learn to attend to relative positions (“the word 3 tokens back”), not just absolute ones.</p><p>The final input to the model is simply: Input = Embedding(x) + PE</p><p>Just element-wise addition — position gets baked directly into the same vector space as the word’s meaning.</p><p>(Modern models like GPT and BERT often use learned positional embeddings instead of fixed sine/cosine — a trainable lookup table per position — but the goal is identical: give the model a way to distinguish position 1 from position 50.)</p><p><strong>Code</strong></p><p>import torch<br>import math</p><p>def positional_encoding(seq_len, d_model):<br> pe = torch.zeros(seq_len, d_model)<br> position = torch.arange(0, seq_len).unsqueeze(1).float()<br> div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))<br> pe[:, 0::2] = torch.sin(position * div_term)<br> pe[:, 1::2] = torch.cos(position * div_term)<br> return pe</p><p>pe = positional_encoding(seq_len=10, d_model=16)<br>print(pe.shape) # [10, 16]</p><h3>4. Self-Attention — Query, Key, Value</h3><p>This is the heart of the entire architecture. Everything else in the model exists to support this mechanism.</p><p><strong>The Intuition First</strong></p><p>Think about how you understand the word “it” in this sentence:</p><p>“The animal didn’t cross the street because it was too tired.”</p><p>To know what “it” refers to, your brain automatically looks back at the other words and decides “animal” is far more relevant than “street.” Self-attention is a mechanism that lets the model do exactly this — for every word, look at every other word in the sentence, and learn how much attention to pay to each one.</p><p><strong>Query, Key, Value — The Library Analogy</strong></p><p>This is the part beginners often memorize without truly understanding. Here’s the clearest way to think about it:</p><p>Query (Q) — “What am I looking for?” A representation of the current word, used to search.</p><p>Key (K) — “What do I contain?” A representation of every word, used to be searched against.</p><p>Value (V) — “What information do I actually carry?” The actual content returned once a match is found.</p><p>Imagine a library search: your query is your search term, every book has a key (its title/index tag) that gets matched against your query, and once you find a good match, you get the value — the actual book content, not just its title.</p><p>Every word gets all three — Q, K, V — computed by multiplying the input embedding by three separate learned weight matrices:</p><p>Q = XW^Q, K = XW^K, V = XW^V</p><p>Where W^Q, W^K, W^V are learned during training — the model decides what makes a good “query,” “key,” and “value” purely through training; nobody hand-designs these.</p><p><strong>The Attention Formula</strong></p><p>Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) V</p><p>Breaking this into steps, since every piece has a specific job:</p><p>Step 1 — QK^T: compute similarity scores. The dot product of each word’s query against every word’s key gives a raw similarity score — how relevant each word is to the current word being processed. Higher dot product = more relevant.</p><p>Step 2 — divide by sqrt(d_k): scale. Without this, dot products can grow large in magnitude as d_k increases, pushing softmax into regions with extremely small gradients (softmax saturation). Dividing by sqrt(d_k) keeps values in a stable range — literally why this is called “Scaled Dot-Product Attention.”</p><p>Step 3 — softmax: turn scores into weights. Softmax converts raw scores into a probability distribution summing to 1 across all words — a clean weighting of “how much attention to pay to each word,” not raw unbounded numbers.</p><p>Step 4 — multiply by V: retrieve weighted content. The attention weights compute a weighted sum of all Value vectors. Words judged more relevant contribute more; irrelevant words contribute close to nothing.</p><p>The output is a new vector for each word — no longer just “the meaning of this word in isolation,” but “the meaning of this word, informed by every relevant word around it.”</p><p><strong>Tiny Worked Example</strong></p><p>Say we have 3 words with toy 2-dimensional Q, K, V (heavily simplified for intuition — real models use much higher dimensions):</p><p>Word “it”: Query = [1, 0]. Word “animal”: Key = [1, 0], Value = [0.9, 0.1]. Word “street”: Key = [0, 1], Value = [0.1, 0.9].</p><p>Dot products: “it”·”animal” = 1.0, “it”·”street” = 0.0. After softmax (roughly): weights ≈ [0.73, 0.27]. Output for “it” ≈ 0.73 × [0.9, 0.1] + 0.27 × [0.1, 0.9] ≈ [0.685, 0.315].</p><p>The result vector for “it” leans heavily toward “animal”’s value — exactly the behavior we wanted. Real attention operates over 512+ dimensions and dozens of words, but the mechanics are identical.</p><p><strong>Code</strong></p><p>import torch<br>import torch.nn.functional as F</p><p>def self_attention(Q, K, V):<br> d_k = Q.size(-1)<br> scores = torch.matmul(Q, K.transpose(-2, -1)) / (d_k ** 0.5)<br> weights = F.softmax(scores, dim=-1)<br> output = torch.matmul(weights, V)<br> return output, weights</p><p>seq_len, d_k = 5, 8<br>Q = torch.randn(seq_len, d_k)<br>K = torch.randn(seq_len, d_k)<br>V = torch.randn(seq_len, d_k)</p><p>output, attn_weights = self_attention(Q, K, V)<br>print(output.shape) # [5, 8]<br>print(attn_weights.shape) # [5, 5] -&gt; each word’s attention over every other word</p><h3>5. Multi-Head Attention</h3><p>A single attention mechanism can only learn one type of relationship pattern at a time. But language has many kinds of relationships happening simultaneously — grammatical dependency, coreference (like “it” → “animal”), semantic similarity, positional closeness. Forcing all of that into one attention computation is limiting.</p><p>Multi-Head Attention runs several attention computations in parallel — each with its own separately learned W^Q, W^K, W^V — so different heads can specialize in different kinds of relationships. In practice, researchers have found some heads learn to track syntax, others track long-range coreference, others track local word order — the model discovers these specializations on its own during training, nobody assigns them.</p><p><strong>The Formula</strong></p><p>MultiHead(Q, K, V) = Concat(head_1, …, head_h) W^O</p><p>head_i = Attention(Q W_i^Q, K W_i^K, V W_i^V)</p><p>Where h is the number of heads (8 in the original paper), and W^O is a learned output projection that combines all the heads’ outputs back into a single vector of size d_model.</p><p>Important detail on dimensions: each head works with a smaller dimension, d_k = d_model / h (e.g., 512/8 = 64), so running all heads in parallel costs roughly the same total compute as one full-size attention head — the total capacity is split across 8 specialized views, not multiplied by 8.</p><p><strong>Code</strong></p><p>import torch<br>import torch.nn as nn</p><p>multi_head_attn = nn.MultiheadAttention(embed_dim=512, num_heads=8, batch_first=True)</p><p>x = torch.randn(1, 10, 512) # batch=1, seq_len=10, d_model=512<br>output, attn_weights = multi_head_attn(x, x, x) # Q=K=V=x for self-attention</p><p>print(output.shape) # [1, 10, 512]<br>print(attn_weights.shape) # [1, 10, 10] -&gt; averaged across heads by default</p><h3>6. Masked (Causal) Attention</h3><p>This piece is specific to decoders — models generating text one token at a time (GPT-style models, and the decoder half of the original Transformer).</p><p><strong>The Problem It Solves</strong></p><p>During training, the decoder sees the entire target sentence at once (for efficiency). But when actually generating text, the model can only see words it has already produced — it can’t peek at future words it hasn’t generated yet. If training didn’t account for this, the model would learn to “cheat” by looking ahead, then fail completely at real generation time, where there is no “ahead” to look at.</p><p><strong>The Fix: Masking</strong></p><p>Before the softmax step in attention, a mask is added that sets all “future” positions to -infinity:</p><p>MaskedAttention(Q, K, V) = softmax(QK^T / sqrt(d_k) + M) V</p><p>Where M has 0s for allowed (past and current) positions and -infinity for forbidden (future) positions. Since e^-infinity = 0, those positions get exactly zero weight after softmax — the model mathematically cannot attend to future tokens, not just “is discouraged from” — it’s a hard, structural constraint baked directly into the math.</p><p>Mask for a 4-word sequence (row = current word, column = word being attended to): word 2 can attend to words 1 and 2, never to 3 or 4. This is exactly the left-to-right constraint GPT-style generation depends on.</p><p><strong>Code</strong></p><p>import torch</p><p>def causal_mask(seq_len):<br> mask = torch.triu(torch.ones(seq_len, seq_len), diagonal=1)<br> mask = mask.masked_fill(mask == 1, float(‘-inf’))<br> return mask # 0s on/below diagonal, -inf above</p><p>mask = causal_mask(4)<br>print(mask)<br># tensor([[0., -inf, -inf, -inf],<br># [0., 0., -inf, -inf],<br># [0., 0., 0., -inf],<br># [0., 0., 0., 0.]])</p><h3>7. Add &amp; Norm — Residual Connections</h3><p>After both the multi-head attention block and the feed-forward block, the Transformer applies the same pattern:</p><p>output = LayerNorm(x + Sublayer(x))</p><p>Two separate ideas are packed into this one line.</p><p>The “Add” part — residual (skip) connection. Instead of passing x only through the sublayer, the original input is added back to the sublayer’s output. This matters for the same reason residuals matter in any very deep network: it gives gradients a direct path backward during training, bypassing the risk of vanishing as the network gets deep (real Transformers stack 6, 12, even 96+ layers). Without this, training networks this deep would be extremely difficult.</p><p>The “Norm” part — layer normalization. This normalizes values across the feature dimension for each individual token, stabilizing the scale of activations flowing through the network. This keeps training stable and lets the model use higher learning rates without diverging.</p><p><strong>Code</strong></p><p>import torch.nn as nn</p><p>class AddNorm(nn.Module):<br> def __init__(self, d_model):<br> super().__init__()<br> self.norm = nn.LayerNorm(d_model)</p><p>def forward(self, x, sublayer_output):<br> return self.norm(x + sublayer_output)</p><h3>8. Feed-Forward Network</h3><p>Every position in the sequence also passes through a simple, fully-connected feed-forward network — applied identically and independently to each position (the same weights are reused at every position, similar in spirit to how RNN weights are reused across time steps — but here there’s no recurrence; every position is processed in parallel).</p><p><strong>The Formula</strong></p><p>FFN(x) = max(0, xW_1 + b_1) W_2 + b_2</p><p>That’s a linear layer, a ReLU activation, then another linear layer. Simple by design. The inner dimension is typically much larger than d_model (2048 vs. 512 in the original paper) — this expansion-then-compression gives the model extra capacity to transform each token’s representation after attention has gathered context, before passing it to the next layer.</p><p>Why this matters, conceptually: attention is what lets tokens exchange information with each other. The FFN, by contrast, is where the model does per-token “thinking” with the information attention just gathered — no cross-token interaction happens here at all; it’s purely a transformation applied to each position on its own.</p><p><strong>Code</strong></p><p>import torch.nn as nn</p><p>class FeedForward(nn.Module):<br> def __init__(self, d_model, d_ff):<br> super().__init__()<br> self.linear1 = nn.Linear(d_model, d_ff)<br> self.linear2 = nn.Linear(d_ff, d_model)<br> self.relu = nn.ReLU()</p><p>def forward(self, x):<br> return self.linear2(self.relu(self.linear1(x)))</p><p>ffn = FeedForward(d_model=512, d_ff=2048)</p><h3>9. The Full Encoder-Decoder Stack</h3><p>Putting every piece together, one encoder layer looks like:</p><p><strong>Code</strong></p><p>import torch.nn as nn</p><p>class EncoderLayer(nn.Module):<br> def __init__(self, d_model, num_heads, d_ff):<br> super().__init__()<br> self.self_attn = nn.MultiheadAttention(d_model, num_heads, batch_first=True)<br> self.ffn = FeedForward(d_model, d_ff)<br> self.norm1 = nn.LayerNorm(d_model)<br> self.norm2 = nn.LayerNorm(d_model)</p><p>def forward(self, x):<br> attn_out, _ = self.self_attn(x, x, x)<br> x = self.norm1(x + attn_out) # Add &amp; Norm #1<br> ffn_out = self.ffn(x)<br> x = self.norm2(x + ffn_out) # Add &amp; Norm #2<br> return x</p><p>A decoder layer adds masked self-attention and a cross-attention step that attends to the encoder’s output:</p><p><strong>Code</strong></p><p>class DecoderLayer(nn.Module):<br> def __init__(self, d_model, num_heads, d_ff):<br> super().__init__()<br> self.masked_self_attn = nn.MultiheadAttention(d_model, num_heads, batch_first=True)<br> self.cross_attn = nn.MultiheadAttention(d_model, num_heads, batch_first=True)<br> self.ffn = FeedForward(d_model, d_ff)<br> self.norm1 = nn.LayerNorm(d_model)<br> self.norm2 = nn.LayerNorm(d_model)<br> self.norm3 = nn.LayerNorm(d_model)</p><p>def forward(self, x, encoder_output, tgt_mask):<br> attn_out, _ = self.masked_self_attn(x, x, x, attn_mask=tgt_mask)<br> x = self.norm1(x + attn_out) # Add &amp; Norm #1<br> cross_out, _ = self.cross_attn(x, encoder_output, encoder_output)<br> x = self.norm2(x + cross_out) # Add &amp; Norm #2<br> ffn_out = self.ffn(x)<br> x = self.norm3(x + ffn_out) # Add &amp; Norm #3<br> return x</p><p>Stack N of these (6 in the original paper, far more in modern LLMs), and you have the full Transformer.</p><h3>10. End-to-End Worked Example</h3><p>Let’s trace one sentence, “I love NLP,” through the whole pipeline conceptually:</p><p>Tokenize: [“I”, “love”, “NLP”] → converted to token IDs.</p><p>Embed: each ID becomes a 512-dim vector via the embedding table.</p><p>Add positional encoding: position 0, 1, 2’s sine/cosine patterns are added to each embedding — now the vectors carry both meaning and position.</p><p>Self-attention (per head): for each word, compute Q, K, V. For “love,” its Query gets compared against the Keys of “I,” “love,” and “NLP” — likely attending fairly evenly since it’s a short, simple sentence (longer sentences show far more interesting attention patterns, like “it” attending strongly to its antecedent).</p><p>Concatenate all 8 heads, project back to 512 dims.</p><p>Add &amp; Norm: residual connection adds the original embeddings back, then normalizes.</p><p>Feed-forward network: each of the 3 word-vectors independently passes through the expand-then-compress FFN.</p><p>Add &amp; Norm again.</p><p>Repeat steps 4–8 for all N encoder layers — each layer refining the representation further.</p><p>Decoder (if generating text): starts with a start-token, uses masked self-attention on what it’s generated so far, cross-attention against the final encoder output, its own FFN, and Add &amp; Norm — producing a probability distribution over the vocabulary for the next word, one token at a time.</p><p>That’s the entire architecture, start to finish — every component covered above is just one repeated step in this loop.</p><h3>Where We Are in the Journey</h3><p>BoW → TF-IDF → Word2Vec / GloVe / FastText → RNN → LSTM → GRU → Attention → Transformers → LLMs (You are here)</p><p>This is the architecture underneath BERT, GPT, T5, and effectively every major language model since 2018. Everything from here — LLMs, fine-tuning, RAG, agents — builds directly on top of what’s explained in this article. If you understood this piece properly, you now have the real foundation the rest of modern NLP sits on.</p><p>This wraps the architectural core of the series. Next up: how these Transformer building blocks scale into full Large Language Models, and what changes (and what doesn’t) at that scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fbf2c090717" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP from Scratch — Part 3: RNNs and LSTMs (Teaching Machines to Remember)]]></title>
            <link>https://medium.com/@surisettikrishna17/nlp-from-scratch-part-3-rnns-and-lstms-teaching-machines-to-remember-b31fbb386030?source=rss-580bb06a49c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b31fbb386030</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Surisetti Vamsi krishna]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-08-05T13:31:01.635Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 3 of the “BoW to Transformers” series. Part 1 built BoW/TF-IDF. Part 2 gave words meaning through Word2Vec, GloVe, and FastText — but left one problem unsolved: every word gets exactly one fixed vector, no matter the sentence around it. This part is where sequence finally enters the picture.</p><p>## The Problem This Part Solves</p><p>Take these two sentences:</p><p>“The movie was not good, it was boring.”</p><p>“The movie was not boring, it was good.”</p><p>Same words. Opposite meaning. Flip “good” and “boring,” and the sentiment flips completely. But here’s the catch: Word2Vec, GloVe, and FastText have no idea which word came first, second, or last. They treat a sentence as a set of independent vectors, each computed once, each blind to the words around it.</p><p>To understand a sentence properly, a model needs one more thing none of Part 2’s tools have: memory of what it already read.</p><p>That’s exactly what an RNN was built to give it.</p><p>## What an RNN Actually Is</p><p>A Recurrent Neural Network processes a sequence one element at a time, and — this is the key idea — it carries forward a hidden state that acts like a running summary of everything it has seen so far.</p><p>Think of it like reading a sentence left to right, keeping a mental note as you go, instead of seeing the whole sentence flashed at once. Each new word updates that mental note.</p><p>“I” → “love” → “NLP”</p><p>h0 → h1 → h2</p><p>h0: (nothing read yet)</p><p>h1: (has read “I”)</p><p>h2: (has read “I love”)</p><p>h3: (has read “I love NLP”)</p><p>At every step, the RNN takes two inputs: the current word, and the memory of everything before it. It outputs an updated memory.</p><p>The Formula</p><p>h_t = tanh(W_hh * h_(t-1) + W_xh * x_t + b_h)</p><p>Breaking this down piece by piece:</p><p>x_t — the input at time step t (e.g., the word vector for the current word)</p><p>h_(t-1) — the hidden state carried over from the previous step (the “memory so far”)</p><p>W_hh — weight matrix applied to the previous memory</p><p>W_xh — weight matrix applied to the current input</p><p>b_h — bias term</p><p>tanh — squashes the result into a range between -1 and 1, keeping values stable</p><p>The output at the final time step, h_T, is a single vector that (in theory) has absorbed information from the entire sequence — this is what gets passed on to whatever task you’re solving (classification, translation, next-word prediction).</p><p>The important detail: W_hh and W_xh are the same weights reused at every single time step. That’s what makes it “recurrent” — one small set of weights applied over and over, rather than a separate layer for every word position. This is also what lets an RNN handle sequences of any length with a fixed number of parameters — a real advantage over trying to build one giant fixed-size network for a whole sentence.</p><p>Code (PyTorch)</p><p>import torch<br>import torch.nn as nn</p><p>rnn = nn.RNN(input_size=50, hidden_size=64, batch_first=True)</p><p>x = torch.randn(1, 5, 50) # batch=1, sequence_length=5, embedding_dim=50<br>output, hidden = rnn(x)</p><p>print(output.shape) # [1, 5, 64] -&gt; hidden state at every time step<br>print(hidden.shape) # [1, 1, 64] -&gt; final hidden state only</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5EKxeebsi3l3a1NQuXa7Xg.gif" /></figure><p>The Problem Nobody Wanted: Vanishing Gradients</p><p>This is the part most beginner tutorials gloss over — and it’s the single most important thing to actually understand about why RNNs got replaced.</p><p>RNNs are trained with backpropagation through time (BPTT) — the error signal has to travel backward through every single time step to update the weights. And because the same weight matrix gets multiplied over and over (once per time step), something breaks down mathematically over long sequences:</p><p>dh_T/dh_1 = product of (dh_t/dh_(t-1)) for t = 2 to T</p><p>This is a product of many small numbers, chained together. If those numbers are consistently less than 1 (very common with tanh, whose derivative is at most 0.25), the product shrinks toward zero exponentially fast as the sequence gets longer. That’s the vanishing gradient problem.</p><p>In plain terms: the RNN forgets. By the time it reaches word 50 in a sentence, the gradient signal from word 1 has essentially vanished — the model has no meaningful way to learn that something at the start of a long sequence mattered. This is precisely why plain RNNs struggle with anything beyond short sequences — they’re technically capable of “remembering” long-range dependencies, but in practice, gradient math makes sure they never really learn to.</p><p>(The opposite failure — exploding gradients, where the product blows up instead of vanishing — is also possible and is usually handled with gradient clipping. But vanishing gradients is the deeper, harder problem, and it’s what actually motivated the next architecture.)</p><p>LSTM: Built Specifically to Fix This</p><p>Long Short-Term Memory networks (Hochreiter &amp; Schmidhuber, 1997) were designed with one job: let gradients flow across long sequences without vanishing. The core idea is deceptively simple — instead of forcing all memory through one squashed hidden state, give the network a separate, more protected cell state, and let the network learn what to keep, what to throw away, and what to add, using gates.</p><p>The Three Gates</p><p>Every LSTM cell has three gates, each a small neural network layer with a sigmoid activation (output between 0 and 1, acting like a “how much to let through” dial):</p><ol><li>Forget Gate — decides what to erase from memory: f_t = sigmoid(W_f . [h_(t-1), x_t] + b_f)</li></ol><p>Input Gate — decides what new information to add: i_t = sigmoid(W_i . [h_(t-1), x_t] + b_i), and the candidate: C~_t = tanh(W_C . [h_(t-1), x_t] + b_C)</p><ol><li>Output Gate — decides what to reveal as the current hidden state: o_t = sigmoid(W_o . [h_(t-1), x_t] + b_o)</li></ol><p>Updating the Cell State</p><p>This is the step that actually solves the vanishing gradient problem:</p><p>C_t = f_t ⊙ C_(t-1) + i_t ⊙ C~_t</p><p>⊙ means element-wise multiplication. Notice what’s happening: the new cell state is built by adding to the old one (scaled by gates), not by repeatedly multiplying through a tanh at every step like a plain RNN does. Addition doesn’t shrink gradients the way repeated multiplication does — this is the entire trick. The cell state acts like a conveyor belt running through the whole sequence, and the gates simply decide what gets placed on or taken off it, without forcing every bit of information through a lossy squashing function each time.</p><p>Finally, the hidden state (what gets passed to the next step and to the output):</p><p>h_t = o_t ⊙ tanh(C_t)</p><p>Code (PyTorch)</p><p>import torch<br>import torch.nn as nn</p><p>lstm = nn.LSTM(input_size=50, hidden_size=64, batch_first=True)</p><p>x = torch.randn(1, 5, 50)<br>output, (hidden, cell) = lstm(x)</p><p>print(output.shape) # [1, 5, 64]<br>print(hidden.shape) # [1, 1, 64] -&gt; final hidden state<br>print(cell.shape) # [1, 1, 64] -&gt; final cell state (the “memory conveyor belt”)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3YjKnsRPo21ALJ6WGbc3g.gif" /></figure><p>Notice LSTM returns two states, not one — hidden state (h) for output, and cell state(C) for long-term memory. That extra state is the whole reason LSTMs remember better than plain RNNs.</p><p>GRU: A Lighter Way to Solve the Same Problem</p><p>Gated Recurrent Units (Cho et al., 2014) solve the same vanishing gradient problem LSTM solves, but with a simpler internal structure. Instead of three gates and a separate cell state, GRU uses two gates and lets the hidden state itself carry long-term memory — no separate memory track needed.</p><p>The Two Gates</p><ol><li>Reset Gate — decides how much of the past hidden state to forget when computing the new candidate memory: r_t = sigmoid(W_r . [h_(t-1), x_t] + b_r)</li></ol><p>Update Gate — decides how much of the old hidden state to keep versus how much of the new candidate to use: z_t = sigmoid(W_z . [h_(t-1), x_t] + b_z)</p><p>Both gates output values between 0 and 1, same as in LSTM — a sigmoid acting as a “how much to let through” dial.</p><p>Candidate Hidden State</p><p>The reset gate controls how much of the previous hidden state influences this new candidate:</p><p>h~_t = tanh(W_h . [r_t ⊙ h_(t-1), x_t] + b_h)</p><p>If r_t is close to 0, the model is essentially saying “ignore most of the past, start fresh for this candidate.” If r_t is close to 1, the past strongly shapes the new candidate.</p><p>Final Hidden State — The Update Step</p><p>This is where GRU replaces LSTM’s whole separate cell-state mechanism with a single blend:</p><p>h_t = z_t ⊙ h_(t-1) + (1 — z_t) ⊙ h~_t</p><p>Read this carefully — it’s the core idea of GRU in one line. z_t acts as a mixing knob:</p><p>z_t close to 1 → keep mostly the old hidden state, barely update (protects long-term memory)</p><p>z_t close to 0 → mostly replace with the new candidate (adapts quickly to new information)</p><p>Notice there’s no separate C_t cell state here, unlike LSTM. The hidden state h_t does double duty — it’s both the memory and the output, in one vector. That’s the entire simplification GRU makes over LSTM.</p><p>Why This Still Fixes Vanishing Gradients</p><p>Just like LSTM’s cell-state update, the update step here is built on addition, not repeated multiplication through a squashing function:</p><p>h_t = z_t ⊙ h_(t-1) + (1 — z_t) ⊙ h~_t</p><p>When z_t is close to 1, gradients can flow almost directly from h_t back to h_(t-1) with very little shrinkage — the same trick that saves LSTM from vanishing gradients, just achieved with one gate pair instead of three.</p><p>Code (PyTorch)</p><p>import torch<br>import torch.nn as nn</p><p>gru = nn.GRU(input_size=50, hidden_size=64, batch_first=True)</p><p>x = torch.randn(1, 5, 50)<br>output, hidden = gru(x)</p><p>print(output.shape) # [1, 5, 64]<br>print(hidden.shape) # [1, 1, 64] -&gt; final hidden state (also the “memory”)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vhjI5C7Lm5aRBOW2W8z8g.gif" /></figure><p>Notice GRU returns only one state, not two like LSTM (hidden only, no separate cell). That single-state return is the direct code-level reflection of the simpler math above.</p><p>GRU vs LSTM — What You Actually Give Up</p><p>Gates: LSTM — 3 (forget, input, output) | GRU — 2 (reset, update)</p><p>Separate cell state: LSTM — Yes | GRU — No — hidden state does both jobs</p><p>Parameters: LSTM — More | GRU — Fewer (~25% less typically)</p><p>Training speed: LSTM — Slower | GRU — Faster</p><p>Long-sequence memory: LSTM — Slightly stronger in practice | GRU — Slightly weaker on very long sequences</p><p>Performance on most NLP tasks: LSTM — Strong | GRU — Comparable — often statistically indistinguishable</p><p>When to actually choose GRU over LSTM: smaller datasets, limited compute/GPU memory, faster iteration during prototyping, or when your sequences aren’t extremely long. If you’re squeezing out the last bit of performance on long-document tasks with plenty of compute, LSTM still has a slight edge. For most applied NLP work, the difference in practice is small enough that GRU’s speed advantage makes it the more practical default.</p><p>RNN vs LSTM vs GRU — Quick Comparison</p><p>Handles short sequences: RNN — Fine | LSTM — Fine | GRU — Fine</p><p>Handles long sequences: RNN — Poor (vanishing gradients) | LSTM — Strong | GRU — Strong</p><p>Number of gates: RNN — None | LSTM — 3 (forget, input, output) | GRU — 2 (reset, update)</p><p>Separate cell state: RNN — No | LSTM — Yes | GRU — No</p><p>Training speed: RNN — Fastest | LSTM — Slowest | GRU — Middle ground</p><p>Parameters: RNN — Fewest | LSTM — Most | GRU — Fewer than LSTM</p><p>Typical use today: RNN — Rarely used alone | LSTM — Sequence tasks where you need reliability | GRU — Fast prototyping, resource-constrained settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Esr_ND4MACncNNxUkk4hUQ.gif" /></figure><p>Where This Still Falls Short</p><p>LSTMs solved the memory problem, but they left two real limitations on the table — and both of these are exactly what pulled the field toward attention and transformers.</p><ol><li>They’re still sequential — and that’s slow. To compute h_50, you must first compute h_1 through h_49, one at a time, in order. There’s no way to parallelize this across a GPU the way you can with, say, a convolution. For long sequences and large datasets, this becomes a real training-speed bottleneck.</li><li>2. Even LSTMs have a limit on “long.” The cell state helps a lot, but it’s still one fixed-size vector trying to compress an entire sequence’s worth of relevant history. For very long documents, something written at token 1 can still get diluted by the time you’re at token 500 — it’s a better memory, not an infinite one.</li><li>The fix the field eventually landed on wasn’t “build an even better memory cell.” It was a completely different idea: what if, instead of compressing the whole sequence into one memory vector, the model could look back at every previous word directly, and decide for itself which ones matter most for the word it’s processing right now?</li><li>That question is the entire premise of Attention — and it’s what breaks the sequential bottleneck for good. That’s Part 4.</li></ol><p>Where We Are in the Journey</p><p>BoW → TF-IDF → Word2Vec / GloVe / FastText → RNN → LSTM → Attention → Transformers → LLMs</p><p>(You are here: RNN / LSTM)</p><p>We went from “words with no memory of order” to “a model that reads left to right and remembers.” That’s real progress — this is the architecture that powered machine translation, sentiment analysis, and speech recognition for most of the 2010s. But sequential memory has a ceiling. Attention is where the field breaks past it.</p><p>Part 4 covers Attention — the mechanism that let models stop reading strictly left-to-right and instead look directly at every word in the sequence at once. This is the idea that “Attention Is All You Need” turned into Transformers. Follow along for the rest of the series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b31fbb386030" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP from Scratch : Word2Vec, GloVe, and FastText (Teaching Machines What Words Actually Mean)]]></title>
            <link>https://medium.com/@surisettikrishna17/nlp-from-scratch-word2vec-glove-and-fasttext-teaching-machines-what-words-actually-mean-6bad9544ee79?source=rss-580bb06a49c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bad9544ee79</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Surisetti Vamsi krishna]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 14:31:01 GMT</pubDate>
            <atom:updated>2026-07-27T14:31:01.579Z</atom:updated>
            <content:encoded><![CDATA[<p>This is Part 2 of the “BoW to Transformers” series. In Part 1, we built Bag of Words and TF-IDF by hand — and ended on a confession: neither of them understands a single word. They just count. This part fixes that.</p><p>## The Problem We Left Unsolved</p><p>Quick recap of where Part 1 left us stuck. In TF-IDF, “good” and “great” are two completely unrelated columns in a matrix. So are “king” and “queen.” So are “Delhi” and “Mumbai.” To TF-IDF, every word is an island — equally distant from every other word, no matter how related they actually are in meaning.</p><p>That’s not a small gap. That’s the entire problem of meaning missing from the model.</p><p>So here’s the real question this part answers:</p><p>Can we represent a word as a vector such that words with similar meaning end up close together in space?</p><p>The answer arrived in 2013, and it changed NLP forever: Word2Vec.</p><p>## The Idea That Changed Everything</p><p>Word2Vec is built on one deceptively simple linguistic idea, first stated by linguist J.R. Firth:</p><p>“You shall know a word by the company it keeps.”</p><p>In other words — words that appear in similar contexts tend to have similar meaning. “Coffee” and “tea” show up near words like “drink,” “cup,” “morning,” “hot.” So a model that learns to predict a word from its neighbors, or neighbors from a word, ends up learning meaning as a side effect.</p><p>That’s the whole trick. Word2Vec doesn’t try to “understand” language. It just plays a very simple prediction game, millions of times, and meaning emerges from the pattern.</p><p>## Two Flavors of Word2Vec</p><p>CBOW (Continuous Bag of Words)</p><p>Given the surrounding words, predict the middle word.</p><p>Sentence: “The quick brown fox jumps over the lazy dog”</p><p>Window size = 2</p><p>Context: [quick, brown, jumps, over] → Predict: “fox”</p><p>Skip-Gram</p><p>The reverse — given the middle word, predict the surrounding words.</p><p>Input: “fox” → Predict: [quick, brown, jumps, over]</p><p>Rule of thumb: CBOW is faster and works better with frequent words. Skip-Gram is slower but shines on rare words and smaller datasets — which is why Skip-Gram tends to be the more popular choice in practice.</p><p>## What’s Actually Happening Under the Hood</p><p>Here’s the part most explanations skip over, and the part that actually matters if you want to use this properly, not just quote it in an interview.</p><p>Word2Vec is a shallow neural network — one hidden layer, no activation function on it, just a linear projection. The trick isn’t the network architecture. The trick is what you throw away after training.</p><p>You train the network to predict context words. Once training is done, you discard the output layer entirely. What you keep is the hidden layer’s weight matrix — and each row of that matrix becomes the vector representation for one word in your vocabulary.</p><p>W is a V × d matrix — V rows (one per vocabulary word) and d columns (the embedding size, commonly 100–300). Each row wᵢis a dense, low-dimensional vector — a massive downgrade from TF-IDF’s sparse 50,000-length vectors, and yet it captures far more.</p><p>The Softmax Bottleneck (and Why You’ll Hear “Negative Sampling”)</p><p>Training this naively means computing a softmax over the entire vocabulary for every single training step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*Po5Da-STURwdC93PyXytJw.png" /></figure><p>With a 100,000-word vocabulary, that denominator sum is brutal to compute millions of times. Word2Vec’s actual innovation — the reason it could train at scale in 2013 — was negative sampling: instead of updating weights against the entire vocabulary, update against the true context word plus a handful (5–20) of randomly sampled “negative” words that aren’t in the context. This turns an expensive multi-class problem into a cheap set of binary classification problems, and it’s the detail that made Word2Vec fast enough to train on billions of words.</p><p>## The Famous Result: Vector Arithmetic</p><p>This is the moment that made the NLP world sit up in 2013:</p><p>king — man + woman ≈ queen</p><p>Read that again. Nobody told the model that gender is a concept. Nobody labeled anything. The model just predicted context words over and over — and out of that, directions in vector space started encoding relationships: gender, tense, country-capital, plural-singular. Meaning became geometry.</p><p>Code (Gensim)</p><p>from gensim.models import Word2Vec</p><p>sentences = [[“i”, “love”, “nlp”], [“i”, “love”, “deep”, “learning”], [“nlp”, “is”, “a”, “part”, “of”, “deep”, “learning”], [“king”, “is”, “a”, “man”], [“queen”, “is”, “a”, “woman”]]</p><p>model = Word2Vec(sentences, vector_size=50, window=2, min_count=1, sg=1) # sg=1 -&gt; Skip-Gram</p><p>print(model.wv[“nlp”]) # dense 50-dim vector</p><p>print(model.wv.most_similar(“nlp”)) # closest words by cosine similarity</p><p>On tiny toy data like this, the vectors won’t show much — Word2Vec needs real scale (Wikipedia-sized corpora) to produce those famous analogies. That itself is an important, honest caveat: Word2Vec is data-hungry.</p><p>## GloVe: A Different Philosophy, Same Goal</p><p>Word2Vec learns from local context windows — it never sees the corpus as a whole, only small sliding windows. GloVe (Global Vectors, Stanford, 2014) asks: why throw away global statistics?</p><p>GloVe starts by building a co-occurrence matrix X, whereXᵢⱼ counts how often word i appears near word j across the entire corpus. Then it learns vectors such that their dot product approximates the log of that co-occurrence count:</p><p>wᵢᵀw̃ⱼ + bᵢ + b̃ⱼ = log(Xᵢⱼ)</p><p>The intuition: if “ice” and “solid” co-occur far more than “ice” and “gas,” that ratio should be baked directly into the vectors — not learned indirectly through prediction, but fit directly to global co-occurrence statistics.</p><p>Word2Vec vs GloVe, in one line: Word2Vec is predictive (learns by guessing context), GloVe is count-based (learns by fitting to global statistics). In practice, their resulting embeddings behave fairly similarly — this is more a difference in training philosophy than in output quality.</p><p>## FastText: Fixing the Biggest Blind Spot</p><p>Here’s a question that breaks both Word2Vec and GloVe: what happens when you meet a word you’ve never seen during training?</p><p>Answer: nothing good. Both treat “unbelievable” and “unbelievably” as two completely unrelated tokens, each needing its own training exposure. And any truly unseen word — a typo, a rare name, a new slang term — has no vector at all. This is the out-of-vocabulary (OOV) problem, and for morphologically rich languages (Hindi, Telugu, Finnish, German) it’s a serious weakness.</p><p>FastText (Facebook, 2016) fixes this with one elegant change: instead of learning a vector per whole word, it learns vectors for character n-grams, and represents a word as the sum of its n-gram vectors.</p><p>Word: “learning” (with boundary symbols, n=3)</p><p>n-grams: “&lt;le”, “lea”, “ear”, “arn”, “rni”, “nin”, “ing”, “ng&gt;”</p><p>vector(“learning”) = sum of vectors of all these n-grams</p><p>The payoff: now “learning” and “learn” and “learner” share n-grams, so they share meaning components automatically. And a brand-new, never-seen-before word can still get a reasonable vector, built from n-grams the model has seen — no OOV problem.</p><p>Code (Gensim FastText)</p><p>from gensim.models import FastText</p><p>model = FastText(sentences, vector_size=50, window=2, min_count=1, sg=1)</p><p>print(model.wv[“learning”])</p><p>print(model.wv.most_similar(“learning”))</p><p># The real test — a word NEVER seen during training still gets a vector:</p><p>print(model.wv[“learnable”])</p><p>## Comparison Table — Which One Do You Actually Reach For?</p><p>Aspect | Word2Vec | GloVe | FastText</p><p>Learns from | Local context window | Global co-occurrence stats | Character n-grams</p><p>Handles unseen (OOV) words | No | No | Yes</p><p>Good for morphologically rich languages | Weak | Weak | Strong</p><p>Training speed | Fast | Moderate (needs co-occ. matrix) | Slower (n-gram overhead)</p><p>Captures word analogies | Yes | Yes | Yes, slightly less crisp</p><p>Best use case | General-purpose, large clean corpora | Static, pre-trained embeddings for downstream tasks | Any real-world text with typos, slang, rare/compound words</p><p>If you’re working with clean English text and a huge corpus — Word2Vec or GloVe both do the job. If you’re working with noisy, real-world, or morphologically rich text (which, if you’ve built anything like a JD–skill matcher on real job postings, you already know is most real text) — FastText’s OOV handling alone can be the deciding factor.</p><p>## The Limitation That Sets Up Part 3</p><p>Here’s the catch none of these three fully solve, and it’s the one that matters most:</p><p>Every one of these gives a word exactly one fixed vector — no matter the sentence it’s in.</p><p>“I sat by the river bank.”</p><p>“I withdrew cash from the bank.”</p><p>Same word, wildly different meaning — but Word2Vec, GloVe, and FastText all hand you back the same vector for “bank” both times. These are called static embeddings, and this is precisely the ceiling they can’t break through. Meaning here still isn’t context-aware; it’s fixed the moment training ends.</p><p>Solving that — vectors that change depending on the sentence around them — is what pulled the field toward RNNs, then Attention, then Transformers. That’s Part 3.</p><p>## Where We Are in the Journey</p><p>BoW → TF-IDF → Word2Vec / GloVe / FastText → RNN → Attention → Transformers → LLMs</p><p>You are here: right after static word embeddings, right before sequence models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5LW9du49JSGKrvhwO_tFg.gif" /></figure><p>We’ve gone from “just count words” to “words that live in meaningful space.” That’s a real leap. But space isn’t enough — the next leap is context, and that’s where things get genuinely interesting.</p><p>Part 3 picks up with RNNs and the sequence problem — why order matters, why static vectors aren’t enough, and how attention finally cracked context. Follow along for the rest of the series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bad9544ee79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP from Scratch — Part 1: Bag of Words and TF-IDF (With Math, Code, and Intuition)]]></title>
            <link>https://medium.com/@surisettikrishna17/nlp-from-scratch-part-1-bag-of-words-and-tf-idf-with-math-code-and-intuition-b358284c8b94?source=rss-580bb06a49c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b358284c8b94</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[text]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[bow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Surisetti Vamsi krishna]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 12:31:01 GMT</pubDate>
            <atom:updated>2026-07-26T12:31:01.548Z</atom:updated>
            <content:encoded><![CDATA[<p>This is Part 1 of a series tracing NLP’s evolution — from Bag of Words to Transformers. If you’ve ever wondered how a machine turns “I love NLP” into numbers it can actually learn from, start here.</p><p>## Why This Matters</p><p>Every NLP model — from a spam filter you built in college to GPT-style transformers — starts with the same problem: text is not numbers. Machine learning models only understand numbers. So the very first question in NLP is:</p><p>How do we turn text into vectors, without losing meaning?</p><p>Bag of Words (BoW) and TF-IDF are the earliest, simplest answers to that question. They’re not “outdated junk” — they’re still used today in search engines, recommendation systems, and as fast baselines before anyone reaches for a transformer. Understanding them properly is what makes Word2Vec, attention, and transformers actually click later — because those methods exist specifically to fix what BoW and TF-IDF get wrong.</p><p>Part 1: Bag of Words (BoW)</p><p>The Core Idea</p><p>Bag of Words treats a sentence as exactly that — a bag. Throw all the words in, ignore grammar, ignore order, just count how often each word appears.</p><p>Example, three documents:</p><p>D1: “I love NLP”</p><p>D2: “I love deep learning”</p><p>D3: “NLP is a part of deep learning”</p><p>Step 1 — Build vocabulary (unique words across all documents):</p><p>[“I”, “love”, “NLP”, “deep”, “learning”, “is”, “a”, “part”, “of”]</p><p>Step 2 — Represent each document as a vector of word counts:</p><p>D1: I=1, love=1, NLP=1, deep=0, learning=0, is=0, a=0, part=0, of=0</p><p>D2: I=1, love=1, NLP=0, deep=1, learning=1, is=0, a=0, part=0, of=0</p><p>D3: I=0, love=0, NLP=1, deep=1, learning=1, is=1, a=1, part=1, of=1</p><p>That’s it. That’s Bag of Words. Each row is now a numeric vector — something a machine learning model can consume.</p><p>The Formula</p><p>For document d and word w:</p><p>BoW(w, d) = count of w in d</p><p>No logarithms, no weighting — just raw frequency. Simple by design.</p><p>Code (Python, scikit-learn)</p><p>from sklearn.feature_extraction.text import CountVectorizer</p><p>docs = [“I love NLP”, “I love deep learning”, “NLP is a part of deep learning”]</p><p>vectorizer = CountVectorizer()</p><p>bow_matrix = vectorizer.fit_transform(docs)</p><p>print(vectorizer.get_feature_names_out())</p><p>print(bow_matrix.toarray())</p><p>Where BoW Breaks Down</p><p>No word order — “dog bites man” and “man bites dog” get identical treatment in a unigram BoW. Meaning is completely different; the vector doesn’t know that.</p><p>No importance weighting — common words like “the”, “is”, “a” get the same treatment as meaningful words like “NLP” or “transformer”. A word appearing in every document tells you nothing about what makes a document unique, but BoW doesn’t know that.</p><p>Sparse and high-dimensional — vocabulary of 50,000 words means every document is a 50,000-length vector, mostly zeros. Wasteful, and doesn’t scale.</p><p>No semantic meaning — “good” and “great” are as unrelated to BoW as “good” and “banana.” It only counts, it doesn’t understand.</p><p>That third problem — treating every word as equally important — is exactly what TF-IDF was built to fix.</p><p>Part 2: TF-IDF (Term Frequency — Inverse Document Frequency)</p><p>The Core Idea</p><p>TF-IDF asks a smarter question than BoW: not just “how often does this word appear in this document,” but “how important is this word to this document, relative to all other documents?”</p><p>A word that appears a lot in one document but rarely elsewhere is probably a strong signal of what that document is about. A word that appears in every document (like “the”, “is”) is basically noise. TF-IDF rewards the first kind of word and punishes the second.</p><p>It’s made of two parts multiplied together.</p><p>Part A: Term Frequency (TF)</p><p>How often a word appears in a specific document, normalized by document length:</p><p>TF(w, d) = (count of w in d) / (total number of words in d)</p><p>Normalizing by length matters — a word appearing 3 times in a 10-word document is more significant than the same word appearing 3 times in a 1,000-word document.</p><p>Part B: Inverse Document Frequency (IDF)</p><p>How rare a word is across the entire corpus (collection of documents):</p><p>IDF(w) = log( N / (1 + df(w)) )</p><p>Where: N = total number of documents, df(w) = number of documents containing word w, and the +1 in the denominator avoids division by zero (smoothing).</p><p>Notice the logic: if a word appears in every document, df(w) is approximately N, so the fraction goes toward 1, and log(1) = 0 — the word gets zero weight. That’s TF-IDF automatically killing words like “the” and “is” without you writing a stopword list.</p><p>Combine: TF-IDF</p><p>TF-IDF(w, d) = TF(w, d) × IDF(w)</p><p>Worked Example</p><p>Using the same 3 documents:</p><p>D1: “I love NLP”, D2: “I love deep learning”, D3: “NLP is a part of deep learning”</p><p>Let’s compute TF-IDF for the word “NLP” in D1.</p><p>TF(“NLP”, D1) = 1 occurrence / 3 total words = 0.333</p><p>IDF(“NLP”): “NLP” appears in D1 and D3 → df = 2, N = 3</p><p>IDF(“NLP”) = log(3 / (1+2)) = log(1) = 0</p><p>Interesting — with this particular smoothing formula, since “NLP” appears in 2 of 3 docs, IDF comes out to 0, meaning it’s treated as not very distinctive here (small corpus effect — with more documents this evens out). Now compare with “love”:</p><p>TF(“love”, D1) = 1/3 = 0.333</p><p>IDF(“love”): appears in D1, D2 → df = 2</p><p>Same as NLP in this toy example — small-corpus effect. This is why in real projects, TF-IDF needs a reasonably sized corpus to show its real power; on 3 toy sentences the IDF differences are subtle. Scale it to hundreds of documents and the “the/is/a” words get crushed toward zero while distinctive words rise clearly — that’s the effect you’ll see in the code below.</p><p>Code (Python, scikit-learn)</p><p>from sklearn.feature_extraction.text import TfidfVectorizer</p><p>docs = [“I love NLP”, “I love deep learning”, “NLP is a part of deep learning”]</p><p>tfidf = TfidfVectorizer()</p><p>tfidf_matrix = tfidf.fit_transform(docs)</p><p>import pandas as pd</p><p>df = pd.DataFrame(tfidf_matrix.toarray(), columns=tfidf.get_feature_names_out())</p><p>print(df.round(3))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*3ALMINCVWajOoz2QXZQCEw.gif" /></figure><p>Note: sklearn’s actual IDF formula has its own smoothing variant (log((1+N)/(1+df)) + 1 by default), slightly different from the textbook one above — always check TfidfVectorizer(smooth_idf=…) docs before comparing numbers by hand.</p><p>Where TF-IDF Still Falls Short</p><p>TF-IDF fixes the “importance” problem, but it inherits BoW’s deeper flaw: it still has no idea what words mean.</p><p>“good” and “great” are still unrelated vectors, even though they’re near-synonyms.</p><p>Word order is still ignored — TF-IDF vectors for “not good, bad” and “good, not bad” can look confusingly similar.</p><p>It’s still sparse and high-dimensional for large vocabularies.</p><p>No notion of context — the word “bank” gets one fixed weight whether you mean “river bank” or “money bank.”</p><p>This is exactly the gap that Word2Vec, GloVe, and FastText were built to close — dense vectors that capture meaning, not just frequency. That’s Part 2 of this series.</p><p>BoW vs TF-IDF — Quick Comparison</p><p>What it measures: BoW = raw word count. TF-IDF = weighted importance.</p><p>Common words (the, is, a): BoW gives same weight as rare words. TF-IDF automatically down-weights them.</p><p>Formula complexity: BoW is very simple. TF-IDF is simple, but two-part.</p><p>Captures word order: Neither does.</p><p>Captures meaning/semantics: Neither does.</p><p>Vector type: Both are sparse, high-dimensional.</p><p>Best used for: BoW — quick baselines, small vocab tasks. TF-IDF — search engines, keyword extraction, document similarity.</p><p>Still used in industry? BoW rarely alone. TF-IDF — yes, in search/IR systems and baseline models.</p><p>Where This Fits in the Bigger Picture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TP5HFq5YEDHwBWCbxcADgQ.gif" /></figure><p>BoW → TF-IDF → Word2Vec / GloVe / FastText → RNN → Attention → Transformers → LLMs</p><p>Each step exists to fix a specific limitation of the step before it:</p><p>BoW → TF-IDF: fixes “all words are equally important” (wrong)</p><p>TF-IDF → Word2Vec: fixes “words have no meaning” (wrong)</p><p>Word2Vec → RNN: fixes “no sense of sequence/order”</p><p>RNN → Attention/Transformers: fixes “can’t handle long-range context efficiently”</p><p>Once you see this as a chain of “here’s what broke, here’s the fix,” the whole field stops feeling like memorizing 10 unrelated algorithms and starts feeling like one continuous story.</p><p>What’s Next</p><p>Part 2 of this series covers Word2Vec, GloVe, and FastText — how we get from sparse counting to dense vectors that actually place “king” and “queen” near each other in vector space.</p><p>If this helped, follow for the rest of the series — one part a week, BoW all the way to transformers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b358284c8b94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Neural Networks Work — Complete Pipeline]]></title>
            <link>https://medium.com/@surisettikrishna17/how-neural-networks-work-complete-pipeline-c0f32e53aba9?source=rss-580bb06a49c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0f32e53aba9</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Surisetti Vamsi krishna]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 13:01:01 GMT</pubDate>
            <atom:updated>2026-07-05T13:01:01.788Z</atom:updated>
            <content:encoded><![CDATA[<p>This is Part 5 of the Deep Learning from Scratch series. We’ve covered Single Layer Perceptrons (SLP), Multi-Layer Perceptrons (MLP), Activation Functions, and Optimizers. Now it’s time to connect every piece and walk through the complete neural network pipeline — end to end, with real numbers and real intuition.</p><h3>1. What Is a Neural Network Really</h3><p>Think of a neural network as a very sophisticated guessing machine. You show it thousands of examples — pictures of cats and dogs, house prices, spam emails — and it gradually learns the pattern connecting inputs to outputs.</p><p>A good analogy: imagine you’re teaching a child to recognize dogs. You don’t give them a rulebook. You just show them many examples, correct their mistakes, and they eventually internalize the pattern. Neural networks learn the exact same way — through examples and error correction.</p><h3>2. Big Picture: Neural Network as Function Approximator</h3><p>Mathematically, a neural network is just a function: f(x) = y. You feed in an input vector x (say, pixel values of an image), and it outputs y (a class label, a probability, a number). The network’s job is to approximate the true underlying function that maps inputs to outputs — even when that function is incredibly complex.</p><p>This is sometimes called the Universal Approximation Theorem: given enough neurons and layers, a neural network can approximate any continuous function to arbitrary precision. That’s the theoretical superpower. The practical challenge is training it efficiently.</p><h3>3. Quick Recap: Single Neuron (SLP)</h3><p>A single neuron (Perceptron) is the atomic unit of a neural network. It takes multiple inputs, multiplies each by a weight, sums them up, adds a bias, and passes the result through an activation function.</p><p>The formula: output = activation(w₁x₁ + w₂x₂ + … + wₙxₙ + b)</p><p>Where w = weights (how important is each input), b = bias (shifts the output), and activation = a non-linear function (Sigmoid, ReLU, Tanh). A single neuron can only draw a straight line through data — it can only solve linearly separable problems. That limitation is why we need layers.</p><h3>4. Why We Stack Layers (MLP) — The Non-Linearity Problem</h3><p>The classic example of why a single neuron fails is the XOR problem. XOR outputs 1 when inputs differ (0,1 or 1,0) and 0 when they’re the same. No single straight line can separate these classes — it’s not linearly separable.</p><p>The solution: add hidden layers with non-linear activation functions. Each layer learns a new representation of the data. The hidden layer transforms the XOR inputs into a space where they become linearly separable — and the output layer can then draw that line. This is the core power of deep learning: hierarchical feature learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G20GyOA1YoieKmsRW0v8XQ.gif" /></figure><h3>5. Forward Pass Step by Step</h3><p>The forward pass is data flowing from input to output. Let’s trace it with real numbers using a tiny 2–2–1 network (2 inputs, 2 hidden neurons, 1 output). We’ll use Sigmoid activation: σ(x) = 1/(1+e⁻ˣ).</p><p>Given: Input x = [1.0, 0.5], Weights W1 = [[0.2, 0.8], [0.4, 0.6]], Bias b1 = [0.1, 0.1]</p><p>Step 1 — Hidden layer pre-activation (z¹):</p><p>z¹ = W1 · x + b1</p><p>z¹[0] = (0.2)(1.0) + (0.8)(0.5) + 0.1 = 0.2 + 0.4 + 0.1 = 0.70</p><p>z¹[1] = (0.4)(1.0) + (0.6)(0.5) + 0.1 = 0.4 + 0.3 + 0.1 = 0.80</p><p>Step 2 — Apply Sigmoid activation (a¹):</p><p>a¹[0] = σ(0.70) ≈ 0.668</p><p>a¹[1] = σ(0.80) ≈ 0.690</p><p>Step 3 — Output layer (W2 = [0.5, 0.9], b2 = 0.1):</p><p>z² = (0.5)(0.668) + (0.9)(0.690) + 0.1 = 0.334 + 0.621 + 0.1 = 1.055</p><p>a² = σ(1.055) ≈ 0.742 ← this is the network’s prediction (74.2% probability of class 1).</p><p>This entire computation — input to prediction — is the forward pass. It’s just matrix multiplication, addition, and applying activation functions repeatedly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HUFuILZba6krXI5qtDD7Q.gif" /></figure><h3>6. Loss Function</h3><p>After the forward pass, the network has made a prediction. But how wrong is it? That’s what the loss function measures. It takes the network’s output and the true label and returns a single number: the error.</p><p>Two most common loss functions:</p><p>Mean Squared Error (MSE) — for regression: MSE = (1/n) x sum of (y_pred — y_true)². Example: predicted 0.742, true label 1.0 =&gt; MSE = (0.742–1.0)² = 0.0666.</p><p>Binary Cross-Entropy (BCE) — for binary classification: BCE = -[y * log(y_hat) + (1-y) * log(1-y_hat)]. BCE punishes confident wrong answers disproportionately hard.</p><p>The loss is the feedback signal. Without it, the network has no idea how to improve. The entire goal of training is to minimize this number.</p><h3>7. Backpropagation</h3><p>Backpropagation is how the network learns from its mistakes. The intuition: think of it as blame assignment. The output layer made an error — how much of that error is each weight responsible for? Backprop answers this question systematically, starting from the output and working backwards layer by layer.</p><p>The math behind backprop is the chain rule from calculus. If loss depends on output, and output depends on weights, then: dL/dw = (dL/d_output) x (d_output/dz) x (dz/dw). Each term is a local gradient — how much does this layer’s output change if we tweak this weight slightly?</p><p>For our example: the output layer’s weight W2 gets updated first. Then those gradients are multiplied by the hidden layer’s local gradients to compute how W1 should change. This “chaining” of gradients is backpropagation.</p><p>Key insight: backprop does not re-run the forward pass. It reuses intermediate values (called the computation graph) already computed during the forward pass to efficiently calculate all gradients in one backward sweep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6rPFbLesnWDeRLL6op0UQ.gif" /></figure><h3>8. Gradient Descent and Optimizers</h3><p>Imagine a hilly landscape. The loss function is the terrain. You’re a ball placed somewhere on that landscape, and your goal is to roll to the lowest valley (minimum loss). Gradient descent is the algorithm that rolls you downhill.</p><p>The weight update rule: w = w — lr * (dL/dw). Where lr (learning rate) controls the step size. Too large: you overshoot the valley. Too small: training takes forever.</p><p>Three common optimizers you need to know:</p><p>SGD (Stochastic Gradient Descent) — updates weights after each sample or mini-batch. Fast but noisy.</p><p>Momentum — adds velocity to the update. Remembers the direction of previous steps, smoothing the trajectory and helping escape shallow local minima.</p><p>Adam (Adaptive Moment Estimation) — the default choice for most models. Adapts the learning rate for each weight individually using running averages of gradients. Works well out of the box.</p><h3>9. Activation Functions Recap</h3><p>Activation functions inject non-linearity into the network. Without them, stacking layers would just be one giant linear transformation — useless for complex patterns.</p><p>Quick cheat sheet:</p><p>Sigmoid — outputs (0,1), used in output layer for binary classification. Suffers from vanishing gradients in deep networks.</p><p>Tanh — outputs (-1,1), zero-centered, slightly better than Sigmoid for hidden layers. Still has vanishing gradient issues in very deep nets.</p><p>ReLU (Rectified Linear Unit) — f(x) = max(0, x). Default for hidden layers in modern networks. Fast, efficient, doesn’t saturate for positive values.</p><p>Leaky ReLU / ELU — fixes the dying ReLU problem (neurons stuck at 0) by allowing a small negative slope.</p><p>Softmax — output layer for multi-class classification. Converts raw scores to a probability distribution that sums to 1.</p><h3>10. The Full Training Loop</h3><p>Now let’s tie everything together. Here’s exactly what happens during training, step by step:</p><ol><li>Initialize weights randomly (small values near zero).</li><li>2. For each epoch (one full pass over training data):</li><li>3. Sample a mini-batch of training examples.</li><li>4. Forward pass: compute predictions.</li><li>5. Compute loss: how far off were the predictions?</li><li>6. Backward pass (backprop): compute gradients dL/dw for all weights.</li><li>7. Update weights: w = w — lr * gradient (using optimizer).</li><li>8. Repeat steps 3–7 until loss converges or epochs are exhausted.</li><li>An epoch is one complete pass through the entire dataset. If you have 10,000 samples and a batch size of 100, one epoch = 100 iterations. You typically run dozens to hundreds of epochs during training.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3VlT250YbYy_w4eooebgew.gif" /></figure><h3>11. Mini Code Example: Neural Network from Scratch in NumPy</h3><p>Below is a complete 2–3–1 neural network in pure NumPy. Architecture: 2 inputs, 3 hidden neurons (Sigmoid), 1 output (Sigmoid). Trained on XOR data.</p><pre>import numpy as np<br><br># ---- Activation function ----<br>def sigmoid(x):<br>    return 1 / (1 + np.exp(-x))<br><br>def sigmoid_deriv(x):<br>    s = sigmoid(x)<br>    return s * (1 - s)<br><br># ---- XOR dataset ----<br>X = np.array([[0,0],[0,1],[1,0],[1,1]])  # (4, 2)<br>y = np.array([[0],[1],[1],[0]])          # (4, 1)<br><br># ---- Initialize weights (2-3-1 architecture) ----<br>np.random.seed(42)<br>W1 = np.random.randn(2, 3) * 0.1   # input -&gt; hidden<br>b1 = np.zeros((1, 3))<br>W2 = np.random.randn(3, 1) * 0.1   # hidden -&gt; output<br>b2 = np.zeros((1, 1))<br><br>lr = 0.5   # learning rate<br><br># ---- Training loop ----<br>for epoch in range(10000):<br>    # --- Forward pass ---<br>    z1 = X @ W1 + b1            # (4, 3)<br>    a1 = sigmoid(z1)            # hidden activations<br>    z2 = a1 @ W2 + b2           # (4, 1)<br>    a2 = sigmoid(z2)            # output predictions<br><br>    # --- Loss (MSE) ---<br>    loss = np.mean((a2 - y) ** 2)<br><br>    # --- Backward pass ---<br>    d_loss = 2 * (a2 - y) / y.shape[0]<br>    d_z2 = d_loss * sigmoid_deriv(z2)<br>    dW2 = a1.T @ d_z2<br>    db2 = np.sum(d_z2, axis=0, keepdims=True)<br><br>    d_a1 = d_z2 @ W2.T<br>    d_z1 = d_a1 * sigmoid_deriv(z1)<br>    dW1 = X.T @ d_z1<br>    db1 = np.sum(d_z1, axis=0, keepdims=True)<br><br>    # --- Weight update (SGD) ---<br>    W2 -= lr * dW2<br>    b2 -= lr * db2<br>    W1 -= lr * dW1<br>    b1 -= lr * db1<br><br>    if epoch % 2000 == 0:<br>        print(f&#39;Epoch {epoch}, Loss: {loss:.4f}&#39;)<br><br>print(&#39;\nFinal predictions:&#39;)<br>print(np.round(a2, 2))  # Should be close to [[0],[1],[1],[0]]</pre><h3>12. Common Beginner Mistakes</h3><p>These are the mistakes that trip up almost every beginner. Knowing them in advance saves you hours of debugging.</p><p>Vanishing Gradients — When using Sigmoid or Tanh in deep networks, gradients become extremely small as they flow backwards. Earlier layers barely learn. Solution: use ReLU in hidden layers, and/or Batch Normalization.</p><p>Bad Weight Initialization — Initializing all weights to zero means all neurons compute the same gradient and learn the same thing (symmetry problem). Use small random values (He or Xavier initialization).</p><p>Learning Rate Too High — Loss oscillates or explodes. Too low — training never converges. Start with 0.001 with Adam. Use learning rate schedulers for long training runs.</p><p>Not Normalizing Inputs — Features with vastly different scales (e.g., age=25 vs income=50000) make gradient descent unstable. Always normalize inputs to zero mean and unit variance.</p><p>Overfitting — Your network memorizes training data but fails on new data. Signs: training loss drops, validation loss rises. Solutions: Dropout, L2 regularization, more data, early stopping.</p><h3>13. Summary and What’s Next</h3><p>You now understand the complete neural network pipeline. Let’s recap the key concepts:</p><p>A neural network is a function approximator built from stacked layers of neurons.</p><p>The forward pass computes predictions through matrix multiplications and activations.</p><p>The loss function measures prediction error.</p><p>Backpropagation uses the chain rule to assign blame to each weight.</p><p>Gradient descent (with Adam/SGD) updates weights to minimize loss.</p><p>This full cycle repeats for many epochs until the model converges.</p><p>What comes next in this series?</p><p>Convolutional Neural Networks (CNNs) — how computers see images by learning spatial patterns through filters and pooling layers.</p><p>Recurrent Neural Networks (RNNs) / LSTMs — how neural networks handle sequential data like text, time series, and speech, by maintaining memory across timesteps.</p><h3>Try It Yourself</h3><p>Now that you’ve read the full pipeline, it’s time to code it yourself. Here’s your challenge:</p><p>Build a 2-layer neural network from scratch using only NumPy and train it to solve the XOR problem. Your network should:</p><ol><li>Have architecture 2–4–1 (2 inputs, 4 hidden neurons, 1 output)</li><li>2. Use ReLU activation in the hidden layer and Sigmoid in the output layer</li><li>3. Train for 5000 epochs with learning rate 0.01</li><li>4. Print loss every 500 epochs</li><li>5. Achieve a final loss below 0.01</li></ol><p>Bonus: Try replacing Sigmoid with Tanh in the hidden layer and compare convergence speed. Can you get it to train faster?</p><p>If you found this article helpful, follow for the next parts on CNNs and RNNs. Share your solutions in the comments — let’s learn together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0f32e53aba9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizers in Neural Networks:]]></title>
            <link>https://medium.com/@surisettikrishna17/optimizers-in-neural-networks-10c58ed5aaa0?source=rss-580bb06a49c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/10c58ed5aaa0</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[optimizer]]></category>
            <category><![CDATA[ann]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Surisetti Vamsi krishna]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 16:23:45 GMT</pubDate>
            <atom:updated>2026-06-25T16:23:45.190Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how a neural network actually learns? You give it thousands of images of cats and dogs, and somehow it figures out the difference. But how does it improve itself over time?</p><p>The answer lies in Optimizers — the algorithms that power the learning process in neural networks. In this article, we will explore all the major optimizers used in deep learning, explained in simple language with visual examples. By the end, you will know exactly which optimizer to use and why.</p><p>Let’s dive in! 🚀</p><h3>What is an Optimizer?</h3><p>Imagine you are blindfolded on a hilly landscape, and your goal is to reach the lowest point (valley). You can only feel the slope under your feet. So you take small steps in the direction where the ground goes downhill. That is exactly what an optimizer does in a neural network!</p><p>In technical terms, a neural network has weights (parameters) that need to be adjusted to minimize the Loss Function — a measure of how wrong the model’s predictions are. The optimizer decides how to update these weights after each training step.</p><p>The core formula for any weight update is:</p><p>New Weight = Old Weight − (Learning Rate × Gradient)</p><h3>Gradient Descent — The Foundation of All Optimizers</h3><p>Before we explore individual optimizers, we need to understand the concept they all build upon: Gradient Descent.</p><p>A gradient is just the slope or rate of change of the loss function with respect to the model weights. If the gradient is positive, the weight is too high — decrease it. If it’s negative, increase it. This is how the model learns!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJX6HJ1ebxDZR-03VzzAlg.gif" /></figure><p>There are 3 variants of Gradient Descent, based on how much data is used per update:</p><ol><li>Batch Gradient Descent — Uses ALL training data. Accurate but very slow for large datasets.</li><li>2. Stochastic Gradient Descent (SGD) — Uses ONE sample at a time. Fast but very noisy.</li><li>3. Mini-Batch Gradient Descent — Uses a small batch (e.g., 32 or 64 samples). Best of both worlds! This is the most popular method used in practice.</li></ol><h3>1. SGD — Stochastic Gradient Descent</h3><p>SGD is the simplest optimizer. It updates the weights after looking at just one training example (or a mini-batch) at a time.</p><p>Formula: w = w − η ⋅ ∇L(w)</p><p>Where: w = weight, η = learning rate, ∇L(w) = gradient of loss</p><p>🟢 Pros: Simple, fast, works well for simple problems</p><p>🔴 Cons: Very noisy updates, can bounce around and miss the minimum, sensitive to learning rate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*f9D4i6equYEBmfOHpJAYMA.gif" /></figure><h3>2. SGD with Momentum</h3><p>Think of a ball rolling down a hill. On a flat hill (standard SGD), the ball moves slowly and erratically. But if the ball builds up speed over time (momentum), it moves faster and smoother toward the valley!</p><p>Momentum adds a velocity term that accumulates past gradients. This helps the optimizer accelerate in the right direction and dampens oscillations.</p><p>Formulas:</p><p>v = β × v − η × ∇L(w)</p><p>w = w + v</p><p>Where β (beta) is the momentum coefficient, typically 0.9</p><p>🟢 Pros: Faster convergence than plain SGD, handles noisy gradients better</p><p>🔴 Cons: Introduces an extra hyperparameter (β), can overshoot the minimum</p><h3>3. AdaGrad — Adaptive Gradient Algorithm</h3><p>AdaGrad adapts the learning rate for each parameter individually. Parameters that are updated frequently get a smaller learning rate, and parameters that are rarely updated get a larger learning rate.</p><p>Real-world analogy: Imagine a student studying for exams. If they have been practicing Math every day, they slow down on Math (small learning rate for Math). But if they have never studied History, they spend more time on it (large learning rate for History).</p><p>Formula: w = w − (η / √(G + ε)) ⋅ ∇L(w)</p><p>Where G is the sum of squares of past gradients and ε is a small value to prevent division by zero</p><p>🟢 Pros: Works great for sparse data (like NLP tasks), no manual tuning of learning rate</p><p>🔴 Cons: Learning rate keeps decreasing and can become very small (effectively stopping learning)</p><h3>4. RMSProp — Root Mean Square Propagation</h3><p>RMSProp was developed by Geoffrey Hinton to fix AdaGrad’s problem of the learning rate shrinking too quickly. Instead of accumulating ALL past squared gradients, RMSProp uses a moving average (exponential decay), which gives more weight to recent gradients.</p><p>Formula:</p><p>E[g²] = β × E[g²] + (1−β) × g²</p><p>w = w − (η / √(E[g²] + ε)) × g</p><p>Where β (typically 0.9) controls how much history to remember</p><p>🟢 Pros: Solves AdaGrad’s vanishing learning rate problem, works well for recurrent neural networks (RNNs)</p><p>🔴 Cons: Still requires tuning of the learning rate manually</p><h3>5. Adam — Adaptive Moment Estimation (The Most Popular!)</h3><p>Adam is the king of optimizers! It combines the best of both Momentum and RMSProp. It uses two moving averages:</p><ol><li>First moment (m): The mean of gradients (like Momentum) — helps with direction</li><li>2. Second moment (v): The mean of squared gradients (like RMSProp) — helps with learning rate scaling</li><li>Adam also does bias correction to fix the fact that at the start of training, m and v are initialized to 0 (biased towards zero).</li><li>Formulas:</li><li>m = β₁ × m + (1−β₁) × g</li><li>v = β₂ × v + (1−β₂) × g²</li><li>m̂ = m / (1−β₁ᵗ) (bias corrected)</li><li>v̂ = v / (1−β₂ᵗ) (bias corrected)</li><li>w = w − η × m̂ / (√v̂ + ε)</li><li>Default hyperparameters: η=0.001, β₁=0.9, β₂=0.999, ε=10⁻⁸</li><li>🟢 Pros: Fast convergence, low memory requirements, works for most problems out of the box, very little tuning needed</li><li>🔴 Cons: Can sometimes converge to suboptimal solutions compared to SGD with tuning; newer papers suggest it may generalize slightly worse</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jt4KKnUrF5OEN3ifQxMhJA.gif" /></figure><h3>6. AdamW — Adam with Weight Decay</h3><p>AdamW is a modern improvement over Adam, introduced in 2019. The key difference is how it handles weight decay (L2 regularization), which prevents the model from overfitting by penalizing large weights.</p><p>In regular Adam, weight decay is mixed with the gradient update, which is mathematically incorrect. AdamW separates weight decay from the gradient update, leading to better regularization and often better generalization.</p><p>🟢 Best for: Large language models, Transformers (GPT, BERT use AdamW)</p><p>🟢 Recommended when your model is overfitting and you want regularization built-in</p><h3>Quick Comparison: Which Optimizer Should You Use?</h3><p>Here’s a simple decision guide to help you pick the right optimizer:</p><p>🔵 Just starting out / simple model → Use SGD with Momentum</p><p>🔵 General deep learning tasks (CNNs, classification) → Use Adam</p><p>🔵 NLP tasks / Transformers (BERT, GPT) → Use AdamW</p><p>🔵 RNNs / sequence models → Use RMSProp or Adam</p><p>🔵 Sparse data / NLP word embeddings → Use AdaGrad</p><p>🔵 Want best final accuracy (after lots of tuning) → Use SGD + Momentum + LR scheduler</p><h3>Summary Table</h3><p>Optimizer | Speed | Memory | Adaptive LR | Best For</p><p>SGD | Medium | Low | No | Simple models, image classification</p><p>SGD + Momentum | Fast | Low | No | Most vision tasks</p><p>AdaGrad | Slow | Medium | Yes | Sparse data, NLP</p><p>RMSProp | Fast | Medium | Yes | RNNs, non-stationary problems</p><p>Adam | Very Fast | Medium | Yes | General deep learning (default choice)</p><p>AdamW | Very Fast | Medium | Yes | Transformers, LLMs, regularization</p><h3>Conclusion — Key Takeaways</h3><p>Congratulations! You now understand the core optimizers used in neural networks. Let’s quickly recap what we covered:</p><ul><li>Gradient Descent is the foundation — it minimizes loss by following the gradient downhill</li><li>• SGD is simple and fast but noisy</li><li>• Momentum adds speed and direction memory to SGD</li><li>• AdaGrad adapts learning rates per parameter, great for sparse data</li><li>• RMSProp fixes AdaGrad’s vanishing rate problem with exponential decay</li><li>• Adam = Momentum + RMSProp + Bias Correction. The king of optimizers!</li><li>• AdamW adds proper weight decay, perfect for modern Transformers</li></ul><p>The golden rule for beginners: Start with Adam. It works 90% of the time without tuning. Once you understand your data and model better, explore others for that extra edge.</p><p>If you found this article helpful, give it a clap 👏 and follow for more beginner-friendly deep learning content. Happy learning! 🧠⚡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10c58ed5aaa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Activation Functions in Neural Networks Explained: Sigmoid, Tanh, ReLU, Leaky ReLU, and Softmax]]></title>
            <link>https://medium.com/@surisettikrishna17/activation-functions-in-neural-networks-explained-sigmoid-tanh-relu-leaky-relu-and-softmax-7518167f1dc6?source=rss-580bb06a49c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7518167f1dc6</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Surisetti Vamsi krishna]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 13:01:02 GMT</pubDate>
            <atom:updated>2026-06-22T13:01:02.844Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are just starting your journey into neural networks and deep learning, you have probably heard the term “activation function” thrown around a lot. But what exactly is it? Why do we need it? And which one should you use?</p><p>This guide answers all of those questions in simple language, with visual diagrams, real-world analogies, and a handy cheat sheet at the end — perfect for beginners and for quick revision.</p><h3>What is an Activation Function?</h3><p>Think of a neural network as a series of connected neurons, just like the human brain. Each neuron receives some inputs, does a calculation, and passes the result to the next neuron.</p><p>But here is the problem: if a neural network only does simple linear calculations (like multiplying and adding), it can only learn simple patterns. Real-world data like images, audio, and text are highly complex and non-linear.</p><p>This is where activation functions come in. An activation function is a mathematical equation applied to each neuron’s output. It decides whether a neuron should be “activated” (i.e., fire a signal) or not. It introduces non-linearity into the network, which allows it to learn complex patterns.</p><p>Simple Analogy: Imagine a light switch. Without an activation function, the neuron is like a dimmer switch (linear) — it just passes through proportional signals. With a good activation function, the neuron can behave like a smart switch that reacts differently depending on the strength of the signal.</p><h3>1. Sigmoid Activation Function</h3><p>Formula: f(x) = 1 / (1 + e^(-x))</p><p>Output Range: 0 to 1</p><p>Shape: S-curve (Sigmoid curve)</p><p>Graph Visualization (S-Shape)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcB9RwZJ2JkX9A9zhCa1Uw.png" /></figure><p>What does it do? The sigmoid squashes any input value into a smooth curve between 0 and 1. Think of it like a probability output — values near 0 mean “no” and values near 1 mean “yes”.</p><p>Advantages:<br>- Output is always between 0 and 1 (good for probability predictions)<br>- Smooth and differentiable (important for training)</p><p>Disadvantages:<br>- Vanishing Gradient Problem: For very large or very small inputs, the gradient becomes near zero, making training very slow<br>- Output is not zero-centered, which can slow down gradient descent</p><p>Best used for: Binary classification (output layer)</p><h3>2. Tanh (Hyperbolic Tangent) Activation Function</h3><p>Formula: f(x) = (e^x — e^(-x)) / (e^x + e^(-x))</p><p>Output Range: -1 to 1</p><p>Shape: S-curve (similar to Sigmoid but centered at 0)</p><p>Graph Visualization (S-Shape centered at 0):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWM93R9u9IufnDsCK8STJA.png" /></figure><p>What does it do? Tanh is very similar to Sigmoid, but it outputs values between -1 and 1, making it zero-centered. This makes training faster compared to Sigmoid.</p><p>Advantages:<br>- Zero-centered output (better for gradient descent)<br>- Stronger gradients compared to Sigmoid</p><p>Disadvantages:<br>- Still suffers from the vanishing gradient problem</p><p>Best used for: Hidden layers in Recurrent Neural Networks (RNNs)</p><h3>3. ReLU (Rectified Linear Unit) Activation Function</h3><p>Formula: f(x) = max(0, x)</p><p>Output Range: 0 to infinity</p><p>Shape: A hockey-stick shape (flat at 0 for negative x, linear for positive x)</p><p>Graph Visualization (Hockey-Stick Shape):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfzsA94C9ALmyHNFLV3H9Q.png" /></figure><p>What does it do? ReLU is the most widely used activation function in deep learning. It is dead simple: if the input is negative, output 0. If positive, output the value itself. This makes it extremely fast and efficient.</p><p>Advantages:<br>- Computationally very fast<br>- No vanishing gradient for positive values<br>- Creates sparse activations (only some neurons fire)</p><p>Disadvantages:<br>- Dying ReLU Problem: If inputs are always negative, neurons stop firing and “die” permanently</p><p>Best used for: Hidden layers in CNNs and most deep learning networks</p><h3>4. Leaky ReLU Activation Function</h3><p>Formula: f(x) = x if x &gt; 0, else f(x) = 0.01 * x (a small slope for negative values)</p><p>Output Range: -infinity to +infinity</p><p>Shape: Similar to ReLU but with a small negative slope instead of flat zero</p><p>Graph Visualization (Leaky Hockey-Stick):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AH3Xc9iValGaYka27cKUmQ.png" /></figure><p>What does it do? Leaky ReLU is a fix for the dying ReLU problem. Instead of outputting exactly 0 for negative inputs, it outputs a very small negative value (like -0.05 for input -5). This keeps the neuron alive and learning.</p><p>Advantages:<br>- Solves the dying ReLU problem<br>- Works well in practice</p><p>Disadvantages:<br>- The slope value (0.01) is a hyperparameter that needs tuning</p><p>Best used for: When ReLU causes dead neurons in your network</p><h3>5. Softmax Activation Function</h3><p>Formula: f(xi) = e^xi / sum(e^xj) for all j</p><p>Output Range: 0 to 1 (all outputs sum to 1 — like probabilities)</p><p>Shape: Converts raw scores (logits) into a probability distribution</p><p>Graph Visualization (Probability Bars):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iCxJ01RmCNu8X4AQlpQA6g.png" /></figure><p>What does it do? Softmax is used in the output layer of a neural network when you want to classify between multiple classes. It converts raw numbers (called logits) into probabilities that all add up to 1. The class with the highest probability is the prediction.</p><p>Advantages:<br>- Perfect for multi-class classification<br>- Outputs sum to 1, giving clear probabilities</p><p>Disadvantages:<br>- Not suitable for hidden layers (only for output layer)</p><p>Best used for: Output layer of multi-class classification problems</p><h4>Conclusion</h4><p>Activation functions are one of the fundamental building blocks of neural networks. They introduce non-linearity into the model, enabling neural networks to learn complex patterns and relationships that would otherwise be impossible with simple linear transformations.</p><p>In this article, we explored the intuition, mathematical formulation, output ranges, advantages, and use cases of five widely used activation functions: Sigmoid, Tanh, ReLU, Leaky ReLU, and Softmax. Understanding when and why these functions are used is an essential step toward mastering deep learning architectures.</p><p>As deep learning continues to advance, researchers have developed newer activation functions such as ELU, Swish, GELU, and Mish to address some limitations of traditional approaches. Exploring these modern activation functions can provide deeper insights into how today’s state-of-the-art neural networks achieve improved performance across various AI applications.</p><h4>Next in This Series</h4><p>In the next article, we will explore Optimization Algorithms in Deep Learning, covering concepts such as Gradient Descent, Stochastic Gradient Descent (SGD), Momentum, RMSprop, and Adam Optimizer. We will examine how neural networks learn by updating weights and how different optimization techniques influence convergence speed, stability, and model performance.</p><h4>About the Author</h4><p><strong>Surisetti Vamsi Krishna</strong></p><p>Computer Science and Engineering Graduate with a strong interest in Artificial Intelligence, Machine Learning, Data Science, and Deep Learning. Passionate about transforming complex technical concepts into clear, practical, and beginner-friendly learning resources. Currently focused on advancing expertise in Neural Networks, Natural Language Processing, and Generative AI while building real-world AI applications.</p><p>Connect with me:</p><p>LinkedIn: <a href="http://linkedin.com/in/surisetti-vamsi-krishna-54627425a">Link</a></p><p>GitHub: <a href="http://github.com/Vamsi-krishna17">github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7518167f1dc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Layer Perceptron (MLP) Explained for Beginners: The Brain Behind Deep Learning]]></title>
            <link>https://medium.com/@surisettikrishna17/multi-layer-perceptron-mlp-explained-for-beginners-the-brain-behind-deep-learning-7da4ce91f339?source=rss-580bb06a49c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7da4ce91f339</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mlp]]></category>
            <category><![CDATA[ann]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Surisetti Vamsi krishna]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 16:11:53 GMT</pubDate>
            <atom:updated>2026-06-18T16:11:53.251Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how computers can recognize your face, understand your voice, or even beat humans at chess? The secret lies in a fascinating concept inspired by the human brain — the Multi-Layer Perceptron, or MLP.</p><p>In this article, we will break down the MLP from scratch using simple language and real-life examples. No prior experience in machine learning is needed. Let’s dive in!</p><h3>🧠 What is a Neuron? (The Building Block)</h3><p>Before we understand MLP, we need to understand what a single neuron is — because MLP is just a network of many neurons connected together!</p><p>Think of a neuron like a tiny decision-maker. It receives some information, does a quick calculation, and passes the result forward.</p><p>Real-life analogy: Imagine you touch a hot cup of tea. Your nerve cells (neurons) sense the heat, send a signal to the brain, and the brain tells your hand to pull back. This is exactly how artificial neurons work in a computer!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*squb7bUejj5PS4W48t3SYg.jpeg" /></figure><p>An artificial neuron has three main parts:</p><p>Inputs (x): These are the data or information coming in. For example, pixel values of an image.</p><p>Weights (w): These are like the importance level given to each input. The neuron learns which inputs are more important.</p><p>Bias (b): A small extra value that helps the neuron make better decisions.</p><p>Activation Function: This decides whether the neuron should “fire” (pass info forward) or stay quiet.</p><h3>🔗 From a Single Neuron to a Perceptron</h3><p>A Perceptron is the simplest form of a neural network — it’s just ONE neuron. It takes multiple inputs, multiplies each by a weight, adds them up, and passes through an activation function to produce an output.</p><p>Example: Let’s say you want to decide if you should carry an umbrella tomorrow.</p><p>Input 1: Is it cloudy? (1 = Yes, 0 = No)</p><p>Input 2: Is it the rainy season? (1 = Yes, 0 = No)</p><p>Input 3: Did it rain yesterday? (1 = Yes, 0 = No)</p><p>The perceptron would look at these inputs with their weights (importance), add them up, and give an output: “Yes, carry umbrella” or “No, don’t bother.”</p><h3>🏛️ So What is a Multi-Layer Perceptron (MLP)?</h3><p>A Multi-Layer Perceptron is like having MANY layers of these decision-making neurons stacked together. Instead of just one neuron making a single decision, hundreds or thousands of neurons work together across multiple layers to solve complex problems.</p><p>MLP has three types of layers:</p><ol><li>Input Layer — This is where your data enters. Each node in this layer represents one feature of your data. For example, if you have a photo of 28x28 pixels, the input layer has 784 neurons (one per pixel).</li></ol><p>2. Hidden Layer(s) — These are the “secret workers” in the middle. They transform the input data through calculations to find patterns. You can have one or many hidden layers. More hidden layers = more powerful the network!</p><p>3. Output Layer — This gives the final answer. For example, if you’re classifying if an email is spam or not, the output layer might have 2 neurons (spam / not spam).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AxAQEsv_ddaJOFSwGUtOMQ.jpeg" /></figure><h3>⚡ How Does Information Flow Through an MLP?</h3><p>The process of information flowing through an MLP is called Forward Propagation. Here’s how it works step by step:</p><p>Step 1: You feed the data into the Input Layer.</p><p>Step 2: Each neuron in the hidden layer receives inputs, multiplies them by weights, adds a bias, and passes the result through an activation function.</p><p>Step 3: The output of one layer becomes the input of the next layer.</p><p>Step 4: Finally, the Output Layer gives the prediction.</p><p>Think of it like a factory assembly line. The raw material (your data) enters one end, gets processed by many workers (neurons) in different stations (layers), and a finished product (the prediction) comes out the other end!</p><h3>🔥 What are Activation Functions?</h3><p>An activation function is a mathematical gate that decides what output a neuron produces. Without activation functions, an MLP would just be a very complicated addition machine and couldn’t learn complex patterns.</p><p>Here are the most common activation functions explained simply:</p><ol><li>Sigmoid Function</li></ol><p>This squishes any number into a value between 0 and 1. It’s great for binary decisions like yes/no or true/false. Think of it like a light dimmer: output can be 0% (off) to 100% (fully on).</p><p>2. ReLU (Rectified Linear Unit)</p><p>This is the most popular activation function today. It’s super simple: if the value is negative, output 0. If positive, output that same value. It’s like saying: “If the news is good, pass it along. If it’s bad (negative), ignore it!”</p><p>3. Softmax</p><p>Used in the output layer when you have multiple classes (e.g., cat, dog, bird). It converts all outputs into probabilities that add up to 100%. “30% cat, 60% dog, 10% bird” — the model picks the highest one!</p><h3>🔄 How Does the MLP Actually Learn?</h3><p>This is the most magical part! The MLP learns by making mistakes and correcting them — just like how you learn to ride a bike by falling and adjusting.</p><p>Here’s how learning happens:</p><p>1. Make a Prediction: The MLP processes input data and outputs a prediction.</p><p>2. Measure the Error (Loss): We compare the prediction to the correct answer. The difference is called the loss or error.</p><p>3. Backpropagation: The error is sent backward through the network. Each neuron gets told how much it contributed to the mistake.</p><p>4. Update Weights: The weights are adjusted slightly so that next time, the prediction is a little bit better. This process is called Gradient Descent.</p><p>5. Repeat: This process repeats thousands of times until the network becomes accurate.</p><p>Analogy: Imagine practicing free throws in basketball. Every missed shot gives you feedback. You adjust your angle, force, and technique slightly each time. After hundreds of practice shots, your accuracy improves dramatically!</p><h3>🌟 A Real-World Example: Recognizing Handwritten Digits</h3><p>Let’s look at a classic example that beginners use to understand neural networks: recognizing handwritten digits (like the numbers 0 through 9).</p><p>Imagine the problem: You take a photo of someone’s handwritten number “7”. The computer needs to figure out that this is the digit 7.</p><p>How MLP solves this:</p><p>Input Layer: The image is 28x28 pixels = 784 pixels total. Each pixel’s brightness value (0 to 255) is fed as an input. So we have 784 input neurons.</p><p>Hidden Layers: Let’s say 2 hidden layers with 128 neurons each. They detect patterns like edges, curves, and intersections in the image.</p><p>Output Layer: 10 neurons (one for each digit 0–9). The neuron with the highest activation wins!</p><p>If the MLP sees an image, it might output: [0.01, 0.02, 0.01, 0.01, 0.01, 0.01, 0.01, 0.90, 0.01, 0.01]. The 8th value (index 7) is highest at 0.90, so the answer is: “This is the digit 7!” ✨</p><h3>🚀 Where is MLP Used in Real Life?</h3><p>MLPs are used in many exciting real-world applications:</p><p>📞 Spam Detection: Your email app uses an MLP (or similar network) to decide if an email is spam or not.</p><p>🏦 Fraud Detection: Banks use MLPs to detect suspicious transactions in real time.</p><p>🎤 Voice Recognition: When you talk to Siri or Google Assistant, an MLP helps convert your voice to text.</p><p>🏥 Medical Diagnosis: Doctors use ML models to predict diseases from patient data like blood reports and X-rays.</p><p>🎵 Music Recommendation: Spotify’s recommendation system uses neural networks to understand your music taste.</p><p>🚗 Self-Driving Cars: Neural networks process sensor data to help cars make driving decisions.</p><h3>📝 Quick Summary: Key Takeaways</h3><p>Here’s a quick cheat-sheet of everything we learned:</p><p>✅ A Neuron is a tiny decision-making unit inspired by biology.</p><p>✅ A Perceptron is a single neuron with inputs, weights, bias, and an activation function.</p><p>✅ MLP (Multi-Layer Perceptron) = Multiple layers of neurons: Input Layer → Hidden Layer(s) → Output Layer.</p><p>✅ Forward Propagation = Data flows from input to output through layers.</p><p>✅ Backpropagation = Errors flow backward to update weights and improve the model.</p><p>✅ Activation Functions like Sigmoid, ReLU, and Softmax add non-linearity and help solve complex problems.</p><p>✅ MLPs are used everywhere: spam filters, voice assistants, medical diagnosis, and more!</p><h3>🏁 What’s Next?</h3><p>Now that you understand the basics of Multi-Layer Perceptrons, here are some exciting topics to explore next:</p><p>➡️ Convolutional Neural Networks (CNNs) — Great for image recognition</p><p>➡️ Recurrent Neural Networks (RNNs) — Great for sequence data like text and speech</p><p>➡️ Transformers — The technology behind ChatGPT and modern AI</p><p>Remember: Every expert was once a beginner. The fact that you’re reading this means you’ve already taken the first step toward understanding one of the most powerful technologies of our time.</p><p>Keep learning, keep building, and don’t be afraid to experiment. The world of deep learning is exciting, rewarding, and full of possibilities for curious minds like yours! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7da4ce91f339" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single Layer Perceptron (SLP): The Foundation of Neural Networks]]></title>
            <link>https://medium.com/@surisettikrishna17/single-layer-perceptron-slp-the-foundation-of-neural-networks-fbd4b8fdebc8?source=rss-580bb06a49c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbd4b8fdebc8</guid>
            <category><![CDATA[ann]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[dl]]></category>
            <category><![CDATA[slp]]></category>
            <dc:creator><![CDATA[Surisetti Vamsi krishna]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 10:19:25 GMT</pubDate>
            <atom:updated>2026-06-16T10:19:25.997Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Artificial Intelligence and Machine Learning have transformed the modern world. At the heart of every deep learning model lies a fundamental building block — the Perceptron. The Single Layer Perceptron (SLP) is the simplest form of an artificial neural network and serves as the foundation upon which all complex neural networks are built. In this article, we will explore what SLP is, how it works, its architecture, learning algorithm, advantages, limitations, and Python implementation.</p><h3>What is a Single Layer Perceptron?</h3><p>A Single Layer Perceptron (SLP) is the most basic type of artificial neural network. It was introduced by Frank Rosenblatt in 1957 and is inspired by the biological neuron in the human brain. The SLP consists of only one layer of output nodes that are directly connected to the inputs. It is a feed-forward network that processes inputs and produces a binary output based on a threshold activation function.</p><p>The SLP can only solve linearly separable problems, meaning it can classify data that can be divided by a straight line (or hyperplane in higher dimensions). Despite this limitation, it laid the groundwork for all modern deep learning architectures.</p><h3>Architecture of Single Layer Perceptron</h3><p>The architecture of a Single Layer Perceptron consists of the following key components:</p><p>1. Input Layer: The input layer consists of n input nodes (x1, x2, …, xn). Each input represents a feature of the data. These inputs are fed directly into the neuron.</p><p>2. Weights (w1, w2, …, wn): Each input is associated with a weight. Weights determine the importance or contribution of each input to the final output. They are adjusted during the learning process.</p><p>3. Bias (b): The bias is an additional input with a fixed value of 1 and its own weight. It helps the model shift the activation function and improves flexibility.</p><p>4. Summation Function (Net Input): The net input is computed as the weighted sum of all inputs plus the bias:<br>Net Input = (x1*w1 + x2*w2 + … + xn*wn) + b</p><p>5. Activation Function: The activation function (usually a step function) converts the net input into an output. If net input &gt;= threshold, output = 1; otherwise, output = 0.</p><p>6. Output: The final binary output (0 or 1) is produced based on the activation function result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LZiK1gmXs5dboIqB" /><figcaption>Photo by <a href="https://unsplash.com/@virupro10?utm_source=medium&amp;utm_medium=referral">notorious v1ruS</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>How Does a Single Layer Perceptron Learn?</h3><p>The SLP learns through a process called the Perceptron Learning Algorithm. This is a supervised learning algorithm where the model is trained using labeled data. Here are the steps:</p><p>Step 1 — Initialize Weights: Set all weights (w1, w2, …, wn) and the bias (b) to zero or small random values.</p><p>Step 2 — Feed Input: For each training sample, feed the input values into the perceptron.</p><p>Step 3 — Compute Net Input: Calculate the weighted sum of inputs:<br>Net Input = sum(xi * wi) + b</p><p>Step 4 — Apply Activation Function: Apply the step function:<br>If Net Input &gt;= 0, Output (y) = 1<br>If Net Input &lt; 0, Output (y) = 0</p><p>Step 5 — Compute Error: Compare the actual output with the target (desired) output:<br>Error = Target Output — Actual Output</p><p>Step 6 — Update Weights: Adjust the weights using the update rule:<br>wi(new) = wi(old) + (learning rate * Error * xi)<br>b(new) = b(old) + (learning rate * Error)</p><p>Step 7 — Repeat: Repeat steps 2–6 for all training samples and multiple epochs until the error is minimized or the model converges.</p><h3>Python Implementation of Single Layer Perceptron</h3><p>Here is a simple Python implementation of a Single Layer Perceptron from scratch using NumPy:</p><p>import numpy as np</p><p>class SingleLayerPerceptron:<br> def __init__(self, learning_rate=0.1, epochs=100):<br> self.lr = learning_rate<br> self.epochs = epochs<br> self.weights = None<br> self.bias = None</p><p>def activation(self, x):<br> return 1 if x &gt;= 0 else 0</p><p>def fit(self, X, y):<br> n_samples, n_features = X.shape<br> self.weights = np.zeros(n_features)<br> self.bias = 0</p><p>for _ in range(self.epochs):<br> for i in range(n_samples):<br> net_input = np.dot(X[i], self.weights) + self.bias<br> y_pred = self.activation(net_input)<br> error = y[i] — y_pred<br> self.weights += self.lr * error * X[i]<br> self.bias += self.lr * error</p><p>def predict(self, X):<br> return [self.activation(np.dot(x, self.weights) + self.bias) for x in X]</p><p># Example: AND Gate<br>X = np.array([[0,0],[0,1],[1,0],[1,1]])<br>y = np.array([0, 0, 0, 1]) # AND gate</p><p>slp = SingleLayerPerceptron(learning_rate=0.1, epochs=100)<br>slp.fit(X, y)<br>predictions = slp.predict(X)<br>print(‘Predictions:’, predictions)</p><h3>Advantages of Single Layer Perceptron</h3><p>1. Simple and Easy to Understand: The SLP is the simplest neural network model. It is easy to implement and understand, making it a great starting point for beginners learning about neural networks and machine learning.</p><p>2. Fast Training: Due to its simple architecture and direct computation, the SLP trains very quickly on small datasets.</p><p>3. Binary Classification: The SLP is very effective for simple binary classification problems where data is linearly separable.</p><p>4. Foundation for Deep Learning: Despite its simplicity, the SLP is the fundamental building block for Multi-Layer Perceptrons (MLP) and all modern deep neural networks.</p><p>5. Convergence Guarantee: The Perceptron Convergence Theorem guarantees that if the data is linearly separable, the SLP will converge to a perfect solution in a finite number of iterations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjwMVM0xDfZ_W1z8QS1tDg.png" /></figure><h3>Limitations of Single Layer Perceptron</h3><p>1. Cannot Solve Non-Linearly Separable Problems: The biggest limitation of SLP is that it cannot classify data that is not linearly separable. A classic example is the XOR problem, which cannot be solved by a single layer perceptron.</p><p>2. Binary Output Only: The SLP produces only binary output (0 or 1), making it unsuitable for multi-class classification problems or regression tasks.</p><p>3. No Hidden Layers: The absence of hidden layers means the SLP cannot learn complex features or patterns in the data.</p><p>4. Limited Representation Power: Due to its simple architecture, the SLP has very limited representation power and cannot model complex relationships in data.</p><p>5. Sensitive to Feature Scaling: The SLP is sensitive to the scale of input features and requires proper feature normalization for effective training.</p><p>6. Not Suitable for Complex Real-World Problems: Modern real-world problems such as image recognition, natural language processing, and speech recognition require multi-layer architectures that go far beyond what an SLP can handle.</p><h3>Conclusion</h3><p>The Single Layer Perceptron (SLP) is truly the grandfather of modern artificial intelligence and deep learning. Introduced by Frank Rosenblatt in 1957, this simple yet powerful model demonstrated that machines could learn from data and make decisions — a revolutionary concept at the time.</p><p>Although the SLP has significant limitations (most notably its inability to handle non-linearly separable problems), it remains an essential concept for anyone studying machine learning and neural networks. Understanding how the SLP works — its architecture, learning algorithm, and weight update mechanism — gives you the foundation you need to understand far more complex models like Multi-Layer Perceptrons (MLP), Convolutional Neural Networks (CNNs), and Recurrent Neural Networks (RNNs).</p><p>The journey from a Single Layer Perceptron to modern deep learning models is a testament to how far the field has come. But it all starts here — with one neuron, a few weights, and the desire to learn.</p><p>Thank you for reading! If you found this article helpful, feel free to clap, share, and follow for more articles on Machine Learning and Deep Learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbd4b8fdebc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>