<?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 Shanmugapriyan Gopalakrishnan on Medium]]></title>
        <description><![CDATA[Stories by Shanmugapriyan Gopalakrishnan on Medium]]></description>
        <link>https://medium.com/@shan123.gym?source=rss-d69f97fdde1e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oICny-OQWAFswEKO</url>
            <title>Stories by Shanmugapriyan Gopalakrishnan on Medium</title>
            <link>https://medium.com/@shan123.gym?source=rss-d69f97fdde1e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:44:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shan123.gym/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[From Words to Intelligence:
How LLMs Actually Work]]></title>
            <link>https://medium.com/@shan123.gym/from-words-to-intelligence-how-llms-actually-work-ddb78614cb9c?source=rss-d69f97fdde1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddb78614cb9c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <category><![CDATA[mixture-of-experts]]></category>
            <category><![CDATA[bpe]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shanmugapriyan Gopalakrishnan]]></dc:creator>
            <pubDate>Fri, 08 May 2026 22:04:50 GMT</pubDate>
            <atom:updated>2026-05-08T22:07:50.609Z</atom:updated>
            <content:encoded><![CDATA[<p>A language model does not write an entire sentence all at once like humans do. First, it reads the input by breaking the text into smaller pieces called tokens, which can be words or parts of words. It then analyzes the context and meaning of the sentence. While generating a reply, the model makes many tiny decisions step by step for every next token. It decides how creative or predictable the response should be and predicts which token best fits next.</p><p>In advanced models, different internal networks or “experts” may handle different kinds of tasks such as reasoning, coding, or language understanding. So even a simple AI-generated sentence is actually the result of hundreds of small calculations happening behind the scenes.</p><p>These decisions are governed by five interlocking concepts: Byte Pair Encoding (BPE), Temperature, Top‑K sampling, Top‑P sampling, and Mixture of Experts (MoE). This article connects all five in sequence — from the moment raw text enters a model, to the moment a response is produced.</p><h4>Background — Transformers &amp; Attention:</h4><p>Before going deeper, let’s first understand the basic idea behind a transformer model. A transformer is a type of neural network designed so that every word (or token) in a sentence can look at all the other words and decide which ones are important for understanding the meaning. This process is called <strong>self-attention</strong>.</p><p>For example, consider the sentence:<br> <em>“The trophy didn’t fit in the suitcase because it was too big.”</em><br> When the model reads the word <em>“it”</em>, it looks back at the earlier words and understands that <em>“it”</em> most likely refers to the <em>trophy</em>, not the suitcase, because the trophy is the thing that can be “too big.”</p><p>The model does this by giving importance scores, called <strong>attention weights</strong>, between words. These scores are learned during training. Unlike older models that read words one by one, transformers can look at all words in parallel, understand the relationships between them, and build a rich understanding of the sentence before predicting the next token.</p><p>But before the transformer can process any text, the words must first be converted into numbers that the model can understand. That is where <strong>BPE (Byte Pair Encoding)</strong> comes in.</p><h3>Byte Pair Encoding (BPE)</h3><p>The method used to create tokens:</p><p>Language models do not directly read full sentences like humans. They first break text into smaller pieces called <strong>tokens</strong>. These tokens are usually parts of words, whole words, or symbols. <strong>BPE (Byte Pair Encoding)</strong> is the technique used to create those tokens.</p><p>BPE starts by treating every word as individual characters. Then it repeatedly looks for character pairs that appear together very often and combines them into a single token.</p><p>Over time:</p><ul><li>common words become single tokens,</li><li>and rare or new words are split into smaller known pieces.</li></ul><p>This helps the model understand almost any word.</p><p>Simple Example:</p><p>Imagine the training data contains these words many times:</p><ul><li>low</li><li>lower</li><li>newer</li></ul><h4><strong><em>Step 1: Split into characters</em></strong></h4><p>The words are first broken into characters:</p><ul><li>l o w</li><li>l o w e r</li><li>n e w e r</li></ul><h4><strong><em>Step 2: Find common pairs</em></strong></h4><p>The model checks which character pairs appear together most often.</p><p>For example:</p><ul><li>e r appears many times.</li></ul><p>So BPE combines:</p><ul><li>e + r → er</li></ul><p>Now er becomes a new token.</p><h4><strong><em>Step 3: Repeat merging</em></strong></h4><p>Next, another common pair may be:</p><ul><li>l o → lo</li></ul><p>The process continues again and again until the vocabulary reaches the desired size, such as 50,000 tokens.</p><h4><em>What happens with new words?</em></h4><p>When the model sees a new word, it breaks it into known token pieces.</p><p>Example:</p><ul><li>unhappiness<br> might become:</li><li>un + happi + ness</li></ul><p>Even if the full word was never seen before, the model still understands parts of it.</p><p>That is why language models rarely encounter completely “unknown” words.</p><p>Why not use only characters or full words?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*OkvURhVp75ZWQJI7_lR_Mw.png" /></figure><p>So BPE gives the model:</p><ul><li>smaller vocabulary,</li><li>better efficiency,</li><li>and the ability to understand new words.</li></ul><p>After text is converted into tokens, the transformer processes them and predicts probabilities for the next possible token. Techniques like <strong>Temperature</strong>, <strong>Top-K</strong>, and <strong>Top-P</strong> then decide how the final next token is chosen.</p><h3>Temperature</h3><p><strong>Temperature is a setting that controls how predictable or creative the AI’s next word will be.</strong></p><p>After the model scores all possible next words, it turns them into probabilities. Temperature then changes how those probabilities behave before the final word is chosen. i.e., Temperature changes how “confident” the model looks by scaling its internal scores before converting them into probabilities.</p><h4>What different values mean:</h4><ul><li><strong>Low temperature (&lt; 1)</strong><br> The model sticks to the safest, most likely words<br> → very focused and predictable answers</li><li><strong>Temperature = 1</strong><br> Normal behavior of the model<br> → balanced and natural responses</li><li><strong>High temperature (&gt; 1)</strong><br> The model becomes more experimental<br> → more variety and creativity, but sometimes less accurate</li></ul><p>It’s like choosing answers in a quiz:</p><ul><li>Low temperature → always picks the most obvious correct answer</li><li>Medium temperature → chooses sensible answers</li><li>High temperature → sometimes picks unexpected or creative answers</li></ul><p>Most production models use T between 0.7 and 1.2 because it gives a good balance between <strong>accuracy and creativity</strong></p><p><em>Each logit z is divided by the temperature T before softmax:</em></p><p><strong><em>P(token) = softmax(z / T)</em></strong></p><h4>Steps:</h4><ul><li>The model first gives <strong>scores for all possible next words</strong> (logits).</li><li>Temperature <strong>modifies these scores before selection</strong>.</li><li>Then the model <strong>chooses a word by sampling from the modified probabilities</strong>.</li></ul><h4>Example:</h4><p><strong><em>1. First: the model produces raw scores (logits)</em></strong></p><p>The model outputs numbers like:</p><ul><li>“morning” → 3.0</li><li>“day” → 1.0</li><li>“evening” → 0.0</li></ul><p>These are <strong>not probabilities yet</strong>. They are just “preference scores”.</p><p><strong><em>2. Softmax converts scores into probabilities</em></strong></p><p>Softmax turns them into probabilities like:</p><ul><li>“morning” → 70%</li><li>“day” → 20%</li><li>“evening” → 10%</li></ul><p>It does this using exponentials, which naturally amplify differences.</p><p><strong><em>3. Temperature changes the sharpness of these scores</em></strong></p><p>Before softmax, each score is divided by temperature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*Sa-wzbXkbXD4HoSalYz3uA.png" /></figure><p><strong><em>4. What this actually does</em></strong></p><blockquote>Low temperature (T &lt; 1)</blockquote><p><strong>Example: T = 0.5</strong><br> We divide scores by a small number → differences become larger:</p><ul><li>3.0 / 0.5 = 6</li><li>1.0 / 0.5 = 2</li><li>0.0 / 0.5 = 0</li></ul><p>Now softmax sees a <strong>huge gap</strong>, so it becomes:</p><ul><li>“morning” → ~85–95%</li><li>others → very low</li></ul><p>Result: <strong>very confident, repetitive, predictable</strong></p><blockquote><em>High temperature (T &gt; 1)</em></blockquote><p><strong>Example: T = 2.0</strong><br> We divide scores by a bigger number → differences shrink:</p><ul><li>3.0 / 2 = 1.5</li><li>1.0 / 2 = 0.5</li><li>0.0 / 2 = 0</li></ul><p>Now softmax sees <strong>small gaps</strong>, so:</p><ul><li>“morning” → ~50%</li><li>“day” → ~30%</li><li>“evening” → ~20%</li></ul><p>Result: <strong>more randomness, more variety</strong></p><h4><strong><em>Simple intuition</em></strong></h4><ul><li>Temperature does <strong>not pick words</strong></li><li>It <strong>stretches or compresses the gap between scores</strong></li><li>Then softmax turns that into probabilities</li></ul><h3>Top-K Sampling</h3><p>Even after temperature is applied, the model still considers <strong>a huge number of possible next words</strong>, but most of them are very unlikely.</p><p><strong>Top-K sampling fixes this by only keeping the best K options.</strong></p><p>Instead of looking at all words, the model says: <em>“I will only consider the top K most likely words.”</em></p><p>Everything else is ignored.</p><h4>Example</h4><p>After the sentence: <em>“The sky at night is”</em></p><p>The model might predict:</p><ul><li><strong>dark</strong> → 54%</li><li><strong>clear</strong> → 28%</li><li><strong>black</strong> → 12%</li><li>blue → 4%</li><li>full → 2%</li></ul><p>If <strong>K = 3</strong>, we only keep:</p><ul><li>dark</li><li>clear</li><li>black</li></ul><p>The rest are removed.</p><p>Then the model <strong>recalculates probabilities only among these 3 words</strong>, and picks one from them.</p><p><strong>Why this helps</strong></p><ul><li>Removes very unlikely words</li><li>Makes output more focused</li><li>Prevents strange or irrelevant choices</li></ul><p>Top-K limits the options to the most likely words, and sampling picks one from them in a probabilistic way, making the output more natural and less repetitive.</p><h3><strong>Top-P sampling (also called nucleus sampling)</strong></h3><p>It is a smarter way to choose the next word.</p><p>Instead of fixing a number like Top-K, it looks at <strong>probability mass</strong>.</p><p>“What is the smallest group of words that together covers most of the probability (for example 90%)?”</p><p>Then it only chooses from that group.</p><p><strong><em>Example 1 (very sure situation)</em></strong></p><p>Sentence:</p><blockquote><em>“The capital of France is”</em></blockquote><p>Model predictions:</p><ul><li>Paris → 91%</li><li>Lyon → 5%</li><li>Nice → 4%</li></ul><p>If <strong>P = 0.9</strong>, then:</p><ul><li>Only “Paris” is enough to cover 90% probability</li></ul><p>So the model chooses from:</p><ul><li>{Paris}</li></ul><p>Output becomes very focused and accurate.</p><p><strong><em>Example 2 (uncertain situation)</em></strong></p><p>Sentence: <em>“My favourite colour is”</em></p><p>Model predictions:</p><ul><li>blue → 18%</li><li>red → 15%</li><li>green → 13%</li><li>black → 11%</li><li>yellow → 9%</li></ul><p>To reach <strong>P = 0.9</strong>, we need several options:</p><ul><li>blue, red, green, black, yellow, etc.</li></ul><p>Now the model has more choices because it is less sure.</p><h3>Mixture of Experts (MoE)</h3><p>Before understanding <strong>MoE</strong>, think about a normal transformer:</p><p>In a regular model, <strong>every token passes through the same full network</strong>, even if parts of it are not needed. This becomes very expensive as the model grows.</p><p>Instead of using the whole brain every time, MoE works like:</p><p><em>“Only activate the part of the model that is most useful for this token.”</em></p><p>This is called <strong>conditional computation</strong>.</p><p>Mixture of Experts (MoE) is a transformer design where only a few specialized “expert” subnetworks are activated for each token instead of using the full model every time.</p><h4>What are “expert layers”?</h4><p>An <strong>expert layer</strong> is just a group of small neural networks inside the model.</p><p>Think of them as:</p><ul><li>Expert 1 → good at language / grammar</li><li>Expert 2 → good at math</li><li>Expert 3 → good at coding</li><li>Expert 4 → good at reasoning / logic</li></ul><p>These are not literally fixed labels, but each expert <strong>learns different patterns during training</strong>.</p><h4>MoE Architecture</h4><p>A typical MoE transformer replaces the normal feed-forward layer (FFN) with an <strong>expert system</strong>.</p><p><strong><em>Core components:</em></strong></p><p><em>1. Input token representation:</em></p><p>Each token comes from the transformer attention layer.</p><p>2. Router / Gating network:</p><p>This is a small neural network that decides: <em>“Which experts should handle this token?”</em></p><p>It outputs a score for each expert and selects <strong>top-1 or top-2 experts</strong>.</p><p><em>3. Experts (multiple FFNs):</em></p><p>Instead of one FFN, you have many:</p><ul><li>Expert 1 (FFN)</li><li>Expert 2 (FFN)</li><li>Expert 3 (FFN)</li><li>… up to 8, 16, 64, etc.</li></ul><p>Each expert is just a <strong>separate neural network layer</strong> trained to specialize.</p><p><em>4. Combination step:</em></p><p>Outputs from selected experts are combined (weighted sum) to produce final result.</p><h4>Simple architecture view:</h4><p>Input token<br> → Attention layer<br> → Router (decides experts)<br> → Selected Experts (only 1–2 active)<br> → Combine outputs<br> → Next layer</p><h4>Real-world MoE models (examples)</h4><p>Here are actual systems that use MoE:</p><blockquote><em>Mixtral (Mistral AI)</em></blockquote><ul><li>Uses MoE transformer architecture</li><li>Has multiple experts per layer</li><li>Only activates 2 experts per token</li><li>Very efficient compared to dense models</li></ul><blockquote><em>GPT-4 (rumored MoE-style design)</em></blockquote><ul><li>OpenAI has not fully confirmed architecture</li><li>Many research analyses suggest it may use <strong>Mixture-of-Experts ideas</strong></li><li>Helps scale to very large parameter sizes efficiently</li></ul><h4>How MoE works (simple flow)</h4><p>For each token:</p><ol><li>The model looks at the token</li></ol><p>2. A <strong>router (gating system)</strong> decides: “Which experts should handle this token?”</p><p>3. It selects only <strong>top 1 or top 2 experts</strong></p><p>4. Only those experts process the token</p><p>5.Their outputs are combined</p><p>Example:</p><p>Sentence: <em>“Write a Python loop”</em></p><p>Token activates:</p><ul><li>coding expert</li><li>syntax expert</li></ul><p>Not:</p><ul><li>poetry expert</li><li>translation expert</li></ul><p>Without MoE:</p><ul><li>every token uses <strong>100% of the model</strong></li><li>very expensive computation</li></ul><p>With MoE:</p><ul><li>only a <strong>small part of the model is used per token</strong></li></ul><h3>Conclusion:</h3><p>It all starts with <strong>BPE</strong>, which breaks raw text into small token pieces so the model can read and handle any word, even new or unfamiliar ones. Then the <strong>transformer’s attention mechanism</strong> helps each token understand the context by looking at how it relates to all other tokens in the sentence. To make this process scalable, <strong>Mixture of Experts (MoE)</strong> routes each token only to a few specialized sub-networks instead of using the full model every time. After processing, the model assigns scores to all possible next tokens, and <strong>Temperature, Top-K, and Top-P</strong> together control how the final choice is made — balancing between safe, focused output and creative variation.</p><p>Finally, one token is selected and added to the sentence, and this entire cycle repeats step by step until the full response is generated.</p><p>The one-sentence version to never forget: <strong>BPE </strong>reads your words, attention understands them, <strong>MoE</strong> thinks about them efficiently, and <strong>Temperature + Top-K + Top-P</strong> decide <strong>what to write back — one word at a time, repeated until the answer is done.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddb78614cb9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From RNN to Attention: A Practical Journey Through Sequence Models]]></title>
            <link>https://medium.com/@shan123.gym/from-rnn-to-attention-a-practical-journey-through-sequence-models-fa752615a2d9?source=rss-d69f97fdde1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa752615a2d9</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shanmugapriyan Gopalakrishnan]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 00:19:08 GMT</pubDate>
            <atom:updated>2026-03-15T00:19:08.466Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern AI systems like translation, speech recognition and chatbots rely heavily on sequence models. Unlike traditional models that treat data independently, sequence models understand context and order.</p><h4>Why Sequence Models Are Needed:</h4><p>Many real-world problems involve ordered data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*2x9Ap9SznInARddrIF1J6g.png" /></figure><p>Traditional models assume, “Inputs are Independent”. But language has context.</p><p>“I grew up in USA. I speak fluent ____.”</p><p>The missing word is likely English, which requires remembering earlier words. This is where <strong>Recurrent Neural Networks</strong> (RNNs) come in.</p><h3>Recurrent Neural Networks (RNN):</h3><p>RNNs process sequential data step-by-step while remembering past information.</p><p>At each time step:</p><p>Current Output = f(Current Input + Previous Hidden State)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*PsAIEEF2UMDGhBKVmcdZAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*w60IZMuD2wMUf4N4ehFJUA.png" /></figure><p>Example: Sentiment Analysis -&gt; “The movie was surprisingly good”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*_FrKZYTvneXlLnLyb4KD0A.png" /></figure><p>Each state remembers previous words.</p><h4>Problem: Vanishing Gradient</h4><p>Backpropagation through time (BPTT) is a method used in RNNs to train the network by backpropagating errors through time. In a traditional feedforward neural network, the data flows through the network in one direction, from the input layer through the hidden layers to the output layer.</p><p>However, in RNNs, there are connections between nodes in different time steps, i.e. the output of the network at one time step depends on the input at that time step as well as the previous time steps.</p><p><strong><em>When training RNNs with Backpropagation Through Time (BPTT), gradients become extremely small.</em></strong></p><p>So the model <strong>forgets long-term dependencies</strong>.</p><p><strong>Example failure:</strong></p><p>“The movie I watched last week despite bad reviews was actually fantastic”</p><p>RNN struggles to link <strong>fantastic </strong>with <strong>movie</strong>. This led to <strong>LSTM</strong> networks.</p><h3>Long Short-Term Memory (LSTM)</h3><p>LSTM was introduced to solve vanishing gradient problems.</p><p>Key idea is instead of one hidden state, LSTM maintains:</p><p>Cell State (long-term memory)<br>Hidden State (short-term output)</p><h4><strong>LSTM controls information using three gates:</strong></h4><p>Forget Gate, Input Gate, Output Gate</p><p><strong>1. Forget Gate:</strong> Decides what information to discard from memory.</p><p>Output range:</p><p>0 → forget completely<br>1 → keep completely</p><p><strong>2. Input Gate:</strong> Decides what new information to store.</p><p>Sentence: “The movie was boring but the ending was amazing”</p><p>The model learns to store “ending was amazing” strongly.</p><p><strong>3.</strong> <strong>Output Gate:</strong> Controls what part of memory becomes output.</p><p>“The movie was boring but the ending was amazing”</p><p>The final hidden state should emphasize <strong>amazing</strong>.</p><h4>Simple numeric example showing how LSTM gates work:</h4><p>It decides what to forget, decides what to store, produces output through gated memory updates.</p><p>Assume we are processing the word: “Love”</p><p><strong>Inputs:</strong><br>Previous hidden state h(t−1) = 0.5<br>Previous cell state C(t−1) = 0.8<br>Current input x(t) = 0.6</p><p>Wf = 0.7<br>Wi = 0.6<br>Wo = 0.5<br>Wc = 0.9</p><p><strong>Step 1: Forget Gate</strong></p><p>f_t = sigmoid(Wf * [h(t−1), x(t)])</p><p>0.7 × (0.5 + 0.6)<br>= 0.77</p><p>sigmoid(0.77) ≈ 0.68 i.e, 68% of previous memory is retained</p><p>Updated memory contribution -&gt; 0.68 × 0.8 = 0.544</p><p><strong>Step 2: Input Gate</strong></p><p>i_t = sigmoid(Wi * [h(t−1), x(t)])</p><p>0.6 × (0.5 + 0.6)<br>= 0.66</p><p><strong>Step 3: Candidate Memory</strong></p><p>C̃_t = tanh(Wc * [h(t−1), x(t)])</p><p>0.9 × (0.5 + 0.6)<br>= 0.99</p><p>tanh:<br>≈ 0.76</p><p><strong>Step 4: Update Cell State</strong></p><p>C_t = f_t * C(t−1) + i_t * C̃_t</p><p>C_t = (0.68 × 0.8) + (0.66 × 0.76)</p><p>C_t = 0.544 + 0.501 ≈ 1.045</p><p>New memory contains both previous context and new information.</p><p><strong>Step 5: Output Gate</strong></p><p>o_t = sigmoid(Wo * [h(t−1), x(t)])<br>0.5 × (0.5 + 0.6)<br>= 0.55</p><p>Sigmoid ≈ 0.63</p><p><strong>Step 6: Hidden State Output</strong></p><p>h_t = o_t × tanh(C_t)</p><p>tanh(1.045) ≈ 0.78</p><p>h_t = 0.63 × 0.78 ≈ 0.49</p><p>This hidden state is passed to the next time step.</p><h4>Advantages:</h4><ul><li>Handles long-term dependencies</li><li>Solves vanishing gradient problem</li><li>Maintains long memory</li></ul><h4>Limitations:</h4><ul><li>Computationally expensive</li><li>Many parameters</li><li>Slow training</li></ul><p>To simplify LSTM, researchers introduced GRU.</p><h3>GRU (Gated Recurrent Unit)</h3><p>GRU simplifies LSTM.</p><p>Instead of 3 gates, it uses 2 gates:</p><p><em>Update Gate</em> and <em>Reset Gate</em></p><p>Also NO separate cell state. <strong>Hidden state</strong> handles both memory and output.</p><h3>GRU vs LSTM:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*O5yAl0e3d3965uXMPjNwUw.png" /></figure><h3>Sequence-to-Sequence (Seq2Seq)</h3><p>Seq2Seq models are designed for <strong>sequence transformation tasks</strong>.</p><p>English → French translation</p><h4><strong>Architecture:</strong></h4><p><strong><em>Encoder → Context Vector → Decoder</em></strong></p><p><strong>Example:</strong></p><p>Input sentence: <em>“I love Machine Learning”</em></p><p><strong>Encoder </strong>converts the entire sentence into a <strong>single context vector</strong>.</p><p><strong>Decoder </strong>generates translation: <em>“J’aime l’apprentissage automatique”</em></p><p><strong>Embedding vector:</strong><br> An embedding vector is the size of the vector used to represent each word. In other words, it converts a word into a dense numerical vector that captures its semantic meaning so neural networks can process text.</p><p><strong>LSTM units:</strong><br> LSTM units represent the number of neurons in the LSTM layer that learn and store contextual information from the sequence, producing a hidden state vector of that size.</p><h4>Limitation:</h4><p>The entire sentence is compressed into one vector.</p><p>For long sentences, this becomes a bottleneck. The model struggles to remember early words.</p><h3>Attention <strong>Mechanism</strong></h3><p>Attention solves this problem. Instead of relying on <strong>one vector</strong>, the decoder <strong>looks at all encoder states.</strong></p><p>Attention Weight Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*0w4NBmVl41vSjLXxjlIMag.png" /></figure><p>This allows the model to focus dynamically on important words.</p><p><strong>Example:</strong></p><p>Input: “I love machine learning”</p><p>When generating: “learning”</p><p>Decoder focuses strongly on encoder state for <strong>learning</strong>.</p><h4>Attention assigns weights:</h4><p><strong><em>I</em></strong> → 0.05<br><strong><em>love</em></strong> → 0.15<br><strong><em>machine</em></strong> → 0.30<br><strong><em>learning</em></strong> → 0.50</p><h4>Advantages:</h4><ul><li>Handles long sentences</li><li>Improves translation accuracy</li><li>Enables parallelization</li></ul><h3>Summary:</h3><p>Sequence models evolved step-by-step to address fundamental limitations.</p><p>The progression:</p><p>RNN → LSTM → GRU → Seq2Seq → Attention</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*OeW0M0yGUlF3VfRljrOjjQ.png" /></figure><p>This evolution eventually led to Transformers, which completely remove recurrence and rely entirely on attention-based architectures.</p><p>Instead of compressing the entire sentence into a single context vector, the attention mechanism allows the decoder to dynamically focus on different parts of the input sequence while generating each output word.</p><p>Today, models like GPT, BERT and T5 are built entirely on attention-based architectures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa752615a2d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Made Simple: Predicting House Prices]]></title>
            <link>https://medium.com/@shan123.gym/deep-learning-made-simple-predicting-house-prices-18d09297d00e?source=rss-d69f97fdde1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/18d09297d00e</guid>
            <dc:creator><![CDATA[Shanmugapriyan Gopalakrishnan]]></dc:creator>
            <pubDate>Fri, 13 Feb 2026 23:48:25 GMT</pubDate>
            <atom:updated>2026-02-14T03:05:23.158Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>Imagine teaching a computer to predict house prices. At first, it only sees raw numbers — square footage, number of bedrooms, lot size and location. It doesn’t know which features are important or how they interact.</p><p><strong>Deep learning</strong> is a branch of machine learning that allows computers to automatically <strong>learn complex patterns from data</strong>, improving their predictions over time.</p><h3>What is a Neural Network?</h3><p>A <strong>neural network</strong> is a system of <strong>layers of interconnected “neurons”</strong> that work together to make predictions. Each neuron is a small calculator: it takes inputs (house features), multiplies them by weights, adds a bias, applies an activation function, and produces an output.</p><p>Mathematically, a neuron computes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*U89JEapcHAF4WbNxxL_6Qw.png" /></figure><h4>Layers in a Neural Network</h4><p>Neural networks are organized into <strong>layers</strong>:</p><ol><li><strong>Input layer:</strong> Takes raw features like square footage, number of bedrooms, lot size, and location.</li><li><strong>Hidden layers:</strong> Combine features in complex ways to find patterns. Multiple hidden layers allow the network to understand relationships like “houses with large lots in certain neighborhoods tend to be pricier.”</li><li><strong>Output layer:</strong> Produces the final prediction, e.g., the house price in dollars.</li></ol><h4>Activation Functions: How Neurons Decide</h4><p>It takes input features (like house size, bedrooms, lot size), multiplies them by weights, adds a bias, and gets a number. This number is called the pre-activation.</p><p>The activation function decides what part of that number should actually go to the next layer. It’s like a filter or gate: it says, “only send this much forward,” and sometimes, “ignore small values.”</p><blockquote>ReLU</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*wPZKX7rcbjGmmj7PMKDcTA.png" /></figure><ul><li>If the input is <strong>negative</strong>, output = 0 → neuron is “silent” for this input.</li><li>If input is <strong>positive</strong>, output = the input itself → neuron “fires” proportionally.</li></ul><p>Example:</p><ul><li>A neuron sees a small house with a combination of features giving a pre-activation value of <strong>-2</strong> → output = 0 → this neuron doesn’t contribute.</li><li>Another neuron sees a large suburban house giving a pre-activation of <strong>5</strong> → output = 5 → neuron passes strong signal forward.</li></ul><blockquote>Leaky ReLU</blockquote><p>Leaky ReLU allows <strong>a small fraction of negative values to pass</strong>. This avoids neurons dying completely (never firing).</p><ul><li>Example: Same small house with pre-activation -2 → output = -0.01 × 2 = -0.02 → neuron still contributes slightly.</li></ul><blockquote>Sigmoid / Tanh</blockquote><p>These functions <strong>squash values into a small range</strong>:</p><ul><li>Sigmoid: 0 → 1</li><li>Tanh: -1 → 1</li></ul><p>For very large or very small inputs, the output saturates (almost 0 or almost 1), and the neuron <strong>hardly changes</strong> during learning.</p><p>Example: If a neuron sees an extremely expensive house, the output might be 0.999 → the neuron has almost “maxed out” and can’t adjust much during learning.</p><h3>Forward Pass: Making Predictions</h3><p>In a <strong>forward pass</strong>, inputs move through the network layer by layer. Each neuron computes a weighted sum of its inputs, applies the activation function, and passes it forward. At the end, the network predicts the house price.</p><p>Example: A house with 2500 sq ft, 3 bedrooms, and a mid-sized lot might get predicted at $350,000. The network combines all features to produce this number</p><h4>Loss Function: Measuring Mistakes</h4><p>After predicting, the network measures <strong>how wrong it was</strong> using a <strong>loss function</strong>. For house prices, <strong>Mean Squared Error (MSE)</strong> is common:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*PUS9BHwS-HMxD4LibiJt8g.png" /></figure><h3>Backpropagation: Learning from Errors</h3><p><strong>Backpropagation</strong> calculates <strong>how much each weight contributed to the error</strong> and updates them accordingly.</p><p>Example: If the network overestimates prices for suburban houses, backpropagation reduces the weights associated with lot size and location, improving future predictions.</p><h3>Gradient Descent and Optimizers</h3><p>Weights are updated using <strong>gradient descent</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*BrpAYh8mtRAWinx5ATrdPA.png" /></figure><ul><li><strong>SGD (Stochastic Gradient Descent):</strong> Updates weights using small batches of houses.</li><li><strong>Momentum:</strong> Smooths updates by combining previous steps.</li><li><strong>RMSProp:</strong> Adjusts learning rate per parameter.</li><li><strong>Adam:</strong> Combines momentum and adaptive learning for fast, stable updates.</li></ul><p>Example: Adam helps the network quickly learn relationships between house features and prices without overshooting.</p><h3>Dropout:</h3><p><strong>Dropout</strong> randomly ignores some neurons during training, so the network doesn’t rely too heavily on one feature.</p><p>Example: Without dropout, the network might think “location alone determines price.” Dropout forces it to also consider bedrooms, lot size, and age, producing a <strong>more balanced and generalizable model</strong>.</p><h4>Batch Normalization: Keeping Values Balanced</h4><p>House features can vary widely — one house might be 500 sq ft, another 5000 sq ft. Feeding these extreme numbers into a network can slow or destabilize learning. <strong>Batch normalization</strong> adjusts values so each layer sees inputs on a similar scale, helping the network learn faster and more reliably.</p><p>Example: Lot sizes vary from 500 to 5000 sq ft, bathrooms from 1 to 5. Batch normalization ensures all features contribute fairly, preventing any one from dominating learning.</p><h3>Saturation, Vanishing and Exploding Gradients</h3><h4>Saturation:</h4><p>Saturation happens when a neuron <strong>reaches the limits of its activation function</strong>. Once it’s at the extreme, it <strong>can’t respond much to changes in input</strong>, slowing learning.</p><p><strong>Example:</strong></p><ul><li>Suppose the network predicts prices for suburban houses. A neuron sees a combination of features for a very large house and outputs 0.99 (almost the maximum for a Sigmoid activation).</li><li>Even if the actual price should be higher, this neuron <strong>can’t increase much</strong>, so it “saturates” and stops learning effectively for very expensive houses.</li></ul><p>Think of it as the neuron saying:</p><blockquote><em>“I’ve already reached my max — I can’t tell the network this house is worth even more.”</em></blockquote><h4>Vanishing Gradients</h4><p>Vanishing gradients happen <strong>because of saturation</strong>.</p><ul><li>During backpropagation, the network calculates <strong>gradients</strong> (signals telling it how much to adjust weights).</li><li>If a neuron is saturated, the gradient becomes <strong>very small</strong>, so weight updates are tiny.</li><li>This makes learning <strong>extremely slow</strong>, especially in deep networks with many layers.</li></ul><p><strong>Example:</strong></p><ul><li>A neuron predicts a mid-sized house at $350k but it should be $400k.</li><li>If the neuron is near saturation, the gradient is almost zero. Each training step only nudges the prediction slightly. After many epochs, it may eventually get closer to $400k — but the process is <strong>painfully slow</strong>.</li></ul><h4>Exploding Gradients</h4><p>Exploding gradients happen when weights <strong>grow too large</strong>, making gradients <strong>huge</strong>.</p><ul><li>During backpropagation, this causes massive updates to weights.</li><li>Predictions swing wildly, and the network may fail to learn at all.</li></ul><p><strong>Example:</strong></p><ul><li>A small starter house should be $150k.</li><li>In one update, the prediction jumps to $1M, then drops to $50k in the next update.</li><li>The network can’t stabilize and training becomes chaotic.</li></ul><h3>Epochs, Batches, and Iterations</h3><p>Training happens in <strong>epochs, batches, and iterations</strong>:</p><ul><li><strong>Mini-batch:</strong> A small subset of houses processed together.</li><li><strong>Iteration:</strong> One batch processed.</li><li><strong>Epoch:</strong> One full pass through the dataset.</li></ul><p>Example: 10,000 houses with batch size 100 → 100 iterations per epoch. Multiple epochs allow the network to gradually refine predictions.</p><h3>Regularization and Generalization</h3><h4>Regularization</h4><p>Regularization <strong>prevents the network from memorizing the training data</strong> and keeps it from relying too heavily on any single feature.</p><ul><li>Example: Without regularization, the network might think “every house in this neighborhood costs $500k,” ignoring size, bedrooms, or age.</li><li>Techniques like <strong>dropout</strong> (temporarily ignoring neurons) and <strong>weight decay</strong> (penalizing very large weights) make the network focus on <strong>real patterns</strong>, not memorization.</li></ul><h4>Generalization</h4><p>Generalization is the network’s ability to <strong>make accurate predictions on new houses it hasn’t seen</strong>.</p><ul><li>Example: A house in a neighborhood not in the training data is predicted at $350k because the network learned <strong>how features like lot size, bedrooms, and age interact</strong>, rather than memorizing specific houses.</li><li><strong>Regularization</strong> = keeps the model from overfitting.</li><li><strong>Generalization</strong> = ensures accurate predictions on unseen data</li></ul><h3>Conclusion</h3><p>Training a deep learning model is like teaching a computer to price houses intelligently. It learns to combine multiple features, adjust predictions based on errors, and improve gradually. Dropout, batch normalization, optimizers, and careful handling of gradients make learning stable, accurate, and generalizable, allowing the model to predict prices reliably even for houses it has never seen before.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18d09297d00e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding PCA in ML]]></title>
            <link>https://medium.com/@shan123.gym/understanding-pca-in-ml-3d99d949c1eb?source=rss-d69f97fdde1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d99d949c1eb</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[principal-component]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ml-model]]></category>
            <dc:creator><![CDATA[Shanmugapriyan Gopalakrishnan]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 21:50:22 GMT</pubDate>
            <atom:updated>2026-01-28T21:52:01.487Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In machine learning, we often work with datasets that have many columns (features). At first glance, having more features sounds good. More data should mean better predictions. But in practice, many of these features are strongly related to each other. In Insurance data, Premium and Sum Assured usually move together. Policy Term and Tenure are also connected.</p><p>This is where PCA (Principal Component Analysis) comes in. PCA helps us simplify the data without losing the important information.</p><h3>What is PCA</h3><p>PCA is a technique that converts/transforms many correlated features into a smaller number of new, uncorrelated features (Principal components) which capture the maximum variance.</p><p>It reduces features by rotating the data to new axes where variance is maximum, while keeping minimum information loss. It removes redundancy and noise. In other words, PCA does not change the underlying structure or information in the data. It only changes how the data is represented, by rotating the axes.</p><h3><strong>Why PCA is needed</strong></h3><p>Consider a typical insurance dataset Annual Premium, Sum Assured, Policy Term, Policy Tenure, Rider Count</p><p>Many of these features move together. This leads to below problems:</p><ol><li><strong><em>Multicollinearity </em></strong>— Linear models struggle when features are strongly correlated. Coefficients become unstable and hard to interpret</li><li><strong><em>Overfitting </em></strong>— Redundant features increase dimensionality without adding new information. Models start fitting noise</li><li><strong><em>Slower training </em></strong>— More features = more computation, especially for large datasets</li></ol><p>PCA addresses these problems by creating new, uncorrelated features (principal components) that summarize the original data.</p><p><strong>Step-by-step effect:</strong></p><ol><li>Removes redundancy / multicollinearity</li></ol><blockquote>Original correlated features — combined into PC1, PC2</blockquote><blockquote>PCs are orthogonal (uncorrelated) — linear models no longer suffer from multicollinearity.</blockquote><p>2. Reduces dimensionality / overfitting</p><blockquote>Keep only top components (e.g., PC1 captures 95% of variance)</blockquote><blockquote>Drop minor components (PC2, PC3) — reduces noise</blockquote><blockquote>Model focuses on main patterns — better generalization</blockquote><p>3. Speeds up training</p><blockquote>Fewer features — faster computation for almost all ML algorithms.</blockquote><p><strong>Example: Original features: Premium, Sum Assured, Policy Term, Rider Count</strong></p><p><strong>Without PCA:</strong></p><p>Model sees 4 separate inputs.</p><p>Premium &amp; Sum Assured give overlapping signals — multicollinearity.</p><p>Model might overweight one feature, underweight another — unstable predictions.</p><p><strong>With PCA:</strong></p><p>PC1 = combination of Premium + Sum Assured + Rider Count (captures 90–95% variance)</p><p>PC2 = minor deviations (5–10%) — optional</p><p>Model sees 1 main signal — more stable and faster training</p><p><em>Machine Learning learns from differences. PCA finds the direction where differences between data points are the strongest and removes directions where differences are too small to be useful</em>.</p><h3>PCA Concepts</h3><ol><li><strong>Variance:</strong></li></ol><p>Variance means how spread out the data is.</p><p>High variance — lots of information</p><p>Low variance — very little information (often noise)</p><p>PCA always tries to maximize variance.</p><p><strong>2. Principal Components:</strong></p><p>PC1 — direction with maximum variance</p><p>PC2 — perpendicular to PC1, next highest variance</p><p>PCs are always 90° apart (orthogonal)</p><p><strong>3. Eigenvalues &amp; Eigenvectors:</strong></p><p>Eigenvector — direction of spread (axis)</p><p>Eigenvalue — how much variance exists along that direction</p><h3>PCA Step-by-Step</h3><p>Let’s take two features:</p><p>Annual Premium (X)</p><p>Sum Assured (Y)</p><h4>Step 1: Standardize the data</h4><p>We convert values to the same scale. Because PCA is sensitive to scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/1*OXRuOcrS06XaoTtmvy1iYA.png" /></figure><h4>Step 2: Compute covariance matrix</h4><p>Covariance tells us how features move together. If covariance is high, features are strongly related.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*POP-Rn5K-ksCLS8JGMywZg.png" /></figure><h4>Step 3: Find eigenvalues and eigenvectors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*0EIFm3C5uf4lbSiF8rfbYw.png" /></figure><p>Eigenvalues: λ1,λ2</p><p>Eigenvectors: v1,v2</p><p>Each eigenvector is a <strong>new axis direction</strong></p><h4>Step 4: Select the principal components</h4><p>Sort eigenvalues in descending order</p><p>Largest eigenvalue — PC1</p><p>Second largest — PC2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*Ui7DmnkQck-D91Rd5davSw.png" /></figure><p>Example:</p><p>PC1 = 95% ; PC2 = 5%</p><h4>Step 5: Choose top k components</h4><p>If PC1 captures 95% variance:</p><p>Keep PC1</p><p>Drop PC2</p><p>This reduces dimension without losing much information.</p><h4>Step 6: Project data onto PC1</h4><p>New feature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*umFI_CqKdaDKC4URA2DZyg.png" /></figure><p>This becomes the input to ML models.</p><p><strong>Why PC1 captures maximum variance</strong></p><p>Because PC1 is chosen as the direction where:</p><blockquote>Data points are most spread out</blockquote><blockquote>Information content is highest</blockquote><blockquote>Patterns are strongest</blockquote><p>Perpendicular directions:</p><blockquote>Points are close together</blockquote><blockquote>Mostly noise</blockquote><blockquote>Less useful for prediction</blockquote><h4>Summary:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*8NJ5Y0t06teT9Vt2h7XHHA.png" /></figure><h4>Conclusion:</h4><p>PCA helps us simplify complex data by finding the directions where it varies the most. It turns correlated features into a smaller set of meaningful components, removing redundancy and noise. This makes machine learning models faster, more stable, and better at learning real patterns. In short, PCA doesn’t change the information — it just shows it from a smarter angle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d99d949c1eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predict Anything with Decision Trees: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@shan123.gym/predict-anything-with-decision-trees-a-step-by-step-guide-9b173817a60b?source=rss-d69f97fdde1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b173817a60b</guid>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ml-model]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shanmugapriyan Gopalakrishnan]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 03:00:41 GMT</pubDate>
            <atom:updated>2025-12-26T03:00:41.031Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decision Trees: How They Work and Why They Matter</h3><p>Decision Trees are one of the most popular algorithms in machine learning. They are simple to understand, easy to visualize and form the <strong>foundation for more advanced models</strong> like Random Forests and Boosting. In this article, I will explain <strong>everything you need to know about decision trees</strong> — from root nodes to leaf nodes, splitting criteria, stopping rules.</p><h3><strong>What is a Decision Tree?</strong></h3><p>A decision tree is a model that predicts a target variable by <strong>splitting data into groups</strong> based on feature values. It looks like a flowchart:</p><ul><li><strong>Root node:</strong> The topmost node that represents the first feature chosen to split the data.</li><li><strong>Internal nodes:</strong> Nodes where further splits happen based on other features.</li><li><strong>Branches:</strong> Paths connecting nodes based on feature conditions.</li><li><strong>Leaf nodes:</strong> Terminal nodes that provide the final prediction (label for classification, value for regression).</li></ul><p><strong>Advantages:</strong></p><ul><li>Easy to understand and interpret</li><li>Works for <strong>classification</strong> (categorical target) and <strong>regression</strong> (continuous target)</li><li>Doesn’t follow a fixed pattern; works with any kind of data</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Can overfit if tree grows too deep</li><li>Sensitive to small changes in data (high variance)</li></ul><h3>How Decision Trees Are Built</h3><h4>a) Root Node Selection</h4><p>The root node is the feature that divides the data so that each resulting group contains mostly similar values. Choosing the right root node is crucial because it affects the entire tree structure.</p><p><strong>Common criteria to select the root node:</strong></p><p><strong>1. Gini Impurity:</strong></p><p>It shows how mixed the classes are in a group. i.e., It measures how often a randomly chosen element would be incorrectly classified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*VkxJhoHfUES9SyVgFlr4xw.png" /></figure><p>Where C = number of classes, Pi​ = proportion of class i in the node.</p><p><strong>Example:</strong></p><ul><li>Node has 10 samples: 7 Positive, 3 Negative</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*Daz7SIRhH96-Al6kiGa6Iw.png" /></figure><ul><li>Lower Gini → more pure node → preferred for root</li></ul><p>2.<strong> Entropy:</strong></p><p>It measures <strong><em>how uncertain or mixed the data is</em></strong></p><ul><li>High entropy → data is mixed (more confusion)</li><li>Low entropy → data is clean (less confusion)</li><li>Zero entropy → all data belongs to one class (no confusion at all)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*5afTGzeCIOyegk5q36Z2kg.png" /></figure><p><strong>Example:</strong></p><p>Suppose a node has 10 records:</p><ul><li>7 Yes</li><li>3 No</li></ul><p>This node is mixed → <strong>high entropy</strong></p><p><strong>Calculate probabilities</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*MeHvdwqkGPfamIl8CQ9uDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*jLG9cnylvehiys6u9hIVIg.png" /></figure><p>Entropy = <strong>0.881</strong>, which means the node is <strong>mixed</strong></p><p>If a node has:</p><ul><li>10 Yes</li><li>0 No</li></ul><p>This node is very pure → <strong>Entropy = 0</strong></p><p><strong>Information Gain — </strong>It tells how much uncertainty/confusion is reduced after a split</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*cKjXt_Ioe2O2DsLkDaxOgw.png" /></figure><h4>Feature Split: “Has Job?”</h4><p>Suppose after splitting on this feature:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*y82ekrA854lBzU0Znsu6Yg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*6X7_W_Z7VgY0n3SKJ2ZH3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*tRDTIhC96wIQe6mUIj3EAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*R6h7QI_0ngfAypandpDFtA.png" /></figure><ul><li>High information gain → good split</li><li>Low information gain → bad split</li></ul><p>The feature with the <strong>highest information gain</strong> becomes the root node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*0s2NsiVUe4138ArsnBVCNg.png" /></figure><ul><li>Information Gain = <strong>0.09</strong>, which is <strong>small but positive</strong></li><li>This split <strong>reduces uncertainty slightly</strong></li></ul><p>Decision trees:</p><ol><li>Calculate entropy before split</li><li>Try different features</li><li>Choose the feature with <strong>maximum information gain</strong></li></ol><p><strong>3. Other measures:</strong></p><p><strong>Mean Squared Error</strong> for regression</p><h4>b) Splitting Nodes</h4><p>After selecting the root node, the tree recursively <strong>splits the data</strong> at each internal node:</p><ul><li>At each node, the algorithm evaluates all features</li><li>Chooses the feature that <strong>best reduces impurity</strong> in the child nodes</li><li>Continues until stopping criteria are met</li></ul><h4>c) Stopping Criteria</h4><p>To prevent the tree from growing infinitely:</p><ul><li>Maximum depth (max_depth)</li><li>Minimum samples to split a node (min_samples_split)</li><li>Minimum samples per leaf (min_samples_leaf)</li><li>Minimum impurity decrease (min_impurity_decrease)</li><li>All nodes are pure (contain only one class)</li></ul><h3>Decision Tree Types</h3><ol><li><strong>Classification Tree:</strong> Predicts categories (Yes/No, Class A/B/C)</li><li><strong>Regression Tree:</strong> Predicts continuous numbers (like price or temperature)</li></ol><p><strong>Regression tree splits</strong> minimize <strong>Mean Squared Error (MSE):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*boMmCuNMYC1qAwbfuAC2fA.png" /></figure><h3>Bias-Variance Perspective</h3><ul><li><strong>Shallow tree:</strong> High bias, low variance → may underfit</li><li><strong>Deep tree:</strong> Low bias, high variance → may overfit</li></ul><h3>Handling Overfitting</h3><ul><li>Limit <strong>tree depth</strong></li><li>Set <strong>minimum samples per leaf</strong></li><li><strong>Prune</strong> the tree (pre-pruning or post-pruning)</li><li>Use <strong>ensemble methods</strong> like Random Forests or Boosting for stability</li></ul><h3>Conclusion</h3><p>Decision Trees work by breaking a problem into smaller, easy-to-understand decisions based on data. Knowing how features are chosen at each split, how the tree grows, and how to control overfitting makes the model more accurate.</p><p>A solid understanding of decision trees helps in building real-world machine learning solutions and also makes it easier to learn advanced models like Random Forest and Boosting, since they are built on top of decision tree logic.</p><h3>Follow &amp; Share</h3><p>If you enjoyed this article, <strong>follow me on Medium</strong> for more stories about Machine Learning and AI!<br><em>#MachineLearning #ArtificialIntelligence #DataScience #ML Model #Decision Tree</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b173817a60b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Titanic Survival with FastAPI: From Model Building to API Deployment]]></title>
            <link>https://medium.com/@shan123.gym/predicting-titanic-survival-with-fastapi-from-model-building-to-api-deployment-aa358d10099f?source=rss-d69f97fdde1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa358d10099f</guid>
            <category><![CDATA[ml-model-deployment]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shanmugapriyan Gopalakrishnan]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 01:59:48 GMT</pubDate>
            <atom:updated>2025-12-05T02:24:40.035Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning is not just about building models — it’s also about making them accessible so others can use them easily. I will walk you through how I built a <strong>Titanic Survival Prediction model</strong> and turned it into a <strong>FastAPI application</strong> that anyone can interact with via endpoints.</p><h3>Understanding the Dataset</h3><p>For this project, I used the <strong>Titanic dataset</strong> from Kaggle. It contains details of passengers such as:</p><ul><li>PassengerId, Pclass (ticket class)</li><li>Name, Sex, Age, Fare, Embarked</li><li>Some additional features like SibSp (siblings/spouses aboard), Parch (parents/children aboard) and Cabin</li><li>The target variable is Survived — 1 if the passenger survived, 0 if not.</li></ul><p><strong>Before building the model, I performed feature engineering:</strong><br>1. Extracted Title from passenger names (Mr, Mrs, Miss, etc.).<br>2. Imputed missing Age values using the median age per Title.<br>3. Imputed missing Embarked with the most frequent port.<br>4. Created Deck from the first letter of the cabin; filled missing decks as ‘Unknown’.<br>5. Calculated FamilySize as SibSp + Parch + 1 and a boolean IsAlone to indicate solo travelers.</p><h3>Building the Model Pipeline</h3><p>Instead of manually preprocessing and training, I used a <strong>pipeline</strong> for automation. This pipeline handled:</p><ol><li><strong>Numerical features</strong>: filled missing values and scaled them using StandardScaler.</li><li><strong>Categorical features</strong>: filled missing values and applied one-hot encoding.</li><li><strong>Class imbalance</strong>: used <strong>RandomUnderSampler</strong> from imblearn to balance the number of survivors and non-survivors.</li><li><strong>Model</strong>: a custom ThresholdClassifier wrapped around <strong>Logistic Regression,</strong> with a <strong>threshold of 0.55</strong> (based on the best optimal values derived in the confusion matrix).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*SOTNsaojjHj-eQpsCZFKwg.png" /></figure><p>This pipeline ensures all preprocessing, balancing and prediction steps happen automatically whenever we feed data into it.</p><h3>Training the Model</h3><p>After splitting the data into training and test sets, the pipeline was fitted on the training data. Predictions were made for both training and test sets:</p><ul><li>Training Accuracy: 0.84</li><li>Test Accuracy: 0.82</li></ul><p><strong>Confusion matrices and classification reports</strong> showed the model could predict survivors and non-survivors reliably.</p><p>Finally, the trained pipeline was saved as a .pkl file so we can load it in the API without retraining.</p><p><strong><em>joblib.dump(pipeline, ‘../models/model_balanced_threshold_0.55.pkl’)</em></strong></p><h3>Creating the FastAPI App</h3><p>Created the FastAPI app and Run the custom <strong><em>lifespan </em></strong>function during startup and shutdown to load the model and clean up resources.</p><p><strong><em>app = FastAPI(lifespan=lifespan)</em></strong></p><p>FastAPI works like a middleman — It receives data from the user, passes it to ML model, collects the result and sends the prediction back.</p><p>It is used to <strong>turn the model into an interactive API</strong>. Here’s how the endpoints were structured:</p><p><strong>Root Endpoint (/)</strong></p><ul><li>Welcome message</li><li>Version, author, and status</li><li>Available endpoints: <strong>/docs, /model_info, /predict</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7oorYCWKT4Zkb4eSmv3fGA.png" /></figure><p><strong>Model Info (</strong>/model_info<strong>)</strong></p><p>Returns details about the model:</p><ul><li>Model type: Logistic Regression with Threshold Classifier</li><li>Features used</li><li>Accuracy, Precision, Recall, F1 Score</li><li>Author, version, description</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mT-Ohjmxd9Zg6gQiiGLGg.png" /></figure><p>This helps users understand what the model is and how it performs.</p><p><strong>Prediction Endpoint (/predict)</strong></p><ul><li>Accepts passenger details as input (like Pclass, Age, Sex, Fare etc.)</li><li>Uses the loaded pipeline to predict survival probability</li></ul><p>By increasing the threshold to 0.55, the model predicts ‘Survived’ only when it’s more confident, which helps reduce false positives and makes the model more balanced.</p><p><strong>Prediction details of “Survived”:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzRhJVo_e3S0IsSBmC47Tg.png" /></figure><p><strong>Prediction detail of “NOT Survived”:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBf4pnzinH2McPdRAjrqOg.png" /></figure><h3>Conclusion</h3><p>I have trained a model to predict whether a passenger on the Titanic would survive based on details like age, ticket class, and gender. After training, the model learned patterns from the data and could estimate a survival probability for any new passenger.</p><p>To make this model easy to use, we wrapped it inside a FastAPI application. FastAPI acts like a small service that waits for someone to send passenger details, runs the model behind the scenes and instantly returns the survival prediction.</p><h3>Follow &amp; Share</h3><p>If you enjoyed this article, <strong>follow me on Medium</strong> for more stories about Machine Learning and AI!<br><em>#MachineLearning #ArtificialIntelligence #DataScience #ML Model #</em>FastAPI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa358d10099f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Gradient Descent Optimizes Machine Learning Models!!]]></title>
            <link>https://medium.com/@shan123.gym/how-gradient-descent-optimizes-machine-learning-models-8f18a77858f9?source=rss-d69f97fdde1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f18a77858f9</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[regularization]]></category>
            <dc:creator><![CDATA[Shanmugapriyan Gopalakrishnan]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 00:09:28 GMT</pubDate>
            <atom:updated>2025-12-07T01:46:48.030Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning is all about <strong>making predictions, checking how wrong they are </strong>and <strong>improving them</strong>. Two concepts that are central to this are <strong><em>Gradient Descent</em></strong> and <strong><em>Regularization</em></strong>.</p><h3>What is Gradient Descent and Why Do We Use It?</h3><p>Gradient descent is an optimization algorithm<strong> to find the best values for a model’s parameters</strong> (weights and bias).</p><p>In simple terms:</p><ol><li>The model makes predictions.</li><li>We calculate the <strong>error</strong> (difference between predicted and actual values).</li><li>We adjust the model’s parameters <strong>slightly in the direction that reduces error</strong>.</li><li>Repeat until the error is minimal.</li></ol><p>Gradient descent iteratively updates model parameters to minimize the loss function and works in almost all machine learning algorithms, including:</p><ul><li>Regression (predicting numbers)</li><li>Classification (predicting categories)</li><li>Deep learning (neural networks)</li></ul><p>As long as we can calculate the slope of the loss function (finding its <strong>derivative</strong>) at every point, gradient descent can adjust the model’s weights to reduce the prediction error.</p><h3>How Gradient Descent Reduces Error</h3><p>Let’s take H<strong>ouse Price </strong>example with three features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*QOtns90X2nH57UANHptwlw.png" /></figure><p>Linear model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*GgFvsp7VEbA67mYs4YDvXA.png" /></figure><h4>Step 1: Calculate Error</h4><p>We use <strong>Mean Squared Error (MSE)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*ixd6vtIYK95AWQ25aMSBow.png" /></figure><ul><li>Large difference — large loss</li><li>Small difference — small loss</li></ul><h4>Step 2: Compute Gradient (Derivative)</h4><p>To reduce loss, we check <strong>how changing each weight affects the error</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*C71TLori7zn3U0stSaaRBA.png" /></figure><p>Partial derivatives help to update each weight individually.</p><h4>Step 3: Update Weights</h4><p>Weights are updated using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*2bXzskuc2vHJnNjLcQ15BA.png" /></figure><ul><li>α = learning rate (step size)</li><li>Repeating this process gradually <strong>reduces the error</strong>.</li></ul><p>If slope <strong>positive</strong> — weight should go <strong>down(</strong>decreasing the weight reduces the error)</p><p>If slope <strong>negative</strong> — weight should go <strong>up (</strong>increasing the weight reduces the error)</p><p><strong>Linear model:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*OFbCYxFRI8I1s1eP7vw4-A.png" /></figure><p><strong>Initial parameters</strong></p><p>w1=50, w2=30, w3=20, b=100, α=0.01</p><ol><li><strong>Calculate residuals:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*zssHu-CR6reKBu1o4D4AuA.png" /></figure><p>So residuals (actual − predicted) are [120,250,380]</p><p>Mean squared error (MSE):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*wszwYlRjSGniy-sPDxTtgA.png" /></figure><p>2. <strong>Compute the partial derivative (slope) w.r.t. w1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*CrjAq4NdQLwgNpyUt1dGHw.png" /></figure><p>Interpretation: derivative is <strong>negative</strong>, which means <strong>increasing w1</strong> will reduce the loss.</p><p><strong>3) Update w1​ using gradient descent:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*4rY7bypOPCzGatYwq8u8zg.png" /></figure><p><strong>4) Recompute predictions (only w1​ changed; others unchanged):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*sJ0sdu1mAgeUk5dA3PH-nA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*V9Q7fFKC0T3TgCRCfr-TVQ.png" /></figure><p>Because the derivative was <strong>negative</strong>, gradient descent <strong>increased w1​</strong> (from 50 → 61.733…) and that change <strong>reduced the prediction errors</strong> for all three houses.</p><h3>How Regularization Works</h3><p>Sometimes, model fits the training data <strong>too well</strong>.</p><ul><li>Overfitting = model memorizes noise → poor predictions on new data</li><li>Solution = <strong>regularization</strong></li></ul><p>Regularization adds a <strong>penalty for large weights</strong> to the loss function.</p><h4>L2 Regularization (Ridge)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*WcmNRFIbZGvXUZOhpAmIFw.png" /></figure><p>Gradient descent now <strong>shrinks weights</strong> to prevent overfitting.</p><p><strong>Example With Regularization (w1 only):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ju1T_s89OK8RePhRkG1_7Q.png" /></figure><p>Notice the <strong>weight grows slower</strong> because of the penalty — this prevents overfitting.</p><h3>How Gradient Descent and Regularization Work Together</h3><ul><li><strong>Gradient descent:</strong> finds weights that <strong>minimize loss</strong></li><li><strong>Regularization:</strong> prevents weights from becoming <strong>too large</strong>, keeping the model simple</li><li>Together: gradient descent <strong>optimizes parameters</strong> while regularization <strong>controls complexity</strong></li></ul><h4><strong>Trade-offs:</strong></h4><p>Gradient descent and regularization work together, but sometimes in opposite ways. Gradient descent wants to adjust the weights as much as needed to minimize the error, while regularization gently pulls the weights back to keep them from getting too large.</p><p>The balance between these two is a <strong>tradeoff</strong>: we aim for weights that are big enough to fit the data well, but not so big that the model overfits.</p><h4><strong>Conclusion:</strong></h4><ul><li>By calculating the partial derivative with respect to w1, we find out <strong>how the loss changes</strong> when we slightly adjust that weight.</li><li>In this example, the derivative turned out to be <strong>negative</strong>, which means <strong>increasing w1​</strong> will lower the error.</li><li>After updating w1(from 50 to around 61.73), the prediction errors for all three houses <strong>became smaller</strong>, showing that the model’s predictions moved closer to the actual values.</li><li>The overall loss (MSE) dropped noticeably after just <strong>one</strong> update step. Repeating this process across all weights gradually reduces the error until the model reaches the best-possible parameter values.</li><li>Without regularization, gradient descent may keep increasing or decreasing weights aggressively if the data is noisy or the features are highly correlated. This can make the model focus too much on the specific training data, learning even random quirks, which hurts its ability to make accurate predictions on new data and leads to overfit.</li><li>Regularization adds a penalty term (for example, <strong>L2: 2λw</strong>) to the gradient. This extra term gently pushes large weights back toward smaller values. So even though gradient descent moved w1​ upward to ~61.73 because it reduced the error, <strong>regularization would counter-balance that movement</strong> and prevent the weight from growing unnecessarily large.</li><li>In practice, gradient descent tries to reduce the prediction error, while regularization tries to keep the weights reasonable and stable. Together, they find a balanced point — a weight value like ~61.73 that reduces error <strong>without</strong> growing too large and risking overfitting.</li></ul><h3>Follow &amp; Share</h3><p>If you enjoyed this article, <strong>follow me on Medium</strong> for more stories about Machine Learning and AI!<br><em>#MachineLearning #ArtificialIntelligence #DataScience #Gradient Descent #</em>Regularization</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f18a77858f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Titanic Survival Using Logistic Regression on Kaggle Dataset]]></title>
            <link>https://medium.com/@shan123.gym/predicting-titanic-survival-using-logistic-regression-on-kaggle-dataset-b8f6cbac8f49?source=rss-d69f97fdde1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8f6cbac8f49</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-algorithm]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shanmugapriyan Gopalakrishnan]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 23:48:11 GMT</pubDate>
            <atom:updated>2025-11-24T23:56:53.416Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dataset</h3><p>Kaggle Titanic dataset contains information about passengers on the Titanic ship such as <strong>age, gender, ticket class, survival status</strong>.</p><h3>Goal</h3><p>The main goal is to <strong>predict whether a passenger survived</strong> based on their features. This is a binary classification problem: survived (1) or not survived (0).</p><h3>Data Preparation</h3><p>Before modeling, the data was cleaned and prepared:</p><ul><li>Categorical features like Sex, Embarked, Deck were converted to numbers.</li><li>Numeric features like Age, Fare, Family Size were scaled to make the model more accurate.</li></ul><h3>Model Used</h3><p><strong>Logistic Regression</strong> algorithm was applied. It predicts the <strong>probability of survival</strong> for each passenger. Values close to 1 mean high chance of survival and values close to 0 mean low chance.</p><h3>Evaluation Metrics</h3><p>The model was evaluated using below metrics:</p><ul><li>Accuracy</li><li>Precision, Recall, F1-score</li><li>ROC AUC score</li></ul><h3>Scores:</h3><p>Below are the Train and Test scores:</p><ol><li><strong>Accuracy:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*ZDvjh2ufEpY3TiQ_GIOP1Q.png" /></figure><p><strong>2. Classification Report:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*tlowOsG_k7LbOr-0kyIrrg.png" /></figure><p><strong>3. Confusion Matrix:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*d7KwVbrUEWSW-UnXCJfFJg.png" /></figure><p><strong>4. AUC Score:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*49yVim9dhHK0GsrIFgfeyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*M3ALRYSvukHZKDKgmaNSMw.png" /></figure><p><strong>ROC Curve:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*qc-YBrpy3_tv7bl588hCLA.png" /></figure><h3>Conclusion</h3><p>The model showed that <strong>gender and passenger class</strong> were important factors. Females and higher class passengers were more likely to survive.</p><h3>Follow &amp; Share</h3><p>If you enjoyed this article, <strong>follow me on Medium</strong> for more stories about Machine Learning and AI!<br><em>#MachineLearning #ArtificialIntelligence #DataScience #MLModel #LogisticRegression</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8f6cbac8f49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Classification Metrics in Machine Learning..]]></title>
            <link>https://medium.com/@shan123.gym/understanding-classification-metrics-in-machine-learning-b52634f2feee?source=rss-d69f97fdde1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b52634f2feee</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shanmugapriyan Gopalakrishnan]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 02:02:26 GMT</pubDate>
            <atom:updated>2025-11-23T02:02:26.180Z</atom:updated>
            <content:encoded><![CDATA[<p>Every prediction we see — whether it’s detecting disease, identifying spam or forecasting stock movements — begins with a simple question: <em>Did the model get it right?</em><br> In this story walks you through how machines learn to answer that question with confidence.</p><h3>What Is Classification?</h3><p>In the simplest form, classification answers a question: <strong><em>“Which category does this belong to?”</em></strong></p><p>Imagine on sorting emails:</p><ul><li>Some are <strong>Spam</strong></li><li>Some are <strong>Important (Valid and Not Spam)</strong></li></ul><p>Or predicting whether a person has <strong>diabetes (Yes/No)</strong>.<br> This kind of problem where the output is a <strong>category</strong> and it is called <strong>classification</strong>.</p><h3>What Is Logistic Regression?</h3><p>Despite its name, logistic regression is actually a <strong>classification algorithm</strong>. It predicts a <strong>probability between 0 and 1</strong>.</p><p>Example:<br> Given a patient’s health data, the model predicts:</p><p><em>“There’s a 0.82 probability that the person has diabetes.”</em></p><p>If probability ≥ 0.5 — classify as <strong>Yes (1) </strong>If &lt; 0.5 — classify as <strong>No (0)</strong></p><h4><strong>Confusion Matrix — The Root of All Metrics:</strong></h4><p>Before judge how good a classification model is, need a way to <strong>compare what the model predicted vs what actually happened</strong>.</p><p>That’s where the <strong>confusion matrix</strong> comes in.</p><p>It answers four simple questions:</p><ul><li><em>When the real answer is YES, did the model also predict YES? (True Positive — TP)</em></li><li><em>When the real answer is NO, did the model mistakenly predict YES? (False Positive — FP)</em></li><li><em>When the real answer is YES, did the model mistakenly predict NO? (False Negative — FN)</em></li><li><em>When the real answer is NO, did the model also predict NO? (True Negative — TN)</em></li></ul><p>These four possibilities form the confusion matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*oE3O4aeeY4vHB3Rb-coUHw.png" /></figure><p>Every performance metric — accuracy, recall, precision, F1 score, ROC — comes from these four boxes.</p><h4><strong>1. Accuracy:</strong></h4><p>Accuracy tells how many predictions were correct overall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*-2c7M0sUIElYH70f4s3v9w.png" /></figure><p>Imagine a bank has <strong>100 recent transactions</strong>:</p><ul><li><strong>95 are normal (not fraud)</strong></li><li><strong>5 are fraudulent (fraud cases)</strong></li></ul><p>We want a model to <strong>detect fraud</strong>.</p><p>Now suppose the model predicts — <em>“All transactions are normal (not fraud)”</em></p><ul><li>It correctly identifies all <strong>95 normal transactions</strong> — True Negative (TN)</li><li>It <strong>fails to detect the 5 fraud transactions</strong> → False Negatives (FN)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*Q4ecazpX0uG3Sov588wdbg.png" /></figure><p>Even though accuracy is <strong>95%</strong>, the model <strong>did not catch any fraud</strong> — which is the main goal.</p><p>Accuracy does not highlight:</p><ul><li>How many frauds (positive cases) were detected</li><li>How many were missed</li><li>Whether the model is biased toward “not fraud”</li></ul><p>It only answers ️ “How many predictions were correct overall?”</p><p>That’s why <strong>precision, recall, F1-score</strong> are needed.</p><h4>2. Recall / Sensitivity (Diabetes Example)</h4><p>Recall answers: <strong><em>“Out of all actual positives, how many did we catch?”</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*Wi7SN_fT7xK-0fhP8uiB5Q.png" /></figure><p><strong>Diabetes Example:</strong></p><p>Suppose 100 patients actually have diabetes. Your model identifies only 70 the rest (30) were missed.</p><ul><li>TP = 70</li><li>FN = 30</li><li>Recall = 70 / (70 + 30) = <strong>70%</strong></li></ul><p>Missing a diabetes patient (false negative) is dangerous. So in healthcare, <strong>recall is extremely important</strong>.</p><p><strong>Specificity:</strong></p><p>If recall focuses on catching positives, <strong>specificity</strong> focuses on correctly identifying negatives.</p><p>It answers: <strong><em>“Out of all healthy people, how many did we correctly classify as healthy?”</em></strong></p><h4><strong>3. Precision (Spam Email Example)</strong></h4><p>Precision answers: “Of all the cases the model predicted as positive, <strong>how many are actually positive?”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*eByGrhG8ewtiTjfMd4ZEug.png" /></figure><p>Imagine your email spam filter flags <strong>100 emails</strong> as spam.</p><ul><li><strong>80 are actually spam</strong> — True Positives (TP)</li><li><strong>20 are actually important emails</strong> — False Positives (FP)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*v63EpaXT7di4Az7eEyGIFQ.png" /></figure><p>If precision is low, it means:</p><ul><li>Many of the emails flagged as spam are <strong>actually important emails</strong></li><li>These important emails are <strong>wrongly sent to the spam folder</strong></li></ul><h4><strong>4. F1 Score — (</strong>Job Application Screening Example<strong>)</strong></h4><p>Precision and recall often conflict.</p><ul><li>High recall — catch most positives but with more false positives</li><li>High precision — avoid false positives but may miss actual positives</li></ul><p><strong>F1 score balances them.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*t72So-Kx1oh1BMkb2M0LJA.png" /></figure><p>Imagine a company using a machine learning model to <strong>screen job applications</strong> for a coding position:</p><ul><li><strong>Recall</strong>: Catch <strong>all truly qualified candidates</strong> — don’t miss talent.</li><li><strong>Precision</strong>: Make sure that candidates flagged as qualified <strong>are actually qualified</strong> — don’t interview unqualified people unnecessarily.</li></ul><h4>Scenario:</h4><p>Out of 200 applicants: 50 are actually qualified</p><p>The model predicts 60 applicants as qualified:</p><ul><li>40 are truly qualified — True Positives (TP)</li><li>20 are unqualified but flagged — False Positives (FP)</li><li>10 qualified applicants were missed — False Negatives (FN)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*0WyGBZI6f_Idll7dIv8ZCw.png" /></figure><ul><li><strong>F1 Score balances precision and recall</strong></li><li>Here, the model catches most qualified candidates (<strong>high recall</strong>) while limiting false interviews (<strong>moderate precision</strong>)</li></ul><h4>5. ROC &amp; AUC Curve</h4><p>It helps to understand performance across thresholds.</p><h4>ROC Curve (Receiver Operating Characteristic)</h4><p>ROC curve is a <strong>graph</strong> that shows how well a classification model can distinguish between <strong>positive</strong> and <strong>negative</strong> classes.</p><p>It plots <strong>two rates</strong>:</p><ol><li><strong>True Positive Rate (TPR / Recall / Sensitivity)</strong> — fraction of actual positives correctly identified</li><li><strong>False Positive Rate (FPR)</strong> — fraction of actual negatives incorrectly predicted as positive</li></ol><ul><li>Each point on the ROC curve represents a <strong>different decision threshold</strong> used by the model.</li><li>By looking at the curve, we can understand <strong>how the model’s true positive rate changes as we allow more false positives</strong>.</li></ul><h4>AUC (Area Under the Curve)</h4><ul><li>AUC is a <strong>single number</strong> summarizing the ROC curve.</li><li>It measures the model’s <strong>ability to separate positive and negative classes</strong>.</li></ul><p><strong>Interpretation:</strong></p><ul><li><strong>1.0</strong> → perfect separation between positives and negatives</li><li><strong>0.5</strong> → model performs no better than random guessing</li><li><strong>&lt;0.5</strong> → model is worse than random</li></ul><h4>Conclusion:</h4><p>Logistic regression and other classification models make predictions, but we need metrics to evaluate how accurate those predictions are.</p><p>Measures like accuracy, precision, recall, F1 score, ROC, and AUC reveal where the model performs well and where it struggles. By considering these metrics together, we can better trust the model’s decisions and refine it for improved performance.</p><h3>Follow &amp; Share</h3><p>If you enjoyed this article, <strong>follow me on Medium</strong> for more stories about Machine Learning and AI!<br><em>#MachineLearning #ArtificialIntelligence #DataScience #MLforBeginners #AI</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b52634f2feee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Polynomial Regression and How Regularization Helps in House Price Prediction!!]]></title>
            <link>https://medium.com/@shan123.gym/understanding-polynomial-regression-and-how-regularization-helps-in-house-price-prediction-ef3179eb89f7?source=rss-d69f97fdde1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef3179eb89f7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shanmugapriyan Gopalakrishnan]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 23:44:41 GMT</pubDate>
            <atom:updated>2025-11-21T23:59:20.934Z</atom:updated>
            <content:encoded><![CDATA[<p>Predicting house prices is not as simple as drawing a straight line. For example, In the House price calculation, Sales price of the house depends on many factors like lot size, bedrooms, garage, locality, etc..</p><p>A simple linear model assumes every feature affects price in a straight-line way, which is wrong. For example, adding 100 sq. ft. might not always increase price by the same amount — it could rise faster or slower depending on other factors. <strong>Polynomial regression</strong> helps by allowing the model to capture these curves and more realistic patterns in the data.</p><h3>The Need for Polynomial Regression</h3><p>Polynomial regression allows us to <strong>capture curves and complex relationships</strong> in data. By generating new features like squared, cubed values or combinations of existing features, we can follow curves in the data that a straight line cannot fit. For instance:</p><ul><li>A house with a slightly bigger garden may increase price moderately.</li><li>A very large garden can raise the price much more than expected because big lots are rare.</li></ul><p>Here, a <strong>linear model fails</strong>, but a polynomial model can <strong>fit the curve of reality.</strong></p><h3>Polynomial Features and the Role of Degree</h3><p>Polynomial features are new features created by raising original features to powers or by combining them with other features. For example, if we have the feature:</p><ul><li>Degree 2 → GarageSize²</li><li>Degree 3 → GarageSize³</li><li>Interaction features → GarageSize * HouseAge</li></ul><p>These features allow the model to capture <strong>non-linear relationships.</strong></p><p>The <strong>degree</strong> determines the flexibility of the model:</p><ul><li>Low degree (1–2) → captures gentle curves, avoids extreme flexibility</li><li>High degree (10+) → captures very wiggly patterns, fits training data extremely well</li></ul><p>While higher degrees allow the model to learn <strong>complex relationships</strong>, they also carry a danger <strong>-</strong> <strong>overfitting</strong>.</p><h3>What is Overfitting?</h3><p>Simple answer — “When the Model Remembers Too Much”</p><p>Overfitting happens when a model <strong>fits the training data perfectly</strong>, including the noise, but <strong>fails on unseen test data</strong>. In our house price example:</p><ul><li>A degree (say 10) polynomial may perfectly predict all prices in the training dataset.</li><li>But when predicting a new house, the model may wildly overestimate or underestimate because it <strong>learned the noise</strong>, not just the pattern.</li></ul><p>Metrics like <strong>R² score</strong> and <strong>RMSE</strong> often look great on training data but <strong>drop on test data</strong> — a classic symptom of overfitting.</p><h3>Regularization:</h3><p>To prevent overfitting, we use <strong>regularization techniques</strong>, which act like a “penalty” for making the model too complex. The most popular methods are:</p><ol><li><strong>Ridge Regression (L2 regularization)</strong></li></ol><ul><li>Penalizes large coefficients</li><li>Shrinks them gradually</li><li>Keeps the model smooth and prevents it from going wild</li></ul><p><strong>2. Lasso Regression (L1 regularization)</strong></p><ul><li>Can shrink some coefficients <strong>exactly to zero</strong></li><li>Acts like a feature selector, ignoring irrelevant polynomial features</li></ul><p><strong>3. Elastic Net</strong></p><ul><li>Combines Ridge and Lasso</li><li>Balances between shrinking and zeroing coefficients</li><li>Especially useful when there are many correlated features (like multiple polynomial terms of lot size, square footage, etc.)</li></ul><h3>Impact on House Price Prediction</h3><p>In House Price dataset, I have experimented with <strong>Polynomial Regression of degree 2</strong>. Initially, without regularization, the model <strong>overfitted badly</strong>:</p><ul><li>Training R² is very high</li><li>Test R² is low</li><li>RMSE on test is very large</li></ul><p>After applying <strong>Ridge, Lasso, and Elastic Net</strong>, I observed:</p><ul><li>Test R² improved significantly</li><li>RMSE decreased</li><li>Predictions became more realistic</li></ul><h4><strong>Different Linear Model R² and RMSE scores (for Train and Test data):</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*Tzsl9Q-rlCXqZ-4G2xx7iA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*1irrkmW11zLbnqz1GOVhLg.jpeg" /></figure><p>With regularization, the model could filter out noisy features and focus only on the meaningful ones for predicting house prices.</p><h4><strong>Conclusion:</strong></h4><p>Polynomial regression is useful because it can capture complex patterns in house prices. But if the model is too flexible, it can overfit and perform poorly on new houses.</p><p>Regularization helps by controlling the model, keeping it focused on important patterns, and ignoring noisy features. Using polynomial features together with techniques like Ridge, Lasso, or Elastic Net creates a model that is both flexible and stable, giving more accurate predictions for unseen houses.</p><h3>Follow &amp; Share</h3><p>If you enjoyed this article, <strong>follow me on Medium</strong> for more stories about Machine Learning and AI!<br><em>#MachineLearning #ArtificialIntelligence #DataScience #MLforBeginners #AI</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef3179eb89f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>