<?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 Richa Rani on Medium]]></title>
        <description><![CDATA[Stories by Richa Rani on Medium]]></description>
        <link>https://medium.com/@richa.insights?source=rss-99e3d2ac59ad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nYywjEsOk64O2FTWswqVGQ.jpeg</url>
            <title>Stories by Richa Rani on Medium</title>
            <link>https://medium.com/@richa.insights?source=rss-99e3d2ac59ad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:55:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@richa.insights/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[Understanding XGBoost: How Gradient (First Derivatives) and Hessian (Second Derivatives) Improve…]]></title>
            <link>https://medium.com/@richa.insights/understanding-xgboost-how-gradient-first-derivatives-and-hessian-second-derivatives-improve-f4e3c0f7df2e?source=rss-99e3d2ac59ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4e3c0f7df2e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Richa Rani]]></dc:creator>
            <pubDate>Tue, 05 May 2026 15:32:35 GMT</pubDate>
            <atom:updated>2026-05-05T15:32:35.893Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding XGBoost: How Gradient (First Derivatives) and Hessian (Second Derivatives) Improve Machine Learning Models| Machine Learning Series Part 16</h3><p>There comes a point in life where just knowing what direction to move is not enough. Imagine you’re driving on a mountain road — the path is steep, the turns are sharp, and one wrong move can take you off track. Now, someone tells you, “Just keep moving in the right direction.” It sounds helpful, but it isn’t enough. Because on a mountain road, it’s not just about direction — it’s about how sharply you should turn and how fast the slope is changing. Just like on a mountain road, reaching the destination isn’t just about moving forward — it’s about understanding the turns along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ft_w3uN3cqxOF4H9zgUa0g.png" /></figure><p>In Machine Learning, especially in boosting algorithms, models learn step by step. They don’t learn everything at once —</p><ul><li>First model makes mistakes</li><li>Second model tries to correct those mistakes</li><li>Third improves further… and so on</li></ul><p>This is called <strong>ensemble learning</strong>.</p><p>In algorithms like <strong>XGBoost (Extreme Gradient Boosting, introduced around 2016)</strong>:</p><ul><li>We combine <strong>many weak learners </strong><a href="https://medium.com/@richa.insights/decision-tree-in-machine-learning-explained-with-gini-index-entropy-and-python-code-060015094456"><strong>(decision trees)</strong></a></li><li>Each new tree learns from <strong>previous errors.</strong></li></ul><h3>What Is the Model Actually Trying to Do?</h3><p>At the core, everything revolves around <strong>minimizing error (loss function)</strong>.</p><p>For regression, we often use: L = (y — F(x))²</p><p>Where:</p><ul><li>y = actual value</li><li>F(x) = predicted value</li></ul><p>So the goal is simple:</p><blockquote><strong><em>Make predicted value as close as possible to actual value</em></strong></blockquote><h3>But How Do We Actually Reduce This Error?</h3><p>Knowing the goal is not enough. The real question is: <strong><em>How does the model </em>move<em> from a wrong prediction to a better one?</em></strong></p><p>This is where boosting introduces a powerful idea — instead of fixing everything at once, it improves <strong>step by step</strong>.</p><h3>Learning Through Mistakes (Residuals)</h3><p>The key idea in boosting: —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*waF1rlILRHv4fmqatNTf3A.png" /></figure><p>This residual is the error — and in mathematical terms, it represents the negative gradient<strong>. </strong>Now instead of directly predicting y, the model asks: <strong><em>“What mistake did I just make?”</em></strong></p><p>And then learns to correct it. So the learning becomes sequential:</p><ul><li>Tree 1 → makes prediction</li><li>Tree 2 → learns residual r1</li><li>Tree 3 → learns residual r2</li><li>… and this continues</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*olFcr80rYXRrSYDnrXP2ZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4TFz0xMZ2OPnNwSyzgSZw.png" /></figure><p>Mathematically, each new model learns the remaining error, ensuring that with every step, the overall prediction becomes more accurate.</p><h4>But What Exactly Are We Learning Here?</h4><p>At first, it may look like boosting is simply learning from errors, but this is where something deeper is happening. This “error” is not just a difference — it is actually the <strong>direction in which the loss function decreases the fastest</strong>.</p><h4>Why Does This Matter?</h4><p>Remember our goal: L = (y — F(x))²</p><p>To reduce this loss, we need to know: <strong><em>How does loss change when prediction changes?</em></strong></p><p>This is exactly what <strong>derivatives</strong> tell us.</p><h3>Connecting Residuals to Gradient</h3><p>Let’s take derivative of loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6Whhz7Jf8TBAewDjkF8ug.png" /></figure><p>→Residual = error<br> →Gradient = scaled version of that error</p><p>Which means:</p><blockquote><strong><em>When XGBoost learns residuals, it is actually performing gradient descent.</em></strong></blockquote><p>But instead of stopping there, XGBoost goes one step further — it also understands how reliable that direction is.</p><h3>What Is Gradient (First Derivative)?</h3><p>Let’s not just say what gradient <em>means</em> — let’s <strong>derive it properly</strong>. We start with the loss function (for regression):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYEOTLGr7V4nUq2gFTVneg.png" /></figure><h3>Step 1: Take First Derivative</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsrxfrCXkFeSXTz4uetVbA.png" /></figure><h3>What Does This Mean?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sG2S_1E-mJrENzdPWDNp8Q.png" /></figure><p>This is called the <strong>gradient</strong>.</p><p>Now interpret it:</p><ul><li>If error is large → gradient is large</li><li>If error is small → gradient is small</li></ul><p>So, <strong><em>Gradient tells us: </em>how wrong we are and in which direction to move to reduce error</strong></p><p>Because we update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJw2QdQecxEPEIk23QZADQ.png" /></figure><p>Gradient = <strong>“how much error to fix”</strong></p><h3>Problem: Gradient Alone Is Not Enough</h3><p>Even after all this math, there’s a limitation. Gradient only gives:</p><ul><li>direction</li><li>magnitude (based on error)</li></ul><p>But it <strong>assumes the loss behaves like a straight line</strong>. Reality: Loss functions are <strong>curved. </strong>Let’s understand this mathematically</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*W9H0k8O_0DAjbZR9Ov5jCA.png" /></figure><p>So using only gradient is like saying:</p><blockquote><em>“I know which direction to go…<br> but I don’t know how sharply the road is turning.”</em></blockquote><p>This leads to:</p><ul><li><strong>Overshooting the minimum</strong> — instead of settling at the lowest point, the model keeps jumping across it</li><li><strong>Slow convergence</strong> — steps are too cautious in flat regions</li><li><strong>Inefficient learning</strong> — updates are not optimized</li></ul><p>To overcome these issues, this is where the second derivative comes in.</p><h3>Second Derivative (Hessian)</h3><p>Now let’s mathematically prove the second derivative.</p><h3>Step 2: Take Second Derivative</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_PsMt8S_dfqbi4Y38GaIw.png" /></figure><h3>What Does This Mean?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e3EHYZooolDGr7RCVMjU_A.png" /></figure><p>This is called the <strong>Hessian (second derivative)</strong>.</p><h3>Interpretation</h3><ul><li>It is <strong>constant and positive</strong></li><li>So loss function is <strong>convex (U-shaped)</strong></li><li>There is a <strong>clear minimum</strong></li></ul><p>More importantly: <strong><em>Hessian tells us how the gradient is changing. </em></strong>In other words, it tells us how trustworthy our direction really is.</p><h3>Why This Changes Everything (XGBoost Insight)</h3><p>Now instead of updating blindly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFwCY52G5P75k4Cks21dbw.png" /></figure><p>XGBoost uses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfxhHNyHufm9aSCAdTNzlw.png" /></figure><p>Where:</p><ul><li>g = gradient</li><li>h = Hessian</li></ul><p>This means:</p><ul><li>Step size is <strong>automatically adjusted</strong></li><li>Learning becomes <strong>smarter, not just faster</strong></li></ul><h3>Intuition Behind XGBoost (Why It Works So Well)</h3><p>At its core, XGBoost doesn’t just focus on reducing error — it focuses on <em>how</em> to reduce it efficiently.</p><ul><li><strong>Gradient</strong> tells us the direction of improvement (the slope)</li><li><strong>Hessian</strong> tells us the curvature of the loss function (how that direction is changing)</li></ul><p>This means the model not only knows <em>where to go</em>, but also <em>how confidently and how far to move</em> in that direction.</p><p>Instead of blindly following the gradient, XGBoost combines both:<br> it uses <strong>gradient + curvature</strong> to make optimal updates at every step.</p><h4><strong>One-Line Takeaway</strong></h4><ul><li>First derivative gives direction.</li><li>Second derivative gives confidence.</li><li>XGBoost uses both to move intelligently.</li></ul><p>In the end, learning in machine learning is not just about moving in the right direction — it’s about moving with awareness.</p><p>Gradient helps us take a step.<br>Hessian helps us take the <em>right</em> step.</p><p>And this is where XGBoost stands apart — not by working harder, but by working smarter.</p><p>If this made the intuition behind XGBoost a little clearer, then the journey from “direction” to “understanding curvature” has already begun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4e3c0f7df2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Can’t Skip Math in Machine Learning — Learn Differentiation + (Solved + Practice)…]]></title>
            <link>https://medium.com/@richa.insights/why-you-cant-skip-math-in-machine-learning-learn-differentiation-solved-practice-628079501536?source=rss-99e3d2ac59ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/628079501536</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Richa Rani]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 17:11:25 GMT</pubDate>
            <atom:updated>2026-04-06T17:13:40.483Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why You Can’t Skip Math in Machine Learning | Differentiation for ML (Examples + Practice)Questions<strong>| ML Series Part 15</strong></h3><p>People enter Machine Learning from different backgrounds.</p><p>Some come with a strong foundation in mathematics. Others come from commerce, arts, or completely non-technical fields — learning concepts step by step along the way.</p><p>But at some point, everyone reaches the same place.</p><p>You start building models, working with data, understanding algorithms…<br>and then you realize that behind every prediction, there is mathematics working silently.</p><p>That’s where questions begin: — <em>“How much math do I really need?”</em><br><em>“Can I learn this without going too deep into formulas?”</em></p><p>I had similar doubts. Instead of ignoring them, I decided to understand things — with the help of <a href="https://medium.com/@prince-insight">my friend <strong>Prince Soni</strong></a>. I focused on basics, asked simple questions, and tried to build intuition instead of memorizing formulas.</p><p>And gradually, things started making sense. Not because the math became easier — but because the approach changed.</p><p>I realized that in Machine Learning, math is not something extra to learn.<br>It’s the foundation that explains <em>why</em> models work the way they do.</p><p>In this blog, I’ll walk you through one of the most important concepts — <strong>Differentiation</strong> — in a way that feels intuitive, practical, and easy to connect with, even if you’re not from a maths background.</p><h3>The Intuition Behind Differentiation</h3><p>Imagine this. There is an <strong>army camp</strong>.</p><p>If an enemy directly reaches the camp, he will be destroyed instantly. So attacking the camp directly is <strong>not possible</strong>.</p><p>Instead, what do enemies do?</p><ul><li>They attack from a <strong>safe distance</strong></li><li>They observe the camp from nearby</li><li>They understand the situation <em>without directly touching it</em></li></ul><p>Similarly, In math there are certain functions where if you directly put a value, you get: 0/0</p><p>Which is <strong>undefined </strong>For example: —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*xuhphWXAxYeXMXD3vTD_ng.png" /></figure><p>Just like the army camp — <strong>you can’t directly reach the point</strong></p><p>So what do we do instead?</p><p>— We go <strong>very close to the value</strong>, but not exactly at it<br> — We observe how the function behaves <em>around that point</em></p><p>And this idea leads to one of the most important concepts in mathematics: — Differentiation is not about jumping to a value. It’s about understanding <strong>how things behave near that value</strong></p><p>And that’s exactly why it becomes so powerful in Machine Learning.</p><h3>From Confusion to Clarity: Solving the Undefined Problem</h3><p>Now that we understand we can’t directly reach the value,<br>let’s see how to actually deal with it.</p><p>Consider the same function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*GSTkjv2MPcrob5qUUVYV1Q.png" /></figure><p>Which is undefined but instead of stopping here, let’s simplify the expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mN3A5hhZd8ZjSbONG5BmFQ.png" /></figure><p>That’s the Turning Point. At first, the function looked <strong>undefined</strong><br>But after simplifying, we got a clear answer: <strong>3</strong></p><ul><li>The problem was never the value</li><li>The problem was <em>how we approached it</em></li></ul><p>And this is exactly where the idea of <strong>Differentiation</strong> begins.</p><p>Instead of directly jumping to a point, we understand what’s happening <strong>around it</strong>.</p><h3>What is Differentiation (In the Simplest Way)</h3><p><strong>Differentiation means rate of change of one variable with respect to another.</strong></p><p>Think like this: — If you slightly change x, how does y respond?</p><p>That’s differentiation.</p><h4>Real Intuition</h4><ul><li>Speed → change in distance over time</li><li>Temperature → change over time</li><li>Stock price → change over time</li></ul><p>In all these cases, we care about <strong>how fast things are changing</strong></p><blockquote>And in Machine Learning?</blockquote><p>We care about <strong>how error is changing</strong></p><h3>Types of Differentiation Rules (The Tools You Actually Use)</h3><p>Now that you understand what differentiation <em>means</em>, the next question is: <em>How do we actually calculate it?</em></p><p>Instead of memorizing random formulas, think of these rules as <strong>tools</strong>.</p><p>Different situations → different tools.</p><h4>1. Power Rule (The Most Basic One)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkqEQBNjuhglj0q9d9dkqw.png" /></figure><p>Simple meaning: You <strong>bring the power in front</strong> and <strong>reduce it by 1</strong></p><h4>Question 1: y=x³</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4yZCcLgIEnzFGUo4A7Vmw.png" /></figure><h4>Question 2: y=x⁵</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xv5hoCHNA8LmKNcscX9yNg.png" /></figure><p><strong>ML Connection: </strong>This rule is used everywhere — especially in loss functions like MSE where powers of variables appear.</p><h3>2. Product Rule (When Two Things Multiply)</h3><p>Sometimes functions are multiplied like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eaPH9xqk4saM7Y6-GpQWVw.jpeg" /></figure><p>Meaning: Differentiate one at a time, then add</p><h4>Question 1: y=x².x³</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*IMc8DGAjMJko0SFElC9VPw.jpeg" /></figure><p><strong>ML Connection: </strong>Product rule appears in <strong>neural networks</strong> when multiple parameters interact.</p><h3>3. Quotient Rule (When One Thing Divides Another)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*28O7pq5489QCXZLYLoFVLw.jpeg" /></figure><h4>Question 1: y=x²/x</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*OMgh_FFHFLdhrDUs2s_pWQ.jpeg" /></figure><p><strong>ML Connection: </strong>Used in optimization problems and probability formulas.</p><h3>4. Chain Rule (Most Important for Machine Learning)</h3><p>This is the <strong>king rule</strong> in ML.</p><p>If a function is inside another function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsWsgiPyAkQl2kqQYVjyJA.jpeg" /></figure><p>Meaning: Differentiate <strong>outer function × inner derivative</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkAfCHziMkA3wJLWT2Narg.jpeg" /></figure><p><strong>ML Connection (VERY IMPORTANT):</strong><br> Chain rule is used in:</p><p>— Backpropagation<br> — Gradient Descent<br> — Neural Networks</p><p>Without chain rule → <strong>Deep Learning doesn’t exist</strong></p><h3>Differentiation Cheat Sheet (Quick Formulas You’ll Actually Use)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIdfKIkSoAAsnLlN8Jxktw.jpeg" /></figure><h3>Let’s Practice</h3><p>Now instead of just reading, let’s build confidence.</p><h4>Question 1: y=x⁴+3x²</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9NyyrpmjZEFsF3UCXinIQ.jpeg" /></figure><h4>Question 2: y=Sin(6x);apply chain rule</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4LB8G3aIY01gxnM77ww9Tg.jpeg" /></figure><h4>Question 3: y=x³/x+1 ; apply Quotient Rule</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*S-2kCgdDWdTdbEDcVXir-A.jpeg" /></figure><h3>Differentiation Practice (Basic → Advanced)</h3><h4>Level 1: Basics (Power Rule)</h4><p><strong>Q1.</strong> y=x³<br><strong>Q2.</strong> y= x⁵ + 2x² <br><strong>Q3.</strong>y=7x⁴−3x+10</p><h4>Level 2: Intermediate (Using Rules)</h4><p>Q4. y=x²⋅x³<br>Q5. y=x²/x+1 <br>Q6.y=Sin(x)</p><h4>Level 3: Conceptual</h4><p>Q7. y=(x²+1)³ <br>Q8. y=x²sin(x)</p><h4>Level 4: Advanced (ML-Oriented Thinking)</h4><p>Q9. L=(y−y)² <br>Q10. f(x)=x²+4x</p><blockquote>Don’t just read — solve these questions yourself.<br>That’s where real learning happens.<br>Stuck somewhere? Comment your doubt — let’s figure it out together.</blockquote><h3>Why Differentiation is the Backbone of Machine Learning</h3><p>Now connect everything: In Machine Learning, we try to <strong>minimize error</strong>.</p><p>We ask:</p><ul><li>If I change weight slightly, how does error change?</li><li>Which direction reduces error fastest?</li></ul><p>That’s differentiation.</p><p>And the method used?</p><p><strong>Gradient Descent</strong></p><ul><li>Uses derivatives to find slope</li><li>Moves in direction of minimum error</li></ul><blockquote><em>Suppose your model predicted 80 but actual value is 100<br> Error = (100–80)²<br> Now we use differentiation to see:<br> If we change the model slightly, does error increase or decrease?</em></blockquote><p>This is EXACTLY how Gradient Descent works.</p><p>At first, differentiation feels like a complicated formula game.<br>But as you go deeper, you realize — it’s not about formulas at all.</p><p>It’s about understanding how things change. And Machine Learning is built entirely on that idea. Once this clicks, math stops feeling scary — and starts becoming your biggest strength.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=628079501536" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Random Forest Is So Popular Among Data Scientists (With Python Examples) | Machine Learning…]]></title>
            <link>https://medium.com/@richa.insights/why-random-forest-is-so-popular-among-data-scientists-with-python-examples-machine-learning-75d56f3b707a?source=rss-99e3d2ac59ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/75d56f3b707a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Richa Rani]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 13:46:18 GMT</pubDate>
            <atom:updated>2026-03-14T13:46:18.380Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Random Forest Is So Popular Among Data Scientists (With Python Examples) | Machine Learning Series Part 15</h3><p>Random Forest is one of the most powerful and widely used machine learning algorithms. In this article, we will understand how it works and implement it using Python with practical examples.</p><p>Almost every student faces an important decision at some point in their life.</p><p>After the <strong>10th board exam</strong>, many students struggle to decide which stream they should choose — Science, Commerce, or Arts. Later, after the <strong>12th grade</strong>, another big question appears:</p><p><strong>Which career path should I follow?</strong></p><p>Engineering? Medicine? Data Science? Business?</p><p>Making such decisions based on <strong>just one person’s opinion</strong> can sometimes lead to mistakes. That is why students often consult <strong>multiple teachers, parents, career counselors, and mentors</strong> before making a final choice.</p><p>By gathering multiple opinions, the chances of making a <strong>better and more informed decision increase</strong>.</p><p>Interestingly, one of the most powerful algorithms in machine learning follows a very similar idea of combining multiple opinions before making a decision.</p><p>That algorithm is called <strong>Random Forest</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-n6GifmNI-cGWC--Pk4dw.png" /><figcaption><em>Diagram explaining the Random Forest algorithm using multiple opinions to predict a student’s career path.</em></figcaption></figure><h3>What is Random Forest?</h3><p><strong>Random Forest</strong> is a <strong>supervised machine learning algorithm</strong> that belongs to the category of <a href="https://medium.com/@richa.insights/most-powerful-technique-in-data-science-ensemble-learning-in-machine-learning-voting-bagging-2787dd263f0b"><strong>ensemble learning techniques</strong>.</a></p><p>The main idea behind Random Forest is simple:</p><p>Instead of relying on a <strong>single decision tree</strong>, the algorithm creates <strong>multiple decision trees</strong> and combines their predictions to generate the final result.</p><p>Each tree in the forest learns from <strong>different subsets of the dataset</strong>, which helps the model capture various patterns in the data.</p><p>The final prediction is made by combining the results of all trees.</p><ul><li>For regression problems → <strong>Average prediction</strong></li><li>For classification problems → <strong>Majority voting</strong></li></ul><p>This ensemble approach improves the model’s <strong>accuracy, stability, and generalization ability</strong>.</p><h3>Types of Random Forest Models</h3><p>Random Forest can solve <strong>two major types of machine learning problems</strong>.</p><h3>1. RandomForest Regressor</h3><p>RandomForest Regressor is used when the target variable is <strong>continuous or numerical</strong>.</p><p>For example —</p><ul><li>Predicting house prices</li><li>Forecasting sales</li><li>Predicting temperature</li><li>Estimating revenue</li></ul><p>In regression problems, Random Forest calculates the <strong>average prediction from all decision trees</strong>.</p><h3>2. RandomForest Classifier</h3><p>RandomForest Classifier is used when the target variable is <strong>categorical</strong>.</p><p>For example —</p><ul><li>Spam email detection</li><li>Disease classification</li><li>Customer churn prediction</li><li>Loan approval prediction</li></ul><p>In classification problems, Random Forest uses <strong>majority voting</strong> to determine the final output.</p><h3>How Random Forest Works</h3><p>To understand Random Forest more clearly, imagine asking <strong>multiple experts</strong> to solve a problem instead of relying on just one expert.</p><p>For example, consider a scenario where we want to predict the price of a house.</p><p>Each decision tree provides its prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2q4tEzTzr5T39w0Imh6zfg.png" /><figcaption>able showing predictions from multiple decision trees used in a Random Forest regression model.</figcaption></figure><p>The RandomForest Regressor combines these predictions and calculates the <strong>average value</strong>.</p><p>Final Prediction → <strong>$203,250</strong></p><p>For classification problems, the algorithm works differently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kBf5R3DYOwplJTCDhAwLw.png" /><figcaption>able showing predictions from multiple decision trees used in a Random Forest classification model.</figcaption></figure><p>Final Prediction → <strong>Spam (majority vote)</strong></p><p>This collective decision-making process makes Random Forest <strong>more reliable and accurate</strong> than a single decision tree.</p><h3>Practical Example: RandomForest Regressor</h3><p>Let us connect our earlier example.</p><p>Students often consult multiple people before deciding their career path. Similarly, in machine learning we can use different factors such as a student’s <strong>interest level and academic strengths</strong> to estimate how suitable a particular career path might be.</p><p>Suppose we collect the following data about students:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K5K6NxzzNLIS3zI2BBPt9A.png" /><figcaption>Pandas DataFrame showing a student dataset used for a Random Forest regression example.</figcaption></figure><p>Here:</p><ul><li>Input features → students’ abilities and interests</li><li>Target variable → <strong>career suitability score (continuous value)</strong></li></ul><p>Since the target variable is numerical, we can apply <strong>RandomForest Regressor</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCW_wx-ooL_rEt5s_QRaqA.png" /><figcaption><em>Python code implementing a RandomForest Regressor using scikit-learn to predict career suitability score.</em></figcaption></figure><p>In this example, the model predicts how suitable a career path might be for a student based on their <strong>skills and interests</strong>.</p><h3>Practical Example: RandomForest Classifier</h3><p>Now let us convert the same idea into a <strong>classification problem</strong>.</p><p>Instead of predicting a numerical score, we will predict the <strong>recommended career path</strong>.</p><p>Here’s the Sample Dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m77g4b0CpZq6d6oXEwZD3g.png" /><figcaption>Pandas DataFrame showing a student dataset used for a Random Forest classification example.</figcaption></figure><p>From the dataset above, we can see that the <strong>career path is a categorical variable</strong> (Engineering, Medicine, Business). Machine learning models cannot directly work with text labels, so we need to convert these categories into numerical values before training the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5WXtV71zKM0TN35zpKprA.png" /><figcaption>Using LabelEncoder in Python to convert career categories into numerical values.</figcaption></figure><p>Using LabelEncoder, the career categories are transformed into numerical labels so that the RandomForest Classifier can process them during training. Once the dataset is prepared and the target variable is encoded, we train the RandomForest Classifier to learn patterns between students’ skills and the most suitable career path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IuVDI0ZDnGImCiIEmNbLVw.png" /><figcaption><em>Python code implementing a RandomForest Classification using scikit-learn to predict career .</em></figcaption></figure><p>Here the model predicts the most suitable career path based on the student’s abilities.</p><blockquote>But why do data scientists trust Random Forest so much in real-world projects?</blockquote><h4>Why Random Forest Is So Popular Among Data Scientists</h4><p>There are several reasons why Random Forest is widely used in machine learning.</p><h4>1. High Accuracy</h4><p>Combining multiple decision trees helps the model capture different patterns in the data, improving prediction accuracy.</p><h4>2. Reduces Overfitting</h4><p>Unlike a single decision tree, Random Forest generalizes better.</p><h4>3. Works With Large Datasets</h4><p>Random Forest performs well even with thousands of features.</p><h4>4. Flexible Algorithm</h4><p>It can solve both <strong>regression and classification problems</strong>.</p><h4>5. Robust to Noise</h4><p>The model performs well even with messy or incomplete data.</p><p>Just like students often seek multiple opinions before choosing a career path, Random Forest combines predictions from multiple decision trees to make more reliable decisions.</p><p>In this article, we explored how Random Forest works, the difference between RandomForest Regressor and RandomForest Classifier, and how to implement them using Python.</p><p>This article is part of my <strong>Machine Learning Series</strong> where I explain important algorithms with practical Python examples and real-world analogies.</p><p>If you found this article helpful, consider <strong>clapping and sharing it with others who are learning Machine Learning.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75d56f3b707a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Most Powerful Technique in Data Science: Ensemble Learning in Machine Learning: Voting, Bagging…]]></title>
            <link>https://medium.com/@richa.insights/most-powerful-technique-in-data-science-ensemble-learning-in-machine-learning-voting-bagging-2787dd263f0b?source=rss-99e3d2ac59ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/2787dd263f0b</guid>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Richa Rani]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 13:57:14 GMT</pubDate>
            <atom:updated>2026-03-14T13:09:43.294Z</atom:updated>
            <content:encoded><![CDATA[<h3>Most Powerful Technique in Data Science: Ensemble Learning in Machine Learning: Voting, Bagging, Boosting &amp; Stacking Explained with Python | Machine Learning Series Part 14</h3><p>If you ask an experienced data scientist what technique they rely on most in real-world machine learning projects, many will say <strong>Ensemble Learning</strong>.</p><p>Not because it’s trendy.<br>Not because it sounds complicated.</p><p>But because, in practice, combining multiple models almost always performs better than relying on a single one.</p><p>And that’s where its real power comes from.</p><p>From<strong> Kaggle competitions</strong> to production-level <strong>AI systems</strong>, <strong>ensemble methods</strong> like<strong> Random Forest, Gradient Boosting, and Voting classifiers</strong> dominate real-world applications.</p><p>But why are ensemble models so powerful?</p><p>Let’s understand this with a simple real-world example.</p><h4>Hiring Decisions:</h4><p>Imagine you’re part of a hiring team at a tech company.</p><p>A candidate walks out of the interview room.</p><p>Now the decision begins.</p><ul><li>The technical interviewer says: “Strong coding skills.”</li><li>HR says: “Excellent communication.”</li><li>The manager adds: “Good potential, but needs mentoring.”</li></ul><p>If only one person made the decision, it might be biased or incomplete. But when all opinions are combined, the final decision becomes more balanced, thoughtful, and reliable.</p><p>This is exactly how Ensemble Learning works.</p><p>Instead of depending on a single machine learning model, we combine multiple models so their strengths complement each other and their weaknesses cancel out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R0IOCsfGe4sIowgmvOIGdg.png" /><figcaption>Ensemble learning infographic using hiring interview analogy to explain how multiple models combine predictions into a final decision in machine learning.</figcaption></figure><p>Now let’s turn this hiring scenario into a structured dataset — just like a real data science problem.</p><h3>Dataset Creation in Python</h3><p>A sample hiring dataset with candidate details like experience, test score, communication score, and projects.</p><p>Then, we separate the input features (X) and assign the target variable (y) as the “Selected” column for model training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHjX4omsLhCO6XOeiT1_GQ.png" /><figcaption>Jupyter Notebook displaying Pandas DataFrame for machine learning candidate selection dataset.</figcaption></figure><p>Now, we have structured our hiring panel into data, let’s explore ensemble learning.</p><h3>What is Ensemble Learning in Machine Learning?</h3><p><strong>Ensemble Learning</strong> is a machine learning technique that combines multiple base models to create a stronger and more accurate predictive model.</p><p>Rather than trusting a single algorithm, ensemble models aggregate predictions to:</p><ul><li>Reduce variance</li><li>Reduce bias</li><li>Improve accuracy</li><li>Increase robustness</li></ul><p>Now let’s connect our hiring dataset with types of ensemble methods.</p><h3>Types of Ensemble Techniques in Machine Learning</h3><p>Now, we understand the hiring panel analogy, let’s connect it to the major ensemble methods used in real-world machine learning.</p><p>There are four primary types of ensemble techniques:</p><ul><li><strong>Voting</strong></li><li><strong>Bagging (Bootstrap Aggregating)</strong></li><li><strong>Boosting</strong></li><li><strong>Stacking</strong></li></ul><p>Each method combines multiple models differently to improve predictive performance, reduce overfitting, and increase robustness.</p><h3>1. Voting Ensemble (Simple Ensemble Method)</h3><p>Voting is one of the most straightforward ensemble techniques. It combines predictions from multiple different models and selects the final output based on a collective decision.</p><h4>a) Hard Voting (Classification Task).</h4><p>Hard Voting is used in classification problems where multiple models predict class labels (such as 0/1 or Yes/No). Each model casts one vote, and the class receiving the majority of votes becomes the final prediction.</p><p>Now that we understand the theory behind Hard Voting, let’s implement it step by step using Python and scikit-learn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qANTltK_YGkPAOGjixw1fg.png" /><figcaption>Jupyter Notebook showing train_test_split and StandardScaler usage in scikit-learn for machine learning data preprocessing.</figcaption></figure><h4>Democracy Principle in Hard Voting</h4><p>Hard Voting follows the principle of democratic majority decision-making:</p><ul><li>It is used in binary and multi-class classification problems.</li><li>Each model predicts a class label.</li><li>Each model gets one vote.</li><li>The class with the highest vote count wins.</li></ul><p>Just like in a democratic election, every voter (model) has equal power. Even if some models make incorrect predictions, the majority decision balances individual errors.</p><p><strong>Example:</strong><br> If 5 models predict:</p><ul><li>3 say “Selected”</li><li>2 say “Not Selected”</li></ul><p>Final Prediction → <strong>Selected (majority wins)</strong></p><p>In our hiring example:</p><ul><li>Decision Tree → Selected</li><li>Logistic Regression → Selected</li><li>KNN → Not Selected</li></ul><p>Two out of three vote “Selected,” so the final decision becomes Selected.<br> That’s voting in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JhMxM0-aSvieX-POU1jkA.png" /><figcaption>Jupyter Notebook showing VotingClassifier implementation with Logistic Regression, Decision Tree, and KNN models achieving 100% hard voting accuracy in scikit-learn.</figcaption></figure><h4>b) Soft Voting (Classification Task)</h4><p>Soft Voting is also used in classification, but instead of relying on predicted class labels, it uses predicted probabilities from each model. The probabilities are averaged, and the class with the highest average probability is selected. Because it considers model confidence levels, Soft Voting often performs better than Hard Voting.</p><p>Let’s now implement Soft Voting in Python and observe how probability averaging works in practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Pw6-iO1DZPry7-XzNGkAg.png" /><figcaption>Jupyter Notebook showing soft voting ensemble using VotingClassifier in scikit-learn with 100% accuracy result.</figcaption></figure><h4>c) Voting Regressor (Regression Task)</h4><p>Voting Regressor is used for regression problems where models predict continuous numerical values (such as price, salary, or score). The final prediction is computed by averaging the numerical outputs of all models. Since regression outputs are continuous rather than categorical, majority voting does not apply.</p><p>In practice, we implement voting using <strong>VotingClassifier</strong> from scikit-learn.</p><p>Let’s apply Voting Regressor to our dataset and observe how averaging improves prediction stability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STk0d8i8WSNnewjF9MBdLA.png" /><figcaption>Scikit-learn Python code in a Jupyter Notebook implementing a VotingRegressor with Linear Regression, Decision Tree, and K-Neighbors base models to calculate Mean Squared Error.</figcaption></figure><p>Voting works especially well when different models capture different patterns in the data.</p><h3>2. Bagging (Bootstrap Aggregating)</h3><p>Bagging is an ensemble technique that reduces variance and improves model stability by training multiple models on different random subsets of the dataset (created using bootstrap sampling). Each model learns independently, and their predictions are combined to produce a more robust final result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nkrozcpy3a6sxwb_Eh_FOA.png" /></figure><p>The most popular bagging algorithm is <strong>Random Forest</strong>. It’s a powerful ensemble algorithm based on the Bagging technique.</p><p>It builds multiple decision trees using:</p><ul><li>Different bootstrap samples of the dataset</li><li>Random subsets of features</li></ul><p>Each tree makes its own prediction, and the final output is determined by:</p><ul><li>Majority vote (for classification)</li><li>Average prediction (for regression)</li></ul><p>Because it combines many trees instead of relying on one, Random Forest significantly <strong>reduces overfitting</strong> and<strong> improves model stability.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfJnlg54Zxt39BywNlTRWg.png" /></figure><p>Now, we understand the concept, let’s apply Random Forest to our hiring dataset and see Bagging in action using Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kys0mU3fNh9P415jUpSCuQ.png" /></figure><p>In our hiring example: — It’s like forming multiple independent interview panels, each reviewing a different random group of candidates. Instead of relying on just one panel’s opinion, we take a majority vote across all panels to make a fair and more accurate hiring decision.</p><h3>3. Boosting</h3><p>Boosting works differently. Instead of training models independently, it trains them sequentially — where each new model focuses on correcting the previous model’s mistakes.</p><p>Popular boosting algorithms include:</p><ul><li><strong>AdaBoost</strong></li><li><strong>Gradient Boosting</strong></li><li><strong>XGBoost</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XXn8mIZIscp8-O1WZq198w.png" /></figure><p>In our hiring scenario: — Boosting is like improving hiring decisions by learning from past mistakes and adjusting their evaluation criteria to avoid repeating them.</p><p>That’s boosting — learning from previous errors to improve future decisions.</p><blockquote><strong>This is why boosting models dominate data science competitions and real-world machine learning systems.</strong></blockquote><p>Now let’s apply a boosting algorithm to our hiring dataset and observe how sequential learning improves prediction performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyVDrLhhg6GAweLVIwWZ5w.png" /><figcaption>This model builds trees sequentially, where each new tree tries to correct the errors made by the previous ones.</figcaption></figure><p>This mirrors our hiring example — the team analyzes past hiring mistakes and refines their evaluation strategy step by step to improve future decisions.</p><h3>3. Stacking</h3><p>Stacking combines different types of models and uses another model (called a meta-learner) to make the final prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlHsf_hLDlHUmzBojoWchg.png" /></figure><p>In the hiring example: It’s like combining the technical interviewer, HR, and manager’s recommendations — and then having a senior decision-maker analyze all their inputs before making the final call.</p><p>Now let’s implement Stacking on our hiring dataset and see how multiple models can be combined using a meta-learner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGen3B04iIq3J_gPQm9iNA.png" /></figure><p>Stacking often achieves state-of-the-art performance because it blends different modeling perspectives.</p><h3>Voting vs Bagging vs Boosting vs Stacking: Key Differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BoadIcP-T288K_BO7PeoQQ.png" /></figure><h3>Why Ensemble Learning is So Powerful in Data Science</h3><p>In real-world ML where<strong> data is noisy</strong> and <strong>complex</strong>, ensemble models <strong>improve stability</strong> and <strong>generalization by balancing bias and variance</strong>.</p><p>That’s why ensemble techniques in data science are widely used in: — <strong>Fraud detection, Credit risk modeling, Customer churn prediction, Recommendation systems, Hiring and HR analytics</strong></p><p>Most production-level machine learning systems rely on ensemble methods for reliable performance.</p><p>Ensemble learning helps you build smarter and more reliable machine learning models by combining multiple approaches instead of depending on just one. It’s a key skill that separates beginner projects from real-world ML systems.</p><p>If you loved this blog, clap and share it with someone who’s learning machine learning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2787dd263f0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decision Tree in Machine Learning Explained with Gini Index, Entropy and Python Code]]></title>
            <link>https://medium.com/@richa.insights/decision-tree-in-machine-learning-explained-with-gini-index-entropy-and-python-code-060015094456?source=rss-99e3d2ac59ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/060015094456</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Richa Rani]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 10:04:10 GMT</pubDate>
            <atom:updated>2026-03-14T13:07:58.674Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decision Tree in Machine Learning Explained with Gini Index, Entropy and Python Code | Machine Learning Series Part 13</h3><p>Have you ever played <a href="https://play.google.com/store/apps/details?id=com.digidust.elokence.akinator.freemium&amp;pcampaignid=web_share">Akinator</a>?</p><p>That game where a cartoon genie asks you a series of questions and somehow guesses the character you’re thinking about?</p><p>Is your character real?<br>Is your character female?<br>Is your character from a movie?<br>Is your character animated?</p><p>With every answer, the possibilities shrink.<br>It feels magical.<br>But behind that magic is logic.</p><p>Akinator works by eliminating uncertainty step by step — asking the most informative question each time.</p><p>And that’s exactly how a <strong>Decision Tree algorithm</strong> works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAoeWuqHJvOAHWTtF_9sVg.png" /><figcaption>Illustration of a genie like Akinator above a branching decision tree diagram asking yes/no questions, representing the Decision Tree algorithm in machine learning.</figcaption></figure><h3>What is a Decision Tree Algorithm?</h3><p>A <strong>Decision Tree</strong> is a supervised machine learning algorithm used for:</p><ul><li>Classification (Spam / Not Spam, Disease / No Disease)</li><li>Regression (Predicting numerical values like price)</li></ul><p>It works like a flowchart of questions.</p><ul><li><strong>Root Node</strong> → First question</li><li><strong>Internal Nodes</strong> → Follow-up questions</li><li><strong>Branches</strong> → Outcomes (Yes/No or other splits)</li><li><strong>Leaf Nodes</strong> → Final prediction</li></ul><p>In simple words:</p><blockquote><em>A Decision Tree learns by asking the most useful question at each step to reduce confusion.</em></blockquote><p>Just like Akinator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCXeq_9ErcE3Rp7_lYO1_g.png" /><figcaption>Infographic explaining the Decision Tree algorithm with root node, internal nodes, branches, and leaf nodes for classification and regression, illustrated using an Akinator-style genie example.</figcaption></figure><h3>Types of Decision Tree Algorithms</h3><p>There are different Decision Tree approaches:</p><h4>1. ID3 (Iterative Dichotomiser 3)</h4><ul><li>Uses <strong>Entropy</strong></li><li>Uses <strong>Information Gain</strong></li><li>Works mainly with categorical data</li><li>ID3 typically produces a multiway tree, meaning a feature can split into more than two branches.</li></ul><h4>2. C4.5</h4><ul><li>Improved version of ID3</li><li>Uses <strong>Gain Ratio</strong></li><li>Handles continuous values</li><li>C4.5 can produce both multiway and binary splits, depending on the feature.</li></ul><h4>3. CART (Classification and Regression Trees)</h4><ul><li>Can perform classification and regression</li><li>For classification — splitting will be on the basis of Gini Index</li><li>For Regression — splitting on the basis of MSE (Mean Square Error)</li><li>CART always produces a binary tree</li><li>CART does not use Entropy; instead, it relies on the Gini Index for classification tasks.</li></ul><blockquote>But how does a Decision Tree decide which question to ask first?<br>The answer lies in something called <strong>impurity measures</strong>.</blockquote><h3>Measures of Impurity</h3><p>Just like in <strong>Akinator</strong>, the goal is to ask the question, that’s reduces uncertainty the most. In machine learning, this “uncertainty” is called <strong>impurity</strong>.</p><p>Impurity simply means: — How mixed are the classes in a dataset?</p><p>If a group contains 50% Spam and 50% Not Spam, it is highly impure.<br>If a group contains 100% Spam, it is completely pure.</p><p>The first step in building a decision tree is selecting the best feature to split the data. This selection is based on mathematical measures like Gini Index, Entropy, or Information Gain.</p><p>To measure this impurity mathematically, different algorithms use different metrics.</p><h4>1. Gini Index (GI)</h4><p>— Used in the CART algorithm.<br> — It measures how often a randomly chosen element would be incorrectly classified.<br> — Lower Gini value → Higher purity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgvqU9gsWS65O-7jCwVpIA.png" /><figcaption>Image showing the Gini Index formula for decision trees: Gini = 1 − Σ(pi²), where pi represents class probabilities.</figcaption></figure><p>The Gini Index is calculated using class probabilities within a node. It measures how likely a randomly selected sample would be misclassified if it were randomly labeled.</p><h3>2. Entropy (Used in ID3)</h3><p>— Used in the ID3 algorithm.<br> — Entropy measures randomness or disorder in the data.<br> — Higher entropy → More uncertainty.<br> — Lower entropy → More clarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I96kvjZpr9T5DUd0iZHEPw.png" /><figcaption>Image displaying the Entropy formula for decision trees</figcaption></figure><h3>3. Information Gain</h3><p>— Information Gain is derived from Entropy.<br> — It tells us how much uncertainty is reduced after splitting on a feature.<br> — The feature that gives the highest Information Gain is selected for the split.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBcwQFwJAqEK7BrNW6MHyQ.png" /><figcaption>Image displaying the Information Gain formula for decision trees</figcaption></figure><p>So instead of randomly choosing a question, a Decision Tree uses these mathematical measures to pick the most informative split at each step.</p><p>And just like Akinator asking the smartest next question, the tree keeps reducing uncertainty — step by step — until the predictions become clear.</p><h3>Small Dataset (Inspired by Akinator)</h3><p>Let’s imagine a mini version of Akinator.</p><p>Goal: Predict whether the character is a <strong>Superhero</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBmcv8LDz3MOg410uhxRHA.png" /><figcaption>Screenshot of a Jupyter Notebook showing Python code creating a pandas DataFrame with fictional superhero features and displaying the resulting table.</figcaption></figure><p>Since our dataset contains categorical features, we first convert them into numerical values using encoding techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHveAQJ6noAH5Xn66ewuAA.png" /><figcaption>The image shows a <strong>Jupyter Notebook</strong> with a Python code that performs <strong>label encoding</strong> using sklearn.</figcaption></figure><p>Once the data is prepared, we train the Decision Tree model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGlsEAvxufJ2XUqB4yjhIQ.png" /><figcaption>Jupyter Notebook showing Python code to train a DecisionTreeClassifier using sklearn with Gini criterion.</figcaption></figure><p>The algorithm automatically finds the best feature to split the data, creating branches step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*um-xMQIAnF9Q8RVq59JKsA.png" /><figcaption>Jupyter Notebook displaying a scikit-learn decision tree plot using the Gini index with HasPowers and Fictional features.</figcaption></figure><p>When visualized, the tree clearly shows how each question leads to the final prediction.</p><p>What started as raw data transforms into a structured decision-making process — just like the logical path Akinator follows to guess your character.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPDkDlAN70YYa0bYFzIRkA.png" /><figcaption>Jupyter Notebook showing decision tree prediction</figcaption></figure><h3>Why Decision Trees Matter</h3><p>Decision Trees are popular because they are:</p><ul><li>Easy to understand and visualize</li><li>Highly interpretable</li><li>Capable of working without feature scaling</li><li>The foundation behind powerful ensemble methods like <strong>Random Forest</strong> and<strong> Gradient Boosting</strong></li></ul><p>Decision Trees are not just algorithms. They are structured thinking.</p><p>From Akinator guessing your character to a model predicting customer churn — the logic is the same:</p><p>— Ask the smartest question.<br> — Reduce uncertainty.<br> — Repeat.</p><p>And step by step, clarity emerges.</p><p>If you enjoyed this blog and found it helpful, don’t forget to clap and share it with someone who’s learning Machine Learning.</p><p>And this is just the beginning… <br>In the next blog, we’ll take this idea further and see how multiple trees come together to form something even more powerful — <strong>Random Forest</strong>.</p><p>Until then, keep learning, keep building — and I’ll see you in the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=060015094456" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression for Beginners: Intuition, Graphs, and Python Code]]></title>
            <link>https://medium.com/@richa.insights/linear-regression-for-beginners-intuition-graphs-and-python-code-bc0d376cd0f3?source=rss-99e3d2ac59ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc0d376cd0f3</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[economics]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Richa Rani]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 09:44:34 GMT</pubDate>
            <atom:updated>2026-03-14T13:07:05.800Z</atom:updated>
            <content:encoded><![CDATA[<h3>Linear Regression for Beginners: Intuition, Graphs, and Python Code | Machine Learning Series Part 12</h3><p>Until now in this Machine Learning series, we’ve focused on building intuition — understanding what Machine Learning is, why it matters, and how data, features, and evaluation shape a model’s learning. We explored the language of ML and the logic behind training and performance.</p><p>But sooner or later, one question naturally arises: <strong>how does a machine actually make decisions?</strong></p><p>That question leads us to Machine Learning algorithms. Let’s deep dive into the first one.</p><p>I still remember my intermediate economics class and the Law of Demand: price down, demand up; price up, demand down. The idea was simple, but what stayed with me wasn’t the definition — it was the diagram. Price on one axis, quantity on the other, and a straight line sloping downward that explained the relationship at a glance.</p><p>While learning Machine Learning, I paused at a familiar sight — the same straight line, now in a completely different context. Different data, different problems, but the same idea: understanding how one variable changes with another. That classroom graph had returned with a new name and a much bigger role to play.</p><p>And that line is called <strong>Linear Regression</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiuVb5EdbE1ROPUZVk3Rlw.png" /><figcaption>Comparison of Law of Demand graph and Linear Regression best-fit line showing relationships between variables.</figcaption></figure><h3>What Is Really Happening Behind That Line?</h3><p>At its core, Linear Regression is not trying to predict perfectly or think like a human. It is simply trying to understand the <strong>direction and strength of a relationship</strong> between variables.</p><p>Given a set of data points, it asks a basic question:<br><em>Can a straight line explain this relationship reasonably well?</em></p><p>This idea — capturing <strong>trends rather than exact values</strong> — is what makes Linear Regression both simple and powerful. The model doesn’t care about being right every single time. It cares about being <em>consistently reasonable</em>.</p><h4>So what exactly is Linear Regression, and what does <em>linear</em> really mean here?</h4><blockquote><strong>Linear Regression is a Machine Learning algorithm</strong> used to model the <strong>relationship between an input variable and an output variable by fitting a straight line through the data. The word <em>linear</em> simply means that the relationship is assumed to change at a constant rate — when the input increases or decreases by a certain amount, the output responds proportionally. In other words, the model is not looking for curves, jumps, or complex patterns, but for a steady, predictable trend that can be explained with a straight line.</strong></blockquote><p>Imagine we collect data from a group of students. For each student, we note two things: — The number of hours they studied and the marks they scored in an exam and create a dataset as shown in the image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpH2clIf9Cgwm5vfN3Cy5Q.png" /><figcaption>Pandas DataFrame showing hours studied and corresponding marks used for a Linear Regression example.</figcaption></figure><p>When we plot this data, a familiar pattern often appears. As study hours increase, marks tend to increase as well. Not perfectly, not for every student — but on average, there is a clear upward trend.</p><p>So before applying Linear Regression, let’s plot the raw data and see what the pattern tells us.</p><pre>import matplotlib.pyplot as plt<br>fig, ax = plt.subplots(figsize=(12, 5),dpi=150)<br># Dark background<br>fig.patch.set_facecolor(&quot;#2b3440&quot;)   # lighter outer background<br>ax.set_facecolor(&quot;#020617&quot;)          # inner (almost black)<br># Line plot (single color)<br>ax.plot(df[&quot;Hours_Studied&quot;],df[&quot;Marks&quot;],linewidth=2,alpha=0.6)<br># Scatter with viridis colormap<br>scatter = ax.scatter(df[&quot;Hours_Studied&quot;],df[&quot;Marks&quot;],c=df[&quot;Marks&quot;])<br># Labels &amp; title<br>ax.set_title(&quot;Study Hours vs Marks (Before Learning)&quot;,color=&quot;white&quot;,fontsize=13,pad=10)<br>ax.set_xlabel(&quot;Hours Studied&quot;, color=&quot;white&quot;)<br>ax.set_ylabel(&quot;Marks Scored&quot;, color=&quot;white&quot;)<br>ax.annotate(&quot;Upward trend appears here&quot;,xy=(6, 70),xytext=(3, 80),arrowprops=dict(arrowstyle=&quot;-&gt;&quot;, alpha=0.6,color=&quot;white&quot;),color=&quot;white&quot;)<br># Ticks &amp; grid<br>ax.tick_params(colors=&quot;white&quot;)<br>ax.grid(True, linestyle=&quot;--&quot;, alpha=0.25)<br># Colorbar<br>cbar = plt.colorbar(scatter, ax=ax)<br>cbar.set_label(&quot;Marks Intensity&quot;, color=&quot;white&quot;)<br>cbar.ax.yaxis.set_tick_params(color=&quot;white&quot;)<br>plt.setp(cbar.ax.get_yticklabels(), color=&quot;white&quot;)<br>ax.legend([&quot;Regression Line&quot;, &quot;Actual Data&quot;], facecolor=&quot;#020617&quot;, labelcolor=&quot;white&quot;)<br>plt.show()</pre><p>The plot below shows the raw relationship between study hours and marks — before any algorithm is applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XiYEwCYNeRxoz2NlCxcg1w.png" /><figcaption>Scatter plot of study hours vs marks showing an upward trend before applying Linear Regression.</figcaption></figure><p>Now that we’ve seen a visible upward trend, we let the algorithm formalize it by fitting a Linear Regression model.</p><pre><br>from sklearn.linear_model import LinearRegression<br><br>X=df[[&quot;Hours_Studied&quot;]]<br>y=df[[&quot;Marks&quot;]]<br><br>model=LinearRegression()<br>model<br><br>model_fit=model.fit(X,y)<br>model_fit<br><br>df[&quot;Predicted_Marks&quot;]=model_fit.predict(X)<br>df[&quot;Predicted_Marks&quot;]<br><br>import matplotlib.pyplot as plt<br>fig, ax = plt.subplots(figsize=(12, 5))<br># Dark background<br>fig.patch.set_facecolor(&quot;#2b3440&quot;)   # lighter outer background<br>ax.set_facecolor(&quot;#020617&quot;)          # inner (almost black)<br># Line plot <br>ax.plot(df[&quot;Hours_Studied&quot;],df[&quot;Predicted_Marks&quot;],linewidth=2,alpha=0.6)<br># Scatter with viridis colormap<br>scatter = ax.scatter(df[&quot;Hours_Studied&quot;],df[&quot;Marks&quot;],c=df[&quot;Marks&quot;])<br># Labels &amp; title<br>ax.set_title(&quot;Linear Regression: Hours Studied vs Marks&quot;,color=&quot;white&quot;,fontsize=13,pad=10)<br>ax.set_xlabel(&quot;Hours Studied&quot;, color=&quot;white&quot;)<br>ax.set_ylabel(&quot;Marks Scored&quot;, color=&quot;white&quot;)<br># Ticks &amp; grid<br>ax.tick_params(colors=&quot;white&quot;)<br>ax.grid(True, linestyle=&quot;--&quot;, alpha=0.25)<br># Colorbar<br>cbar = plt.colorbar(scatter, ax=ax)<br>cbar.set_label(&quot;Marks Intensity&quot;, color=&quot;white&quot;)<br>cbar.ax.yaxis.set_tick_params(color=&quot;white&quot;)<br>plt.setp(cbar.ax.get_yticklabels(), color=&quot;white&quot;)<br>plt.show()<br>plt.show()</pre><p>After applying Linear Regression, the model captures this trend using a straight line. That line becomes a simple rule the model learns: given study hours, estimate expected marks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHAuyrG4h734c6lXBFnGgw.png" /><figcaption>Linear Regression plot showing best-fit line and actual data for hours studied versus marks.</figcaption></figure><p>This line doesn’t appear magically. Linear Regression keeps adjusting its position and slope to reduce the gap between predicted and actual marks.<br> If the line is too flat or too steep, the error increases — so the model searches for a balanced fit that stays close to most points.</p><h3>Tuning Effect in Linear Regression</h3><p>In Linear Regression, learning comes down to just <strong>two numbers</strong>: the slope(m) and the starting point of the line (c).</p><p>We describe this relationship using a simple equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*37dsaGk1aObqDx-Kd2qhGA.png" /><figcaption>Linear Regression equation y = mx + c representing slope and intercept.</figcaption></figure><p>If this looks familiar, it’s because it comes straight from basic algebra.</p><p>Here’s what it means in our example:</p><ul><li><strong>x</strong> → input feature (hours studied)</li><li><strong>y</strong> → output we want to predict (marks scored)</li><li><strong>m</strong> → slope of the line — how much marks change for each extra hour studied</li><li><strong>c</strong> → intercept — the expected marks when study hours are zero</li></ul><p>So for our data, the model learns a rule like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*bqu4RlN3zlp74ROo045P3A.png" /><figcaption>Linear Regression formula showing marks predicted from hours studied using slope and intercept.</figcaption></figure><p>The entire learning process of Linear Regression is simply about finding the <strong>best values of m and c</strong> so that the line stays as close as possible to the real data points.</p><p>In scikit-learn, these learned values appear as:</p><ul><li><strong>coef_</strong> → the slope (<em>m</em>)</li><li><strong>intercept_</strong> → the starting point (<em>c</em>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-wh9TTBUOoU3SiF2IxuMg.png" /><figcaption>Jupyter Notebook output displaying Linear Regression slope (m) and intercept © values calculated using Python.</figcaption></figure><p>This equation is not just math — <strong>it’s the machine’s decision rule</strong>.</p><h3>How Does the Model Decide What “Best” Means?</h3><p>When we draw a line on a graph, we rely on intuition. We shift it up or down until it <em>looks</em> right. A machine doesn’t have that luxury — it needs a clear, measurable rule.</p><p>The model begins with a random line and uses it to make predictions. For each data point, it compares the predicted value with the actual value. The <strong>difference between them is called a residual</strong>.</p><blockquote><strong>If the residuals are large, the line is doing a poor job.<br>If the residuals are small, the line is doing better.</strong></blockquote><p>Linear Regression’s goal is to find the line where these residuals — taken together — are as small as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFj6a-V-wwMyavG_PqcMYw.png" /><figcaption>Linear Regression diagram showing a random line, data points, and residuals as vertical distances between actual and predicted values.</figcaption></figure><blockquote><strong>To measure how bad or good these residuals are overall, the model uses something called a loss function.</strong></blockquote><h3>Measuring Mistakes: The Role of Loss</h3><p>Why Accuracy Doesn’t Apply to Linear Regression</p><p>Unlike classification models, Linear Regression does not predict categories, so accuracy or prediction percentage is not meaningful here.<br>Instead, we measure how far predictions are from actual values using error-based metrics like Mean Squared Error (MSE) and R² score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zFxWM2folnj3HUnxQJbWg.png" /><figcaption>Jupyter Notebook showing Python code calculating the R² score to evaluate Linear Regression model performance.</figcaption></figure><p><strong>R²</strong> tells us how much of the variation in marks is explained by study hours.</p><p>To quantify error, we use a <strong>loss function</strong>. The most common one for Linear Regression is <strong>Mean Squared Error (MSE)</strong>.</p><blockquote><strong>Instead of caring about one mistake, MSE looks at <em>all</em> mistakes together, squares them, and takes the average.</strong></blockquote><blockquote><strong>Squaring the errors does two things: —</strong></blockquote><blockquote><strong>(i) it removes direction (positive or negative) and</strong></blockquote><blockquote><strong>(ii) heavily penalizes large mistakes.</strong></blockquote><blockquote><strong>This forces the model to care more about points that are far away from the line.</strong></blockquote><blockquote><strong>The smaller the loss, the better the line.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-QCfY6L8TQQurXSaytwLA.png" /><figcaption>Jupyter Notebook showing Python code calculating the MSE to evaluate Linear Regression model performance.</figcaption></figure><p>In a world dominated by deep learning and complex models, Linear Regression may seem simple — but its value has never faded. It’s fast, interpretable, and easy to explain, even to non-technical audiences. More importantly, it forms the foundation on which many advanced Machine Learning models are built.</p><p>Beyond its practical use, Linear Regression teaches something deeper: <strong>how machines learn from error</strong>. How predictions improve through adjustment, and how learning is driven by feedback rather than intuition.</p><p>Linear Regression is more than an algorithm. It’s a bridge — between classroom graphs and real-world intelligence, between intuition and computation. That straight line you once memorized is no longer static. It learns, adjusts, and improves.</p><p>And once you understand this, Machine Learning stops feeling like a black box. It starts to feel logical.</p><p>In the next algorithm, we’ll build on this idea — but replace the straight line with something more flexible. If you found this helpful, feel free to <strong>clap and share</strong> the blog so it can reach others who are starting their Machine Learning journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc0d376cd0f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Imbalanced Data in Machine Learning: Why Models Fail When Minority Voices Are Ignored]]></title>
            <link>https://medium.com/@richa.insights/imbalanced-data-in-machine-learning-why-models-fail-when-minority-voices-are-ignored-eb9d36f3697e?source=rss-99e3d2ac59ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb9d36f3697e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Richa Rani]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 11:08:26 GMT</pubDate>
            <atom:updated>2026-03-14T13:06:34.471Z</atom:updated>
            <content:encoded><![CDATA[<h3>Imbalanced Data in Machine Learning: Why Models Fail When Minority Voices Are Ignored | Machine Learning Series Part 11</h3><p>A few days ago, I was casually scrolling through my phone when a short <a href="https://youtube.com/shorts/2poL_OvUDOw?si=5Yb9ui8hbSphDSZt">video popped up on my feed. I watched it once… then twice</a>. And suddenly, something clicked. The video talked about voting, representation, and how often the <em>real voice of people gets buried</em>. In the world of politics, especially in India, misleading numbers, fake narratives, and unequal representation can completely change election outcomes. Sometimes, the right people lose, and the wrong people come to power.</p><p>At the heart of this problem lies a simple but dangerous imbalance: <strong>the majority overpowering the minority</strong>. When one group’s voice dominates, the other is ignored. Decisions are made based on loud numbers, not fair representation. Over time, this imbalance fuels corruption, broken promises, and a growing gap between reality and results.</p><p>What shocked me most was realizing that this problem isn’t limited to elections — it quietly exists in the systems we trust every day. In machine learning and analytics, we call it <strong>imbalanced data</strong>. When one class dominates a dataset, machine learning models learn to favor it. Just like elections, the outcome may look accurate on paper, but in reality, it’s deeply biased.</p><p>And that’s why understanding imbalanced data isn’t just a technical concept — it’s about fairness, representation, and making decisions that actually reflect the truth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5SN8yPUVLiJGz1AwVny-qw.png" /></figure><h3>What Is Imbalanced Data?</h3><p>Imbalanced data occurs when one category (class) significantly outnumbers another. In simple terms, one class has significantly more examples than the other(s). This can lead to biased models that favour the majority class and struggle to properly learn the characteristics of the minority class.</p><p>Think of an election:</p><ul><li>Majority voters dominate</li><li>Minority voices are ignored</li><li>Outcome appears legitimate</li><li>Reality is distorted</li></ul><p>Now replace:</p><ul><li><strong>Voters → Data points</strong></li><li><strong>Votes → Labels</strong></li><li><strong>Election result → Model prediction</strong></li></ul><p>Same problem. Same risk.</p><p>Let’s create a <strong>sample dataset which </strong>predict whether a voter report is <strong>Genuine (1)</strong> or <strong>Ignored (0) </strong>(Majority voices vs minority voices)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzpCWDoB_B-94pUbK7xlrg.png" /></figure><p><strong>Issue_Intensity </strong>shows how serious or important an issue is and <strong>Public_Reach</strong> shows how many people are talking about it or noticing it.<br>Even if an issue is very serious, it may still be ignored if only a few people hear about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCW03GC9f-5yQosIseG5Bg.png" /></figure><p>This dataset is <strong>clearly imbalanced</strong>, just like elections dominated by one narrative.</p><h3>Techniques to Handle Imbalanced Data</h3><h4>1. Undersampling — Reducing the Majority</h4><p><strong>Analogy: </strong>Limiting how many majority speakers are allowed, so minorities can be heard.</p><p><strong>What it does: </strong>Removes samples from the majority class.</p><p><strong>Risk: </strong>Important information may be lost.</p><h3>2. Oversampling — Boosting the Minority</h3><p><strong>Analogy: </strong>Allowing minority groups extra speaking opportunities.</p><p><strong>What it does: </strong>Duplicates minority samples.</p><p><strong>Risk: </strong>Overfitting (model memorizes instead of learning).</p><h3>3. SMOTE — Creating Fair Representation (Best Balance)</h3><p><strong>Analogy: </strong>Instead of repeating the same minority speaker, we invite <strong>new people with similar views</strong>.</p><p><strong>What it does: </strong>Creates <strong>synthetic minority data points</strong> based on feature similarity.</p><ul><li>It Balanced the data.</li><li>Less overfitting and</li><li>Widely used in industry</li></ul><p>Let’s apply SMOTE on the sample datasets mentioned above</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNPouKa__cBknm_brA2HTA.png" /></figure><h3>Why This Matters:</h3><p>Before SMOTE:</p><ul><li>Model learns to ignore minority</li><li>High accuracy, low fairness</li></ul><p>After SMOTE:</p><ul><li>Model sees patterns from both sides</li><li>Better recall</li><li>Better decisions</li></ul><h3>Real-World Examples of Imbalanced Data</h3><p>Imbalanced data is not just a theoretical problem — it appears in many real-life applications where the events we care about are <strong>rare but critical</strong>.</p><h4>- Credit Card or Loan Fraud Detection</h4><p>Fraudulent transactions are very rare compared to normal ones.</p><ul><li><strong>Majority class (1):</strong> Non-fraudulent transactions</li><li><strong>Minority class (0):</strong> Fraudulent transactions</li></ul><p>Because most transactions are non-fraud, models often become <strong>biased toward class 1</strong>. This can lead to overfitting on normal behavior and <strong>missing actual fraud cases</strong>, which is far more dangerous than raising a few false alarms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFR7az7thyvyqlFKjKL9ew.png" /></figure><h4>- Medical Diagnosis of Rare Diseases</h4><p>In healthcare datasets, patients with rare diseases may represent <strong>less than 0.1%</strong> of the data.</p><ul><li><strong>Majority class:</strong> Healthy patients (negative cases)</li><li><strong>Minority class:</strong> Patients with a rare disease (positive cases)</li></ul><p>If imbalance is not handled properly, the model may predict everyone as healthy, achieving high accuracy but <strong>failing to identify patients who truly need treatment</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6dvhP2YDJPZI_XtQd8DyQ.png" /></figure><h4>- Insurance Claim Prediction</h4><p>Most insurance customers do not file claims in a given period.</p><ul><li><strong>Majority class:</strong> No claim filed</li><li><strong>Minority class:</strong> Claim filed</li></ul><p>Since claim cases are rare, models trained on imbalanced data may ignore them, leading to poor risk assessment and financial losses for insurance companies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FsboDl39BOIv1fgOVlNiQ.png" /></figure><h4>- Text Classification for Spam Detection</h4><p>In email systems, spam messages are usually a very small fraction.</p><ul><li><strong>Majority class:</strong> Legitimate (non-spam) emails</li><li><strong>Minority class:</strong> Spam emails</li></ul><p>Without handling imbalance, the model may classify almost every email as legitimate, allowing <strong>dangerous or unwanted spam to pass through</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8YXwaXQ3WZQMOXMvyyY7A.png" /></figure><h4>- Anomaly Detection in Manufacturing</h4><p>Defective products occur very rarely on a production line.</p><ul><li><strong>Majority class:</strong> Perfect or normal products</li><li><strong>Minority class:</strong> Defective products</li></ul><p>If imbalance is ignored, the model learns mostly from perfect items and may <strong>fail to detect defects</strong>, affecting quality control and customer trust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*del-W8rtX3w7FOzuZH9zjA.png" /></figure><h4>Key Takeaway</h4><p>In all these cases, the minority class is small in number but <strong>high in importance</strong>. Handling imbalanced data ensures that machine learning models focus not only on what is common — but also on what truly matters.</p><p>Just like democracy fails when minority voices are silenced, machine learning fails when rare data points are ignored. Imbalanced data doesn’t just reduce model performance — it distorts truth. By handling imbalance correctly, we don’t just build better models; we build fairer systems. Because whether in elections or algorithms, real intelligence lies in listening to every voice — not just the loudest one.</p><p>If this perspective made you think, show some love with a clap and let me know your thoughts in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb9d36f3697e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Terminology Explained Through a Street Food Stall]]></title>
            <link>https://medium.com/@richa.insights/machine-learning-terminology-explained-through-a-street-food-stall-c9b6407828fd?source=rss-99e3d2ac59ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9b6407828fd</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Richa Rani]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 17:50:44 GMT</pubDate>
            <atom:updated>2026-03-14T13:05:42.991Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning Terminology Explained Through a Street Food Stall | Machine Learning Series Part 10</h3><p>Machine learning concepts often sound complicated, especially for beginners. Terms like residuals, homoscedasticity, heteroscedasticity, and multicollinearity can feel abstract when explained only through formulas.</p><p>In this article, I explain these core machine learning terms using a simple, real-life example: a street food stall near my house.</p><p>Every evening at 6 PM, a street food vendor sets up his stall near my house. Some days, he’s busy without a break. Other days, he’s just standing there, waiting for customers. The difference between those days is easy to notice.</p><p>One quiet evening, he smiled and said, <em>“Even my chutney is bored today.”</em> That small joke perfectly captured how unpredictable his work can be. Some nights are full, and some are completely slow.</p><p>That made me curious. What if we looked at this like a data problem? What if machine learning could predict how many plates he would sell each day? That thought led me to revisit some machine learning terms that sound complicated at first, but make complete sense when you see them play out in real life. Let’s break them down using this one street food stall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7majq70DpAVkIVKhBGrAQ.png" /><figcaption>It explain machine learning concepts like residuals, homoscedasticity, heteroscedasticity, and multicollinearity, with customers waiting, puzzle pieces labeled with ML terms, and a chart comparing actual and predicted values.</figcaption></figure><h3>1. Residuals: The Gap Between Expectation and Reality</h3><p>Suppose a model predicts that the vendor will sell <strong>120 plates</strong> tonight but by the end of the day, he sells only <strong>95</strong>.</p><p>Those extra plates that didn’t sell? That difference is called a <strong>residual.</strong></p><p>In simple terms:</p><blockquote><strong>Residual = Actual value − Predicted value</strong></blockquote><p>Residuals are not mistakes to hide, they are feedback.</p><p>They tell us <strong>how far our expectations were from reality</strong>.</p><p>If residuals are large and frequent, the model is missing something important — maybe weather, nearby events, or a cricket match on TV.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kj3_2W9bF1OuUFCpXPCjsA.png" /><figcaption>Side-by-side street food stall image showing predicted sales versus actual sales, illustrating residuals in machine learning.</figcaption></figure><h3>2. Normality of Residuals: Are the Vendor’s Bad Days Balanced?</h3><p>After watching the stall for a few weeks, a pattern began to emerge. On some days, the model predicted slightly more plates than the vendor sold, and on others, it predicted slightly fewer. That felt reasonable. Most days, the difference was small — five or ten plates here and there. Big surprises were rare.</p><p>This is what <strong>normality of residuals</strong> looks like in real life. The model’s mistakes were balanced. It wasn’t always overestimating sales, and it wasn’t always underestimating them either. If you listed all those daily errors, they wouldn’t lean heavily to one side.</p><p>Imagine plotting those mistakes on a chart. Most would cluster close to zero, while a few bad days would sit farther away — like sudden rain or an unexpected city-wide strike. When residuals follow this pattern, we say they are normally distributed. And this matters because a model that makes fair, balanced mistakes is far more trustworthy than one that consistently leans in one direction, even if both show similar accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tP4VYDhRlkcdIAmJKhFDg.png" /><figcaption>Normality of residuals shown using a street food stall example, with a bell-curve distribution of prediction errors.</figcaption></figure><h3>3. Homoscedasticity: Same Level of Noise Every Day</h3><p>On regular weekdays, the vendor’s stall follows a familiar rhythm. Office-goers stop by after work, a few regular customers show up, and sales move within a predictable range.</p><p>On these days, the model’s mistakes stay small. It might predict five plates extra or miss by a few, but the variation feels manageable.</p><p>This is <strong>homoscedasticity</strong> — when the spread of errors remains roughly the same across different predictions.</p><p>It’s like the background noise near the stall. Cars pass by, people talk, oil sizzles — present, but consistent.</p><p>Models perform best under this condition because uncertainty is evenly spread, and the model knows what kind of chaos to expect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uOrTxo3VUv8-UOvs1sQeeg.png" /><figcaption>Homoscedasticity illustrated with a street food stall on a regular weekday, showing consistent prediction errors and stable sales patterns.</figcaption></figure><p>But this calm, predictable behavior doesn’t last forever. Not every day follows the same rhythm, and when the environment changes, the model’s mistakes start behaving differently too.</p><h3>4. Heteroscedasticity: When the Crowd Becomes Unpredictable</h3><p>Then there are nights when everything changes. A festival nearby, a cricket match on TV, or sudden rain can completely alter the evening. The stall that usually feels predictable turns chaotic, reacting to forces no model can fully anticipate.</p><p>On some of these nights, plates fly off the counter faster than expected. On others, people disappear just as quickly. The prediction model that worked well on calm weekdays starts to struggle, and the errors become larger and harder to control.</p><p>This is <strong>heteroscedasticity</strong> — when the variability of residuals changes with conditions. In real life, higher sales often come with higher uncertainty. Ignoring this makes a model appear confident even when reality is volatile, like assuming festival nights will behave just like a normal Tuesday.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIfIOgzlvMoJo0q_9VVg8A.png" /><figcaption>Heteroscedasticity explained with a street food stall example, showing unpredictable sales and increasing prediction errors on busy and festival nights.</figcaption></figure><h3>5. Multicollinearity: When the Stall Gives Duplicate Signals</h3><p>To improve predictions, we start adding more details about the stall. We note how many people are standing nearby, how long the queue is, and what time of day it is. At first, this feels like a smart way to give the model more information.</p><p>But there’s a catch. The number of people nearby and the length of the queue almost always rise and fall together. They’re not independent signals — they’re telling the same story in slightly different words.</p><p>This is <strong>multicollinearity</strong>. When a model sees multiple features saying the same thing, it struggles to decide which one truly matters. It’s like asking two customers who arrived together why they came — you don’t gain extra insight, just repetition. Multicollinearity may not hurt accuracy much, but it makes the model’s decisions unstable and harder to interpret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQfr78JQE-oCyNhIk4yCRA.png" /><figcaption>Multicollinearity illustrated with a street food stall, where queue length, people nearby, and time of day give overlapping signals to a machine learning model.</figcaption></figure><p>In practice, this is why data scientists often check correlations or use simple metrics like VIF to detect and reduce multicollinearity before trusting a model’s interpretation.</p><h3>6. Why These Assumptions Matter in Real Life</h3><p>It’s tempting to judge the stall’s prediction model using just one number — accuracy.</p><p>But standing near the stall every evening teaches a different lesson.</p><p>Machine learning isn’t only about predicting how many plates will sell. It’s about knowing <strong>when those predictions deserve trust</strong>.</p><p>Residuals, normality, homoscedasticity, and multicollinearity act like warning signs. They tell us whether the model understands the rhythm of the stall — or is just reacting to patterns it doesn’t fully grasp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3H5M_jFlB8MlQenz2dmbg.png" /><figcaption>Illustration of a street food stall showing how machine learning model trust depends on residuals and assumptions, not just accuracy.</figcaption></figure><p>That street food stall never became perfectly predictable — and it shouldn’t. Machine learning doesn’t exist to remove uncertainty from real life. It exists to help us understand where that uncertainty comes from and how it behaves under different conditions.</p><p>Sometimes, the most valuable insights don’t come from the predictions themselves. They come from observing where, when, and why those predictions go wrong. That’s where learning actually begins.</p><p>If you found this blog helpful, feel free to leave a comment and share it with someone who’s learning machine learning.</p><p>I’d also love to know — have you seen similar patterns in real life that reminded you of ML concepts?</p><p>If this series is helping you learn, don’t forget to clap and follow for the next part of the ML series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9b6407828fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cardinality in Machine Learning: When Too Much Uniqueness Becomes Noise]]></title>
            <link>https://medium.com/@richa.insights/cardinality-in-machine-learning-when-too-much-uniqueness-becomes-noise-a7c17929c7dd?source=rss-99e3d2ac59ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7c17929c7dd</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Richa Rani]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 15:39:05 GMT</pubDate>
            <atom:updated>2026-03-14T13:04:50.222Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cardinality in Machine Learning: When Too Much Uniqueness Becomes Noise | Machine Learning Series Part 9</h3><p>On New Year’s Eve, as our phones light up, it’s not just messages from people — every shopping app starts sending notifications too: <em>“Flat 50% OFF,” “New Year Mega Sale,” “Limited-Time Deal,” “Special Discount Just for You.”</em> Different apps, different messages, different designs — but all pointing to the same thing: a New Year’s sale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0BdZS90pO9AXbRyEtRV6A.jpeg" /><figcaption>Young man excitedly looking at phone with New Year sale notification and data network graphics in the background.</figcaption></figure><p>Now imagine opening each app and instead of seeing <em>discount percentage</em>, <em>category</em>, or <em>offer type</em>, you only see:</p><ul><li>coupon IDs</li><li>transaction codes</li><li>offer reference numbers</li><li>notification IDs</li></ul><p>Technically, all of this information is correct. But does it help you decide where to shop?</p><p>Not really.</p><p>This is exactly what happens in machine learning when we don’t handle <strong>cardinality</strong> properly.</p><p>Models don’t learn from IDs and codes. They learn from <strong>patterns that repeat</strong>.</p><p>And the difference between useful repetition and useless uniqueness is called <strong>cardinality</strong>.</p><h3>What Is Cardinality?</h3><p>In machine learning, <strong>cardinality</strong> simply means the number of <strong>unique values</strong> present in a feature or column.</p><p>If a column has only a few repeating values, it has <strong>low cardinality</strong>.<br>If almost every row has a different value, it has <strong>high cardinality</strong>.</p><p>Just like in shopping apps:</p><ul><li><em>Discount type</em> repeats</li><li><em>Product category</em> repeats</li><li><em>Coupon ID</em> changes every time</li></ul><p>Not all information is equally useful for learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kc7WEz21elLXN-dD3cLZnQ.png" /><figcaption>Smartphone screen showing comparison of low cardinality (repeating discount types and product categories) versus high cardinality (unique coupon codes)</figcaption></figure><h3>Why Cardinality Matters So Much</h3><p>At first glance, columns like <em>User_ID</em>, <em>Order_ID</em>, <em>Transaction_Number</em>, or <em>Serial_Code</em> look important because they uniquely identify each record. They feel precise and reliable, which makes them seem useful.</p><p>However, precision alone doesn’t help a machine learning model learn. Since these values almost never repeat, the model cannot find patterns in them. Instead of learning what usually causes an outcome, it ends up memorizing specific values. This leads to overfitting, where the model works well on old data but fails on new data. It’s similar to remembering random coupon codes instead of understanding which discounts actually make you buy something.</p><h3>Low vs High Cardinality: A Real-Life View</h3><p>When you shop during a New Year sale, you naturally think in terms of <em>categories</em> — clothing, electronics, groceries — or <em>discount types</em> like flat offers or cashback. These ideas repeat across apps and products, which makes comparison easy and decisions faster.</p><p>Now think about coupon IDs or transaction reference numbers. Each one is unique. They are necessary for systems to work, but they don’t help you decide where to spend your money. There’s nothing to compare and nothing to learn from.</p><p>Machine learning models behave the same way. They learn from repeating signals, not from values that are unique every single time.</p><h3>Cardinality in Real Datasets</h3><p>In real datasets, this shows up very clearly.</p><h4>E-commerce Dataset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9F_3klEDXG2ofoTaOfbzMw.png" /><figcaption>Table showing column cardinality and usefulness, where product category and brand are useful, while product ID and customer ID are high-cardinality and not useful.</figcaption></figure><h4>Banking Dataset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzPP4z0Lw5cVTa2k_oGTAg.png" /><figcaption>Table showing banking dataset features, where account type and transaction type have low cardinality and are useful, while transaction ID has very high cardinality and is not useful.</figcaption></figure><p>The pattern is consistent across domains.</p><h3>Why High Cardinality Can Harm Models</h3><p>When high-cardinality features are used carelessly, several problems appear.</p><ul><li>First, the model starts <strong>overfitting</strong> — learning rules like<br> “If User_ID = X, then fraud”<br> instead of learning general fraud patterns.</li><li>Second, <strong>encoding</strong> high-cardinality features creates thousands of sparse columns, making training slower and models harder to maintain.</li><li>Finally, when new unseen values appear, the model struggles because it never learned <em>patterns</em>, only memorized values.</li></ul><h3>Does High Cardinality Always Mean Bad?</h3><p>Not always.</p><p>High-cardinality features can be useful <strong>if handled correctly</strong>. Techniques like target encoding, frequency encoding, or creating aggregated features allow us to extract meaning without overwhelming the model.</p><p>Blindly using high-cardinality columns as they are is the real problem.</p><h3>How to Handle Cardinality (Practical Approaches)</h3><ul><li>One simple approach is to drop ID-like columns that are unique and don’t carry semantic meaning, such as order IDs or transaction numbers.</li><li>Another approach is grouping rare categories into an “Others” bucket, reducing unnecessary uniqueness.</li><li>Instead of one-hot encoding, techniques like target or frequency encoding can capture information more efficiently.</li><li>Finally, creating meaningful aggregates — such as total purchases, average spend, or purchase frequency — transforms high-cardinality identifiers into useful signals.</li></ul><p>This is where cardinality stops being noise and starts becoming information.</p><h3>A Simple Rule of Thumb</h3><p>Before using any categorical feature, ask yourself:</p><blockquote><strong><em>If I remove the unique value, does the meaning still remain?</em></strong></blockquote><ul><li>If yes, it’s probably a good feature.</li><li>If no, it’s likely high-cardinality noise.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wESMYX8wkqf0tIO2vw4Og.png" /><figcaption>Diagram showing a simple rule of thumb to distinguish good low-cardinality features from high-cardinality noise using a meaning-retention check.</figcaption></figure><h3>Final Thought</h3><p>Just like New Year shopping decisions are driven by discounts and categories — not coupon IDs — machine learning models learn better from patterns, not uniqueness.</p><p>Cardinality isn’t about the quantity of data, but about how much meaningful information it conveys.</p><p>Once you notice it, you’ll start seeing cardinality everywhere — not just in datasets, but in everyday life.</p><p>If you found this blog helpful, please clap, comment your thoughts, and share it with others. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7c17929c7dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Filter Methods in Feature Selection: Simplify Your Dataset for Faster Machine Learning]]></title>
            <link>https://medium.com/@richa.insights/filter-methods-in-feature-selection-simplify-your-dataset-for-faster-machine-learning-e4d71b474ff0?source=rss-99e3d2ac59ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4d71b474ff0</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Richa Rani]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 11:38:50 GMT</pubDate>
            <atom:updated>2026-03-14T13:02:55.200Z</atom:updated>
            <content:encoded><![CDATA[<h3>Filter Methods in Feature Selection: Simplify Data to Boost Machine Learning Performance | Machine Learning Series Part 8</h3><p>In everyday life, <strong>decision-making doesn’t start with choosing </strong>— it begins with <strong>filtering</strong>, and a supermarket proves this every single day. Imagine walking into a supermarket filled with countless products: snacks, vegetables, cleaning supplies, cosmetics, toys, and dozens of brands. You don’t stop at every aisle or pick every item on the shelf. Instead, your brain quickly filters out what you don’t need based on your goals, budget, or preferences.</p><p>This natural filtering process is exactly how <strong>Filter Methods</strong> work in machine learning feature selection. Just like a shopper ignores irrelevant products, filter methods remove features from a dataset that don’t contribute valuable information, making the model training process faster and more effective. In this blog, we’ll explore how these methods work, their key statistical techniques, and their strengths and limitations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sWjOhrM8v-reaSTOS2kHg.png" /><figcaption>Illustration of a supermarket shopping analogy for filter methods in machine learning feature selection, showing how irrelevant items or features are filtered out before model training.</figcaption></figure><h3>What Are Filter Methods?</h3><p>Filter methods are feature selection techniques applied <strong>before model training</strong>. They evaluate features using <strong>statistical properties of the data</strong>, not model performance, and assess each feature independently — removing those that fail to meet set criteria.</p><p>Think of it like shopping in a supermarket. You don’t test-cook every product before buying it. You filter items based on labels, price, or necessity — long before reaching the billing counter. Similarly, filter methods clean data early by removing <strong>low-variance features, weakly related features, and noisy features</strong>.</p><p>Because they are model-independent, filter methods are <strong>fast, scalable, and free from model bias </strong>especially useful when dealing with large datasets or during early data exploration. However, evaluating features individually means they can <strong>miss important feature interactions</strong>, which is a key limitation.</p><h3>How Filter Methods Work</h3><p>Filter methods work by examining the <strong>statistical characteristics of each feature</strong>, one at a time, without involving any machine learning model.</p><p>Each feature is given a <strong>score</strong> based on a predefined rule — such as variance, correlation with the target, or information gain. If the feature meets the required threshold, it stays; otherwise, it is removed.</p><p>There is <strong>no interaction between features</strong> at this stage. Every feature is judged independently, purely on how informative it appears from the data itself.</p><p>Just like in a supermarket, where you quickly scan items and ignore what doesn’t fit your needs, filter methods quickly scan features and discard what doesn’t add value — long before any model training begins.</p><h3>A Supermarket Scenario : The Dataset</h3><p>We’ll use a small, easy-to-understand dataset inspired by a supermarket shopping experience. Let’s look at a sample dataset of shoppers. We want to predict the Buy column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqdHYcBv6McIWxCbpMEIlw.png" /><figcaption>Sample supermarket dataset displayed in Pandas DataFrame, used to explain filter methods in machine learning feature selection.</figcaption></figure><p>Since machine learning models work with numbers, we converted the categorical features into numerical values using Label Encoding, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-bxvjtBYQeCeqOr1xknSPA.png" /><figcaption>Label encoding of categorical features in a supermarket dataset, preparing data for filter methods in machine learning feature selection.</figcaption></figure><h3>Common Statistical Measures Used in Filter Methods</h3><h4>1 Variance</h4><p>Variance measures how much a feature’s values change across the dataset. Features with <strong>low or zero variance</strong> show little to no variation. Such features do not help distinguish between data points</p><p><strong>Used: </strong>when<strong> </strong>you want to remove constant or near-constant features early.</p><p>If a feature looks the same for almost everyone, it doesn’t help the model make decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJburP1ujB10NdKi_0r2ZA.png" /><figcaption>Output of Variance Threshold filter method displaying feature variances and selected features before model training</figcaption></figure><h4>2 Correlation (Pearson / Spearman)</h4><p>Correlation measures the <strong>strength and direction of the relationship</strong> between two variables.</p><ul><li>Features weakly correlated with the target may be removed</li><li>Highly correlated features with each other may be redundant</li></ul><p><strong>Types:</strong></p><ul><li><strong>Pearson correlation</strong>: linear relationships</li><li><strong>Spearman correlation</strong>: monotonic relationships (rank-based)</li></ul><p><strong>Used: </strong>when<strong> </strong>you want to reduce redundancy and keep features that truly relate to the target.</p><p>Keeping two highly similar features is like buying the same product twice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ue66sXdj5MIRnmM3fXzRLA.png" /><figcaption>Correlation-based filter method showing feature correlations with the target variable in a supermarket dataset for machine learning feature selection.</figcaption></figure><p>Correlation works best for numerical features and linear relationships</p><h4>3 Information Gain</h4><p>Information Gain measures how much <strong>information a feature provides about the target variable</strong>.</p><ul><li>Higher information gain = more useful feature</li><li>Commonly used in classification problems</li></ul><p><strong>Used: </strong>When you want features that reduce uncertainty in predictions.</p><p>A good feature answers important questions about the outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p67W2J7CDPTzNMWc1nRxzA.png" /><figcaption>Mutual Information filter method ranking features by information gain in a supermarket dataset for machine learning feature selection.</figcaption></figure><h4>4 Mutual Information</h4><p>Mutual Information measures the <strong>dependency between a feature and the target</strong>, capturing both linear and non-linear relationships.</p><ul><li>Value is always non-negative</li><li>Higher values indicate stronger dependence</li></ul><p><strong>Used : </strong>When relationships are complex and not strictly linear.</p><p>Even if two variables don’t move together linearly, they may still share useful information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWe1nSVmXtqBIvMQ6JgAiQ.png" /><figcaption>Mutual Information scores ranking features by how much information they provide about the target variable before model training.</figcaption></figure><h4><strong>Note:-</strong></h4><blockquote>You might notice that Information Gain and Mutual Information often produce similar feature rankings in practice. This can be confusing, but they are <strong>related — not identical</strong>.</blockquote><h4><strong>Information Gain (IG):</strong></h4><blockquote>— Measures how much <strong>entropy (uncertainty)</strong> is reduced in the target after knowing a feature</blockquote><blockquote>— Commonly used in <strong>decision trees</strong></blockquote><blockquote>— Calculated as: <strong>Information Gain = Entropy(before) − Entropy(after split)</strong></blockquote><blockquote>— Typically defined for <strong>discrete features</strong></blockquote><h4><strong>Mutual Information (MI):</strong></h4><blockquote>— Measures how much <strong>information two variables share</strong></blockquote><blockquote>— Captures <strong>both linear and non-linear relationships</strong></blockquote><blockquote>— Always <strong>non-negative</strong></blockquote><blockquote>— More <strong>general and flexible</strong> than Information Gain</blockquote><blockquote>— Works with <strong>both continuous and discrete data</strong></blockquote><blockquote><strong>In simple terms</strong>, Information Gain tells us how much a product reduces uncertainty when making a decision. while Mutual Information measures <strong>how strongly a product and our decision are connected</strong>. <strong>In practice, both help us pick the most informative items for the cart.</strong></blockquote><h4>5 Chi-Square Test (χ²)</h4><p>The Chi-Square test measures the <strong>association between categorical features and the target</strong>.</p><ul><li>Works only with <strong>non-negative values</strong></li><li>Common in text classification and categorical data</li></ul><p><strong>Used : </strong>When you want to select important categorical features.</p><p>It checks whether a feature and target are independent or related.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_mI3FJTn2QOuMskkr4S4w.png" /><figcaption>Chi-Square filter method ranking features by their association with the target variable in a supermarket dataset for machine learning feature selection</figcaption></figure><blockquote><em>Chi-Square requires all input features to be non-negative.</em></blockquote><p>This shows strong conceptual understanding.</p><h4>6 ANOVA (Analysis of Variance)</h4><p>ANOVA tests whether the <strong>means of a numerical feature differ significantly across target classes</strong>.</p><ul><li>Common in classification tasks</li><li>Helps identify discriminative numerical features</li></ul><p><strong>Used :</strong>When you want to compare feature importance across multiple classes.</p><p>If class averages are very different, the feature is informative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UPq1QPUmVqFIfcaQMafew.png" /><figcaption>A Jupyter Notebook screenshot showing Python code for feature selection using f_classif. The output lists &quot;Discount(%)&quot; as the highest-ranked feature with a score of 24.16.</figcaption></figure><h3>Limitations of Filter Methods</h3><p>While filter methods are fast and simple, they have some limitations:</p><ul><li>They evaluate features independently</li><li>They may miss important feature interactions and multicollinearity</li><li>Statistical relevance doesn’t always guarantee model performance</li></ul><p>Filter methods are best used as an <strong>initial step</strong>, often combined with wrapper or embedded methods for better results.</p><h3>Picking the Best Items from the Shelf: SelectKBest</h3><p>Sometimes, you don’t need to manually check every statistic. You just have to say: <em>“Give me the top 2 best features based on the Chi-Square test.”</em> This is where SelectKBest comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*erdbyusIM60xv4GswyN6Ag.png" /><figcaption>A Jupyter Notebook screenshot showing Python code that uses SelectKBest with chi2 to select the top two features from a dataset. The output displays the result: &quot;The best features are: [&#39;Price&#39;, &#39;Discount(%)&#39;]</figcaption></figure><p>Filter methods are like your smart shopping strategy for datasets — they help you quickly identify and keep only the most useful features before you start building machine learning models.</p><p>Ready to clean your dataset like a pro? Try applying filter methods on your next machine learning project, and see how much smoother the process becomes!</p><p>If you found this blog helpful, please clap, comment your thoughts, and share it with others. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4d71b474ff0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>