<?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 Ankita Mohanty on Medium]]></title>
        <description><![CDATA[Stories by Ankita Mohanty on Medium]]></description>
        <link>https://medium.com/@ankitamohanty1919191?source=rss-b12caf5915c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Ankita Mohanty on Medium</title>
            <link>https://medium.com/@ankitamohanty1919191?source=rss-b12caf5915c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 04:45:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankitamohanty1919191/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[K-Means Clustering]]></title>
            <link>https://medium.com/@ankitamohanty1919191/k-means-clustering-a12b42510317?source=rss-b12caf5915c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a12b42510317</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <dc:creator><![CDATA[Ankita Mohanty]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 15:25:54 GMT</pubDate>
            <atom:updated>2026-08-19T15:25:54.477Z</atom:updated>
            <content:encoded><![CDATA[<p>I learnt <strong>K-Means Clustering</strong>, which is one of the most popular <strong>Unsupervised Learning</strong> algorithms.</p><p>Unlike classification, here we <strong>don’t have output labels</strong>. The algorithm itself tries to find similar groups in the data.</p><p><strong>“If similar people naturally stand together, K-Means simply finds those groups.”</strong></p><h3>1. Introduction</h3><p>K-Means is a <strong>clustering algorithm</strong>.</p><p>Its goal is to divide data into <strong>K clusters</strong>.</p><p>Each cluster is represented by a point called the <strong>Centroid</strong>.</p><h3>What is a Centroid?</h3><p>A centroid is simply the <strong>center (mean position)</strong> of all points belonging to that cluster.</p><p>It is <strong>not always an actual data point</strong>.</p><p>Example:</p><p>Customer Segmentation</p><ul><li>Cluster 1 → Students</li><li>Cluster 2 → Working Professionals</li><li>Cluster 3 → Senior Citizens</li></ul><p>We never told the algorithm these labels — it discovered them by itself.</p><h3>Why is it called K-Means?</h3><ul><li><strong>K</strong> = Number of clusters.</li><li><strong>Means</strong> = Mean (average) used to calculate the centroid.</li></ul><h3>2. Geometric Intuition</h3><p>This is the easiest way to remember K-Means.</p><p>Suppose we choose:</p><p><strong>K = 3</strong></p><h3>Step 1: Initialize K Centroids</h3><p>Initially, K-Means randomly places <strong>3 centroids</strong> on the graph.</p><p>These positions are usually random (unless using K-Means++).</p><h3>Step 2: Calculate Distance</h3><p>Now every data point calculates its distance from every centroid.</p><p>The point joins the cluster of the <strong>nearest centroid</strong>.</p><p>Common distance metrics:</p><ul><li>Euclidean Distance (most commonly used)</li><li>Manhattan Distance (less common in standard K-Means)</li></ul><h3>Euclidean Distance</h3><p>Straight-line distance.<br>d=sqrt{(x2-x1)²+(y2-y1)²}</p><h3>Manhattan Distance</h3><p>City-block distance.<br>d=|x2-x1|+|y2-y1|</p><p><strong>Note:</strong> Standard K-Means minimizes <strong>Euclidean distance (squared Euclidean distance)</strong>. Manhattan distance is used in K-Medians or K-Medoids, not classical K-Means.</p><h3>Step 3: Form Clusters</h3><p>Every point joins its nearest centroid.</p><p>Now we have temporary clusters.</p><p>The boundaries between clusters are called <strong>Voronoi regions</strong> (nice interview term), though it’s perfectly fine to remember them simply as dividing lines.</p><h3>Step 4: Move the Centroid</h3><p>Now calculate the average of all points inside each cluster.</p><p>That average becomes the <strong>new centroid</strong>.</p><p>Example:</p><p>Cluster points:</p><p>(2,3)</p><p>(4,5)</p><p>(6,7)</p><p>New centroid:<br>((2+4+6)/3,(3+5+7)/3)=(4,5)</p><p>So the centroid shifts.</p><h3>Step 5: Repeat</h3><p>Again,</p><ul><li>Calculate distances.</li><li>Assign points.</li><li>Recompute centroid.</li></ul><p>Repeat until nothing changes.</p><h3>When do we stop?</h3><p>We stop when:</p><ul><li>Centroids stop moving (or move very little).</li><li>Cluster assignments no longer change.</li><li>Maximum iterations are reached.</li></ul><p>This is called <strong>convergence</strong>.</p><h3>Whole Algorithm in One Flow</h3><p>(K-Means)</p><p>Initialize Centroids</p><p>↓</p><p>Assign Points</p><p>↓</p><p>Move Centroids</p><p>↓</p><p>Assign Again</p><p>↓</p><p>Move Again</p><p>↓</p><p>Repeat until centroids stop moving</p><h3>3. How is K Selected?</h3><p>This is one of the biggest questions in K-Means.</p><p>The most common method is the <strong>Elbow Method</strong>.</p><h3>WCSS (Within Cluster Sum of Squares)</h3><p>WCSS measures how compact the clusters are.</p><p>Formula:<br>WCSS=summation(distance of point from its centroid)²</p><p>Smaller WCSS means points are closer to their centroid.</p><h3>Procedure</h3><p>Take:</p><p>K = 1</p><p>↓</p><p>Compute WCSS</p><p>↓</p><p>K = 2</p><p>↓</p><p>Compute WCSS</p><p>↓</p><p>…</p><p>↓</p><p>K = 20</p><p>Now plot:</p><p>K vs WCSS</p><p>Initially:</p><p>Increasing K reduces WCSS a lot.</p><p>After some point:</p><p>The improvement becomes very small.</p><p>The bend in the graph is called the <strong>Elbow</strong>.</p><p>That K is usually chosen.</p><h3>Why doesn’t WCSS always decide K perfectly?</h3><p>Sometimes there is <strong>no clear elbow</strong>.</p><p>In those cases, we use other validation techniques like the <strong>Silhouette Score</strong>.</p><h3>Euclidean vs Manhattan</h3><p>You wrote both together, but remember this distinction:</p><h3>Euclidean</h3><ul><li>Straight-line distance.</li><li>Default for K-Means.</li><li>Used to minimize WCSS.</li></ul><h3>Manhattan</h3><ul><li>Block distance.</li><li>Not the default distance for classical K-Means.</li></ul><h3>4. Random Initialization Trap (K-Means++)</h3><p>This is a very important interview topic.</p><p>Suppose the actual data has three natural clusters.</p><p>If we randomly place all centroids close together,</p><p>the algorithm may converge to a poor solution.</p><p>Example:</p><p>Actual clusters:</p><p>● ● ●</p><p>▲ ▲ ▲</p><p>■ ■ ■</p><p>Random initialization:</p><p>X X X</p><p>(all centroids start in one region)</p><p>Now the algorithm struggles to discover the true clusters.</p><p>This is called the <strong>Random Initialization Problem</strong>.</p><h3>How does K-Means++ solve this?</h3><p>Instead of placing centroids completely randomly:</p><h3>Step 1</h3><p>Choose the first centroid randomly.</p><h3>Step 2</h3><p>Choose the next centroid <strong>far away</strong> from the existing centroid.</p><p>Points farther from existing centroids have a higher probability of being selected.</p><h3>Step 3</h3><p>Repeat until K centroids are chosen.</p><p>Now the centroids start well separated.</p><p>Result:</p><ul><li>Faster convergence.</li><li>Better clustering.</li><li>Lower chance of bad local solutions.</li></ul><p>This is why scikit-learn uses <strong>init=&#39;k-means++&#39; by default</strong>.</p><h3>5. K-Means Practical</h3><h3>Workflow</h3><p>Import Libraries</p><p>↓</p><p>Create Dataset (make_blobs)</p><p>↓</p><p>Visualize Data</p><p>↓</p><p>Standardize Features</p><p>↓</p><p>Find Optimal K</p><p>↓</p><p>Train Final K-Means</p><p>↓</p><p>Predict Cluster Labels</p><p>↓</p><p>Validate</p><h3>Create Dataset</h3><p>make_blobs() creates synthetic clustered data for practice.</p><h3>Standardization</h3><p>Very important.</p><p>Since K-Means uses distances, features with larger scales dominate.</p><p>So we use:</p><p>StandardScaler()</p><p>before applying K-Means.</p><p>For basic K-Means, <strong>train-test split is generally not required</strong>, because there are no labels to predict.</p><p>Usually the flow is:</p><p>Dataset</p><p>↓</p><p>StandardScaler</p><p>↓</p><p>K-Means</p><p>If you’re building a complete ML pipeline or evaluating on new data, you <em>may</em> split later, but it’s not a standard step in introductory K-Means.</p><h3>WCSS Code Flow</h3><p>For K from 1 to 20:</p><ul><li>Initialize KMeans</li><li>Fit model</li><li>Store inertia_</li></ul><p>In scikit-learn,</p><p>inertia_ = <strong>WCSS</strong></p><p>Then plot:</p><p>K vs WCSS</p><p>Choose the elbow.</p><h3>Final Model</h3><p>Initialize:</p><p>KMeans(n_clusters=k)</p><p>↓</p><p>Fit</p><p>↓</p><p>fit_predict()</p><p>Returns cluster labels:</p><p>Example:</p><pre>0<br>2<br>1<br>1<br>0</pre><p>Each number represents the cluster assigned to that data point.</p><h3>Validation of Clusters</h3><p>Since we don’t have labels,</p><p>we need methods to check whether clustering is good.</p><h3>A. Elbow Method</h3><p>Already discussed.</p><p>Helps estimate K.</p><h3>B. Knee Locator (kneed library)</h3><p>Sometimes the elbow isn’t visually obvious.</p><p>The KneeLocator automatically finds the elbow.</p><p>Important parameter:</p><p>curve=&#39;convex&#39;</p><h3>C. Silhouette Score</h3><p>This is usually a better validation metric.</p><p>Range:</p><ul><li><strong>+1</strong> → Excellent clustering.</li><li><strong>0</strong> → Overlapping clusters.</li><li><strong>Negative</strong> → Wrong cluster assignments.</li></ul><p>Higher Silhouette Score is better.</p><p>It measures:</p><ul><li>How close a point is to its own cluster.</li><li>How far it is from other clusters.</li></ul><p>Choose the K with the <strong>highest Silhouette Score</strong>, keeping in mind that domain knowledge and visualization also matter.</p><h3>Why Standardization is Necessary</h3><p>Suppose:</p><p>Feature 1:</p><p>Age → 20–60</p><p>Feature 2:</p><p>Salary → 20,000–10,00,000</p><p>Without scaling,</p><p>Salary dominates the distance calculation.</p><p>After StandardScaler,</p><p>both contribute fairly.</p><h3>Advantages of K-Means</h3><ul><li>Simple.</li><li>Fast.</li><li>Works well for spherical clusters.</li><li>Easy to interpret.</li><li>Scales well to large datasets.</li></ul><h3>Limitations</h3><ul><li>Must choose K beforehand.</li><li>Sensitive to initialization (solved partly by K-Means++).</li><li>Sensitive to outliers.</li><li>Assumes clusters are roughly spherical and similar in size.</li><li>Doesn’t work well for irregularly shaped clusters.</li></ul><h3>K-Means vs KNN</h3><p>K-Means{Unsupervised, No labels, Finds clusters, Uses centroids,Training creates clusters}</p><p>KNN{Supervised, Uses labels, Predicts labels, Uses nearest neighbours, Training stores data &amp;prediction compares neighbours}</p><p><strong>Memory trick:</strong></p><ul><li><strong>K-Means = Find Groups.</strong></li><li><strong>KNN = Find Neighbours.</strong></li></ul><h3>Real-Life Applications</h3><ul><li>Customer segmentation.</li><li>News/article clustering.</li><li>Image compression.</li><li>Image segmentation.</li><li>Market basket grouping.</li><li>Recommendation systems (as a preprocessing step).</li><li>Document clustering.</li></ul><h3>Questions I Should Be Able to Answer</h3><h3>Q1. Why is K-Means unsupervised?</h3><p>Because it uses <strong>only the features (X)</strong> and never looks at labels (y).</p><h3>Q2. Why is StandardScaler important?</h3><p>Because K-Means is distance-based, and features on larger scales can dominate the distance calculation.</p><h3>Q3. Why is K-Means sensitive to outliers?</h3><p>Outliers can pull the centroid toward themselves since the centroid is the <strong>mean</strong> of the cluster.</p><h3>Q4. What is WCSS?</h3><p>The sum of squared distances between each point and its assigned centroid.</p><p>Lower WCSS means more compact clusters.</p><h3>Q5. Why use K-Means++?</h3><p>To choose better initial centroids, reducing the chance of poor clustering and speeding up convergence.</p><h3>K-MEANS Inshort</h3><ul><li>K = number of clusters.</li><li>Centroid = mean of a cluster.</li><li>Initialize K centroids.</li><li>Assign each point to the nearest centroid.</li><li>Recompute centroids using the mean.</li><li>Repeat until centroids stop moving.</li><li>Use <strong>WCSS + Elbow Method</strong> to estimate K.</li><li>Validate using <strong>Silhouette Score</strong>.</li><li>Standardize features before K-Means.</li><li>K-Means++ chooses smarter initial centroids.</li><li>K-Means is <strong>unsupervised</strong> because it never uses labels.</li></ul><p><strong>K-Means = “Randomly (or smartly) initialize K centroids, repeatedly assign each point to the nearest centroid, move the centroids to the mean of their assigned points, and stop when the centroids no longer change.”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a12b42510317" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PCA]]></title>
            <link>https://medium.com/@ankitamohanty1919191/pca-d58091bf2543?source=rss-b12caf5915c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d58091bf2543</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[apc]]></category>
            <dc:creator><![CDATA[Ankita Mohanty]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 15:02:57 GMT</pubDate>
            <atom:updated>2026-08-19T15:02:57.989Z</atom:updated>
            <content:encoded><![CDATA[<p>I learnt PCA (Principal Component Analysis). Initially I was confused because it is called an “algorithm”, but it does not directly predict classes like Logistic Regression or Random Forest. It is mainly used for Dimensionality Reduction.</p><h3>1. Curse of Dimensionality</h3><h3>Dimensions ↔ Features</h3><p>In ML, dimension = feature/column.</p><p>Example:</p><ul><li>Age</li><li>Salary</li><li>BMI</li><li>Glucose</li><li>Blood Pressure</li></ul><p>If a dataset has 500 columns, it is a 500-dimensional dataset.</p><h3>Analogy</h3><p>Suppose I search for a phone and add filters:</p><ul><li>Brand = Samsung</li><li>RAM = 12GB</li><li>Storage = 256GB</li><li>Color = Blue</li><li>Price &lt; 30k</li><li>AMOLED</li><li>120Hz</li></ul><p>As I keep adding conditions, the number of available options becomes very small.</p><p>Similarly, as dimensions increase, data points become sparse in the feature space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RuZ9_-By4A7wpcmT" /></figure><h3>Model Accuracy Example</h3><p>Suppose we have 500 features.</p><ul><li>Model 1 → 3 features → accuracy = 70%</li><li>Model 2 → 6 features → 78%</li><li>Model 3 → 10 features → 82%</li><li>Model 4 → 50 features → 79%</li><li>Model 5 → 100 features → 74%</li><li>Model 6 → 500 features → 68%</li></ul><p>Initially, adding useful features improves performance.</p><p>After a point, adding too many features introduces:</p><ul><li>Noise</li><li>Redundant information</li><li>Overfitting</li><li>Increased computation</li></ul><p>So the issue is not simply “more features = bad”.</p><p>The issue is too many irrelevant or redundant features.</p><p>This phenomenon is called the Curse of Dimensionality.</p><h3>How to Reduce the Curse?</h3><p>Two main approaches:</p><h3>A. Feature Selection</h3><p>Choose only the important existing features.</p><p>Example:</p><p>From 500 features, keep only the top 20 important ones.</p><h3>B. Dimensionality Reduction / Feature Extraction</h3><p>Create new features by combining existing features.</p><p>This is where PCA comes in.</p><h3>2. Feature Selection vs Feature Extraction</h3><h3>Why do we perform Dimensionality Reduction?</h3><h3>1. Prevent Curse of Dimensionality</h3><p>Fewer dimensions → simpler model.</p><h3>2. Improve Model Performance</h3><p>Less noise and redundancy.</p><h3>3. Visualize Data</h3><p>Humans can easily visualize 2D or 3D data, not 500D data.</p><h3>Feature Selection</h3><p>If a feature is related to the output variable, it is potentially important.</p><p>We often check this using correlation.</p><p>r=Cov(X,Y)/σXσY</p><h3>Interpretation</h3><ul><li>r &gt; 0 → Positive relationship.</li><li>r &lt; 0 → Negative relationship.</li><li>r ≈ 0 → Little or no linear relationship.</li></ul><p>So features with very low correlation may be candidates for removal.</p><h3>Feature Extraction (PCA)</h3><p>Suppose two features are highly related:</p><ul><li>Height in cm</li><li>Height in inches</li></ul><p>Both contain almost the same information.</p><p>Instead of deleting one blindly, PCA can create a new combined feature that captures most of their information.</p><h3>Easy memory</h3><ul><li>Selection = Pick columns.</li><li>Extraction = Create new columns from old columns.</li></ul><h3>3. PCA Geometric Intuition</h3><p>Imagine data points on a 2D graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*S8DiRdA2mOoZpNlk" /></figure><h3>Option 1: Project on X-axis</h3><p>All points become 1D.</p><p>But we may lose important information.</p><h3>PCA Idea</h3><p>Find the direction along which the data varies the most.</p><p>That direction is called the First Principal Component (PC1).</p><ul><li>PC1 captures maximum variance.</li><li>PC2 captures the next maximum variance and is perpendicular to PC1.</li></ul><h3>Why “Maximum Variance”?</h3><p>Variance tells us how spread out the data is.</p><p>A direction with high variance usually contains more information.</p><p>PCA tries to preserve as much information as possible while reducing dimensions.</p><h3>4. PCA Maths Intuition</h3><p>The math sounds scary, but the flow is simple.</p><h3>Standardized Data</h3><p>↓</p><h3>Covariance Matrix</h3><p>↓</p><h3>Eigen Decomposition</h3><p>↓</p><h3>Eigenvalues + Eigenvectors</h3><p>↓</p><h3>Select Top Components</h3><p>↓</p><h3>Project Data</h3><h3>Eigenvalues and Eigenvectors</h3><p>Suppose we compute the covariance matrix.</p><p>Then we find:</p><ul><li>Eigenvectors → Directions in space.</li><li>Eigenvalues → Amount of variance captured in that direction.</li></ul><h3>Important intuition</h3><ul><li>Eigenvector = direction.</li><li>Eigenvalue = importance of that direction.</li></ul><p>The eigenvector with the largest eigenvalue becomes PC1 because it captures the highest variance.</p><p>Eigenvalues decide how much variance is captured, not the magnitude of eigenvectors.</p><p>Eigenvectors are usually normalized to unit length.</p><p>So :</p><p>Highest Eigenvalue → Most Important Principal Component.</p><h3>5. Eigen Decomposition on Covariance Matrix</h3><h3>Step-by-Step</h3><h3>Step A: Standardize the Data</h3><p>If one feature is in thousands and another in decimals, the large-scale feature dominates the variance.</p><p>So we use StandardScaler.</p><p>z=(x−μ)/σ</p><h3>Step B: Compute Covariance Matrix</h3><p>Covariance measures how features vary together.</p><p>For two features:</p><p>Cov(X,Y)=∑(xi−xˉ)(yi−yˉ)/n−1</p><h3>Step C: Find Eigenvalues and Eigenvectors</h3><p>From the covariance matrix, we compute:</p><ul><li>Eigenvectors (directions)</li><li>Eigenvalues (variance captured)</li></ul><h3>Principal Components</h3><p>Suppose:</p><p>Component{PC1,PC2,PC3,PC4}</p><p>Variance{70%,20%,5%,5%}</p><p>If we keep only PC1 and PC2, we still retain 90% of the information.</p><p>This is the significance of PCA.</p><h3>What Does “Projection” Mean?</h3><p>After selecting PC1 and PC2, we project every data point onto these new axes.</p><p>Mathematically:</p><p>Z=XW</p><p>Where:</p><ul><li>X = standardized data</li><li>W = matrix of selected eigenvectors</li><li>Z = transformed lower-dimensional data</li></ul><p>This is the linear transformation performed by PCA.</p><h3>The One Sentence That Explains PCA</h3><p>PCA finds a new coordinate system where the first axis captures maximum variance, the second captures the next maximum variance, and then projects the data onto the most informative axes.</p><h3>6. PCA on (Breast Cancer Dataset)</h3><h3>Workflow</h3><p>Import Libraries</p><p>↓</p><p>Load Dataset</p><p>↓</p><p>Standardize Data</p><p>↓</p><p>Apply PCA</p><p>↓</p><p>Transform Data</p><p>↓</p><p>Check Explained Variance</p><p>↓</p><p>Visualize</p><h3>Import Libraries</h3><p>import numpy as np</p><p>import pandas as pd</p><p>import matplotlib.pyplot as plt</p><p>import seaborn as sns</p><h3>Load Dataset</h3><p>from sklearn.datasets import load_breast_cancer</p><p>data = load_breast_cancer()</p><p>X = data.data</p><p>y = data.target</p><h3>Standardization</h3><p>from sklearn.preprocessing import StandardScaler</p><p>scaler = StandardScaler()</p><p>X_scaled = scaler.fit_transform(X)</p><p>Save this as scaled data because PCA should generally be applied on standardized features.</p><h3>Apply PCA</h3><p>from sklearn.decomposition import PCA</p><p>pca = PCA(n_components=2)</p><p>X_pca = pca.fit_transform(X_scaled)</p><h3>What does n_components=2 mean?</h3><p>Reduce the original 30 features to 2 principal components.</p><h3>Explained Variance</h3><p>pca.explained_variance_ratio_</p><p>Example output:</p><p>[0.44, 0.19]</p><p>Meaning:</p><ul><li>PC1 captures 44% variance.</li><li>PC2 captures 19% variance.</li></ul><p>Total retained variance = 63%.</p><h3>Scatter Plot</h3><p>plt.scatter(X_pca[:,0], X_pca[:,1], c=y)</p><p>plt.xlabel(‘PC1’)</p><p>plt.ylabel(‘PC2’)</p><p>plt.show()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ocKJuqsDZqhjjJUG" /></figure><p>We can visually see how 30-dimensional data is represented in 2D.</p><h3>Is PCA a Prediction Model?</h3><p>No.</p><p>PCA does not predict labels.</p><p>It does not output:</p><ul><li>spam/not spam</li><li>diabetic/not diabetic</li><li>house price</li></ul><p>Instead, it outputs new transformed features.</p><h3>Then How Is It Used With ML Models?</h3><p>Think of PCA as a preprocessing step.</p><h3>Original Pipeline</h3><p>Raw Data</p><p>↓</p><p>Train Random Forest</p><h3>PCA Pipeline</h3><p>Raw Data</p><p>↓</p><p>Standardization</p><p>↓</p><p>PCA</p><p>↓</p><p>Reduced Data</p><p>↓</p><p>Train Random Forest</p><p>So the actual predictive model is still Random Forest, SVM, Logistic Regression, etc.</p><p>PCA only changes the input representation.</p><h3>Example</h3><p>Suppose we have 500 features.</p><p>Without PCA:</p><p>500 features → SVM</p><p>With PCA:</p><p>500 features → PCA → 20 principal components → SVM</p><p>The SVM is trained on the 20 principal components, not on the original 500 features.</p><p>This often makes training:</p><ul><li>Faster</li><li>Less noisy</li><li>Less prone to overfitting</li></ul><h3>Why Is PCA Unsupervised?</h3><p>Because PCA uses only X (features).</p><p>It never looks at y (labels).</p><h3>PCA sees:</h3><ul><li>feature values</li><li>covariance</li><li>variance</li><li>directions of spread</li></ul><h3>PCA does NOT see:</h3><ul><li>class labels</li><li>target values</li><li>output categories</li></ul><p>That is the exact definition of unsupervised learning.</p><h3>Compare with Supervised Algorithms</h3><p>Algorithm{Logistic Regression,Random Forest,XGBoost,PCA}</p><p>Uses y?{Yes,Yes,Yes,No}</p><p>Since PCA ignores labels, it belongs to Unsupervised Learning.</p><h3>Important QUES.</h3><h3>“Can PCA improve classification accuracy?”</h3><p>Yes, indirectly.</p><p>PCA may improve accuracy by:</p><ul><li>removing noise,</li><li>reducing multicollinearity,</li><li>reducing overfitting,</li><li>simplifying the feature space.</li></ul><p>But it can also reduce accuracy if important label-related information is discarded.</p><p>So PCA is not guaranteed to improve performance.</p><h3>Another Important Point</h3><h3>PCA vs Feature Selection</h3><h3>Feature Selection</h3><p>Keeps original columns.</p><p>Example:</p><p>Keep Age, BMI, Glucose.</p><h3>PCA</h3><p>Creates new columns.</p><p>Example:</p><ul><li>PC1 = 0.5×Age + 0.7×BMI + 0.2×Glucose</li><li>PC2 = …</li></ul><p>The original features are transformed into new components.</p><h3>PCA inshort</h3><ul><li>Curse of dimensionality = too many features → sparse data, noise, overfitting.</li><li>Feature Selection = choose important existing columns.</li><li>Feature Extraction = create new features from old ones.</li><li>PCA finds directions of maximum variance.</li><li>Standardize → Covariance Matrix → Eigenvalues/Eigenvectors → Select top PCs → Project data.</li><li>Highest eigenvalue = most informative component.</li><li>Explained variance tells how much information is retained.</li><li>PCA is a preprocessing / dimensionality reduction technique.</li><li>PCA is unsupervised because it never uses the target variable y.</li><li>Final ML model (SVM, RF, XGBoost, etc.) is trained on the principal components, not by PCA itself.</li></ul><p>PCA = “Find the directions that capture the maximum variance in the data, keep the most informative directions, and project the original high-dimensional data onto this lower-dimensional space before training the actual ML model.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d58091bf2543" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XGBoost]]></title>
            <link>https://medium.com/@ankitamohanty1919191/xgboost-6acd6be50885?source=rss-b12caf5915c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6acd6be50885</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Ankita Mohanty]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 09:25:09 GMT</pubDate>
            <atom:updated>2026-08-12T09:25:09.726Z</atom:updated>
            <content:encoded><![CDATA[<p>XGBoost = Optimized Gradient Boosting where each new tree is built using gradients, regularization, and a gain-based splitting strategy.</p><h3>Decision Tree</h3><p>One tree.</p><h3>Random Forest</h3><p>Many trees in parallel → averaging.</p><h3>Gradient Boosting</h3><p>Trees sequentially correct residuals.</p><h3>XGBoost</h3><p>Gradient Boosting + speed + regularization + smarter tree construction.</p><p>So whenever I hear XGBoost, I should think:</p><p>“Gradient Boosting on steroids”</p><p>XD</p><h3>1. XGBoost Classification (In-Depth Intuition)</h3><p>Suppose we want to classify Spam vs Not Spam.</p><h3>Step 1: Base Model</h3><p>XGBoost does not start with a random tree.</p><p>For binary classification, it starts with a constant prediction based on the overall probability of the positive class.</p><p>Example:</p><ul><li>70% emails are spam.</li><li>Initial probability = 0.7 for every sample.</li></ul><p>This constant is called the base score.</p><h3>Easy memory</h3><p>Regression → Start with mean</p><p>Classification → Start with class probability</p><h3>Step 2: Convert Probability to Log-Odds</h3><p>Internally, XGBoost works with log-odds (logits).</p><p>Probability = 0.7</p><p>↓</p><p>Logit = log(p / (1-p))</p><p>The model adds trees in the logit space, not directly on probabilities.</p><p>This is why the final step uses the Sigmoid Activation.</p><h3>Step 3: Compute Gradients (Errors)</h3><p>Instead of simple residuals, XGBoost computes:</p><ul><li>Gradient (g) → direction of error.</li><li>Hessian (h) → curvature / confidence of that error.</li></ul><p>Think:</p><h3>Gradient</h3><p>“Which direction should the prediction move?”</p><h3>Hessian</h3><p>“How strongly should it move?”</p><p>This is the biggest difference from basic Gradient Boosting.</p><h3>Similarity Weights (Leaf Weights)</h3><p>This is the part most students forget.</p><p>After constructing a tree, XGBoost calculates a score for each leaf.</p><h3>Formula (conceptual)</h3><p>w=−∑gi/∑hi+λ</p><p>Where:</p><ul><li>gᵢ = gradients of samples in that leaf.</li><li>hᵢ = Hessians.</li><li>λ = regularization term.</li></ul><h3>Intuition</h3><p>The leaf prediction depends on:</p><ul><li>Total error in that region.</li><li>Confidence of that error.</li><li>Penalty for making the leaf too extreme.</li></ul><h3>Why is it called Similarity Weight?</h3><p>Samples with similar gradient behavior are grouped into the same leaf.</p><p>The leaf gets a weight that best reduces the loss for that group.</p><h3>Easy recall</h3><p>Leaf weight = “How much correction should this region add to the prediction?”</p><h3>Step 4: Sigmoid Activation</h3><p>After all trees are added, we get a final logit score.</p><p>To convert it into a probability, XGBoost applies the Sigmoid (Logistic) Function.</p><p>p=11+e−z</p><p>This squashes any value into 0–1.</p><h3>Final Prediction</h3><ul><li>Probability ≥ 0.5 → Class 1</li><li>Probability &lt; 0.5 → Class 0</li></ul><h3>Classification memory flow</h3><ul><li>Base probability</li><li>Convert to log-odds</li><li>Compute gradients + Hessians</li><li>Build a tree</li><li>Compute leaf weights</li><li>Update predictions</li><li>Repeat</li><li>Apply sigmoid</li><li>Get final class probability</li></ul><h3>2. XGBoost Regressor</h3><p>This is easier because it is closer to Gradient Boosting.</p><p>Suppose we are predicting house prices.</p><h3>Step 1: Base Model</h3><p>Start with the mean of the target.</p><p>Example:</p><p>Actual prices = [100, 150, 200]</p><p>Mean = 150</p><p>Initial prediction for every sample = 150.</p><h3>Step 2: Compute Residuals</h3><p>Residual = Actual − Predicted</p><p>House {A,B,C}</p><p>Actual {100,150,200}</p><p>Predicted {150,150,150}</p><p>Residual {–50,0,+50}</p><p>These residuals become the target for the next tree.</p><h3>Step 3: Construct a Decision Tree</h3><p>XGBoost builds a shallow tree that tries to explain these residuals.</p><p>But unlike ordinary Gradient Boosting, it uses gradients and Hessians to decide splits.</p><h3>Calculate Gain (Very Important)</h3><p>This is the heart of XGBoost.</p><h3>What is Gain?</h3><p>Gain tells us:</p><p>“If I split this node, how much will the loss decrease?”</p><p>XGBoost computes gain using gradients and Hessians.</p><h3>Conceptual formula</h3><p>Gain=1/2[GL^2/HL+λ+GR^2/HR+λ−G^2/H+λ]−γ</p><p>Do I need to memorize the whole formula?</p><p>No.</p><p>I just need to remember what each term means.</p><h3>Meaning of Terms</h3><ul><li>G = sum of gradients.</li><li>H = sum of Hessians.</li><li>L / R = left and right child.</li><li>λ = L2 regularization.</li><li>γ = minimum gain required to make a split.</li></ul><h3>Intuition</h3><p>A split is chosen only if:</p><p>Reduction in loss &gt; Complexity penalty</p><p>This is why XGBoost avoids creating unnecessary branches.</p><h3>Why XGBoost Trees Are Better Than Normal Trees</h3><p>Normal Decision Tree:</p><ul><li>Split based on Gini/Entropy.</li><li>Can grow greedily.</li></ul><p>XGBoost Tree:</p><ul><li>Split based on gain.</li><li>Includes regularization.</li><li>Considers both first-order and second-order information.</li></ul><p>This usually gives better generalization.</p><h3>Visual Memory for Gain</h3><p>Imagine a node with mixed errors.</p><h3>Before split</h3><p>Error = 100</p><h3>After split</h3><p>Left error = 30</p><p>Right error = 20</p><p>Total after = 50</p><h3>Gain</h3><p>100 − 50 = 50</p><p>If gain is large, keep the split.</p><p>If gain is tiny, do not split.</p><p>That is the intuitive meaning of the formula.</p><h3>Why XGBoost Is So Powerful</h3><p>It combines three ideas together.</p><h3>Gradient boosting</h3><p>Sequentially corrects residual errors.</p><h3>Second-order optimization</h3><p>Uses both gradients and Hessians for smarter updates.</p><h3>Regularization</h3><p>Penalizes overly complex trees to reduce overfitting.</p><p>Memory sentence: “Gradient + Hessian + Regularization = XGBoost.”</p><h3>3. Model Training (Classification)</h3><h3>Workflow</h3><p>Dataset</p><p>↓</p><p>Train-Test Split</p><p>↓</p><p>Initialize XGBClassifier</p><p>↓</p><p>Fit</p><p>↓</p><p>Predict</p><p>↓</p><p>Evaluate</p><h3>Practical Code</h3><pre>from xgboost import XGBClassifier</pre><pre>model = XGBClassifier(<br>    n_estimators=100,<br>    learning_rate=0.1,<br>    max_depth=3,<br>    subsample=0.8,<br>    colsample_bytree=0.8,<br>    random_state=42<br>)</pre><pre>model.fit(X_train, y_train)</pre><pre>y_pred = model.predict(X_test)<br>y_prob = model.predict_proba(X_test)</pre><h3>Important Metrics</h3><ul><li>Accuracy</li><li>Precision</li><li>Recall</li><li>F1 Score</li><li>ROC-AUC</li></ul><h3>Model Training (Regression)</h3><h3>Workflow</h3><p>Dataset</p><p>↓</p><p>Train-Test Split</p><p>↓</p><p>Initialize XGBRegressor</p><p>↓</p><p>Fit</p><p>↓</p><p>Predict</p><p>↓</p><p>Evaluate</p><h3>Practical Code</h3><pre>from xgboost import XGBRegressor</pre><pre>model = XGBRegressor(<br>    n_estimators=200,<br>    learning_rate=0.05,<br>    max_depth=4,<br>    subsample=0.8,<br>    colsample_bytree=0.8,<br>    random_state=42<br>)</pre><pre>model.fit(X_train, y_train)</pre><pre>y_pred = model.predict(X_test)</pre><h3>Metrics</h3><ul><li>MAE</li><li>MSE</li><li>RMSE</li><li>R²</li></ul><h3>Hyperparameters I Must Remember</h3><p>Parameter {n_estimators, learning_rate, max_depth, subsample, colsample_bytree, gamma, reg_alpha, reg_lambda}</p><p>Meaning {Number of trees, Contribution of each tree, Tree complexity, Fraction of rows sampled, Fraction of features sampled, Minimum gain required for a split, L1 regularization, L2 regularization}</p><h3>The Most Important Relationship</h3><h3>Learning Rate vs Trees</h3><ul><li>Small learning rate → More trees.</li><li>Large learning rate → Fewer trees.</li></ul><p>A very common good combination is:</p><ul><li>learning_rate = 0.05</li><li>n_estimators = 200+</li></ul><h3>XGBoost vs Gradient Boosting</h3><p>This is a favorite interview question.</p><p>Gradient Boosting{Uses gradients, Basic regularization, Slower, Simple implementation, No automatic missing handling}</p><p>XGBoost{Uses gradients + Hessians, Strong regularization, Highly optimized, Production-grade implementation, Handles missing values internally}</p><h3>One-line answer</h3><p>XGBoost is an optimized, regularized, second-order version of Gradient Boosting.</p><h3>Why XGBoost Often Wins Competitions</h3><p>Because it includes:</p><ul><li>Tree pruning</li><li>Regularization</li><li>Column sampling</li><li>Row sampling</li><li>Parallel computation</li><li>Cache optimization</li><li>Missing value handling</li><li>Second-order optimization</li></ul><p>So it usually achieves high accuracy with good speed.</p><h3>The “Doctor” Analogy</h3><p>Imagine a doctor treating a patient.</p><h3>Visit 1</h3><p>Gives a general medicine (base prediction).</p><h3>Patient still has symptoms.</h3><p>Doctor studies the remaining symptoms (residuals).</p><h3>Visit 2</h3><p>Gives a medicine targeting those symptoms.</p><h3>Some symptoms remain.</h3><p>Doctor targets the remaining symptoms again.</p><p>Each visit is a new tree.</p><p>The final recovery is the sum of all corrections.</p><p>That is exactly XGBoost.</p><h3>Questions I Should Be Able to Answer</h3><h3>Q1: What is the biggest difference between Gradient Boosting and XGBoost?</h3><p>XGBoost uses second-order gradients (Hessians) and adds regularization and optimized tree construction.</p><h3>Q2: What is Gain?</h3><p>Gain is the reduction in loss obtained by making a split.</p><h3>Q3: What is the role of gamma?</h3><p>Gamma is the minimum gain required to create a new split; it helps control tree complexity.</p><h3>Q4: Why are Hessians useful?</h3><p>They provide curvature information, allowing more accurate optimization steps.</p><h3>Q5: Why does XGBoost use sigmoid in binary classification?</h3><p>Because the model outputs logits, and sigmoid converts logits into probabilities between 0 and 1.</p><h3>XGBoost inshort</h3><ul><li>Start with a base prediction (mean or class probability).</li><li>Compute gradients and Hessians.</li><li>Build a tree that maximizes gain.</li><li>Compute leaf/similarity weights.</li><li>Update predictions.</li><li>Repeat sequentially.</li><li>Classification → apply sigmoid to get probabilities.</li><li>Regression → directly sum tree outputs.</li><li>Key hyperparameters → n_estimators, learning_rate, max_depth, gamma.</li><li>Main idea → Gradient Boosting + Hessians + Regularization + Gain-based splits.</li></ul><p>XGBoost = “Build trees sequentially on gradients and Hessians, choose splits using gain, regularize the tree complexity, and keep adding weighted corrections until the loss becomes minimal.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6acd6be50885" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradient Boosting]]></title>
            <link>https://medium.com/@ankitamohanty1919191/gradient-boosting-20e80567c331?source=rss-b12caf5915c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/20e80567c331</guid>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ankita Mohanty]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 08:29:54 GMT</pubDate>
            <atom:updated>2026-08-12T08:29:54.920Z</atom:updated>
            <content:encoded><![CDATA[<p>The easiest sentence to remember is:</p><p>Random Forest builds many trees independently. Gradient Boosting builds trees sequentially where each new tree tries to correct the remaining error of the previous trees.</p><p>That is the whole algorithm in one line.</p><h3>First connect AdaBoost → Gradient Boosting</h3><p>I used to get confused between these two.</p><p>AdaBoost{Focuses on wrongly classified samples, Changes sample weights, Usually uses stumps, Weighted voting}</p><p>Gradient Boosting{Focuses on residual errors, Fits a new model on the residuals, Usually uses shallow decision trees, Additive model (prediction + correction)}</p><ul><li>AdaBoost = “Increase weight of mistakes.”</li><li>Gradient Boosting = “Predict the mistakes (residuals).”</li></ul><h3>1. Gradient Boosting Regression</h3><p>This is the core algorithm. Once I understand regression, classification becomes much easier.</p><h3>The Main Intuition</h3><p>Suppose we are predicting house prices.</p><p>Actual prices:</p><p>House {A, B, C}</p><p>Actual {100, 150, 200}</p><h3>Step 1: Start with a very simple prediction</h3><p>Gradient Boosting first predicts a constant value.</p><p>For regression, the best constant is usually the mean of the target.</p><p>Mean = (100 + 150 + 200) / 3 = 150</p><p>So initial predictions:</p><p>House {A, B, C}</p><p>Actual {100, 150, 200}</p><p>Predicted {150, 150, 150}</p><h3>Step 2: Find the Residuals (Errors)</h3><p>Residual = Actual − Predicted</p><p>House{A, B, C}</p><p>Residual{-50, 0, +50}</p><p>These residuals are the mistakes made by the current model.</p><p>This is the key point of Gradient Boosting.</p><p>The next tree is not trained on the original target.</p><p>It is trained on the residuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/0*PguD9NTWd4ABfM_c" /></figure><h3>Step 3: Train a Tree on Residuals</h3><p>A shallow decision tree learns patterns in:</p><p>-50, 0, +50</p><p>Suppose it predicts:</p><p>House{A, B, C}</p><p>Residual Prediction{-40, 5, 45}</p><h3>Step 4: Update the Predictions</h3><p>New prediction = Old prediction + Learning Rate × Residual Prediction</p><p>Suppose learning rate = 0.1</p><p>For House A:</p><p>150 + 0.1 × (-40) = 146</p><p>For House C:</p><p>150 + 0.1 × 45 = 154.5</p><p>See what happened:</p><ul><li>Prediction for A moved downward.</li><li>Prediction for C moved upward.</li><li>The model became slightly better.</li></ul><h3>Step 5: Repeat</h3><p>Compute new residuals.</p><p>Train another tree on those residuals.</p><p>Add its correction.</p><p>Repeat many times.</p><h3>The whole process</h3><p>Initial mean</p><p>↓</p><p>Residuals</p><p>↓</p><p>Tree 1 learns residuals</p><p>↓</p><p>Update predictions</p><p>↓</p><p>New residuals</p><p>↓</p><p>Tree 2 learns remaining residuals</p><p>↓</p><p>Update again</p><p>↓</p><p>…</p><p>This is why Gradient Boosting is called Boosting — each tree boosts the performance of the previous ensemble.</p><h3>Why is it called “Gradient” Boosting?</h3><p>This is the mathematical intuition :</p><p>We want to minimize a Loss Function.</p><p>For regression, a common loss is Mean Squared Error (MSE).</p><p>Gradient Boosting moves the predictions in the direction that reduces the loss the fastest, i.e., the negative gradient of the loss function.</p><p>For squared error, the negative gradient turns out to be exactly the residuals (Actual − Predicted).</p><p>So:</p><p>Residuals = Negative Gradient of MSE</p><p>That single sentence is often enough for interviews.</p><h3>Easy Analogy</h3><p>Imagine a teacher checking homework.</p><h3>Attempt 1</h3><p>Student gets many questions wrong.</p><h3>Teacher marks the mistakes.</h3><h3>Attempt 2</h3><p>Student practices only the mistakes.</p><h3>Teacher marks the remaining mistakes.</h3><h3>Attempt 3</h3><p>Student practices the remaining mistakes again.</p><p>After many rounds, the student becomes accurate.</p><p>That is exactly Gradient Boosting.</p><h3>2. Gradient Boosting Classification</h3><p>Now instead of predicting a number, we predict a class.</p><p>The intuition is the same, but the residuals are not simple subtraction.</p><h3>Binary Classification Example</h3><p>Target:</p><ul><li>1 = Spam</li><li>0 = Not Spam</li></ul><h3>Initial Prediction</h3><p>The model starts with the overall probability of the positive class.</p><p>Suppose 70% emails are spam.</p><p>Initial probability = 0.7 for every email.</p><h3>Compute Pseudo-Residuals</h3><p>For classification, we use Log Loss (Cross Entropy).</p><p>The new tree is trained on the negative gradient of the log loss, called pseudo-residuals.</p><h3>Easy memory</h3><ul><li>Regression → Residual = y − ŷ</li><li>Classification → Pseudo-residual = Gradient of log loss</li></ul><h3>Sequential Correction</h3><p>Tree 1: predicts probabilities</p><p>↓</p><p>Find where probabilities are wrong</p><p>↓</p><p>Tree 2: learns those errors</p><p>↓</p><p>Adjust probabilities</p><p>↓</p><p>Tree 3: learns remaining errors</p><p>↓</p><p>Final probability</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F8B8UA-rt1ztnwPU" /></figure><h3>Why Gradient Boosting Works So Well</h3><p>Each tree is intentionally small and weak.</p><p>A single tree cannot memorize the entire dataset.</p><p>But many small corrections added together create a highly accurate model.</p><p>This is the opposite philosophy of a deep decision tree.</p><h3>Important Hyperparameters (Must)</h3><p>These are the parameters interviewers ask most.</p><p>Parameter{n_estimators, learning_rate, max_depth, subsample, min_samples_split}</p><p>Meaning{Number of boosting rounds / trees, How much each tree contributes, Complexity of each tree, Fraction of rows used per tree, Minimum samples to split a node}</p><h3>The Most Important Relationship</h3><h3>Learning Rate vs Number of Trees</h3><p>This is a classic interview question.</p><ul><li>Small learning_rate → Need more trees.</li><li>Large learning_rate → Need fewer trees.</li></ul><p>It’s like:</p><p>Tiny corrections + many steps is usually safer than huge corrections + few steps.</p><h3>3. Model Training — Regression</h3><h3>Workflow</h3><p>Dataset</p><p>↓</p><p>Train-Test Split</p><p>↓</p><p>Initialize GradientBoostingRegressor</p><p>↓</p><p>Fit</p><p>↓</p><p>Predict</p><p>↓</p><p>Evaluate</p><h3>Practical Code</h3><pre>from sklearn.ensemble import GradientBoostingRegressor</pre><pre>gbr = GradientBoostingRegressor(<br>    n_estimators=100,<br>    learning_rate=0.1,<br>    max_depth=3,<br>    random_state=42<br>)</pre><pre>gbr.fit(X_train, y_train)</pre><pre>y_pred = gbr.predict(X_test)</pre><h3>Metrics</h3><ul><li>MAE</li><li>MSE</li><li>RMSE</li><li>R²</li></ul><h3>Model Training — Classification</h3><h3>Workflow</h3><p>Dataset</p><p>↓</p><p>Train-Test Split</p><p>↓</p><p>Initialize GradientBoostingClassifier</p><p>↓</p><p>Fit</p><p>↓</p><p>Predict</p><p>↓</p><p>Evaluate</p><h3>Practical Code</h3><pre>from sklearn.ensemble import GradientBoostingClassifier</pre><pre>gbc = GradientBoostingClassifier(<br>    n_estimators=100,<br>    learning_rate=0.1,<br>    max_depth=3,<br>    random_state=42<br>)</pre><pre>gbc.fit(X_train, y_train)</pre><pre>y_pred = gbc.predict(X_test)<br>y_prob = gbc.predict_proba(X_test)</pre><h3>Metrics</h3><ul><li>Accuracy</li><li>Confusion Matrix</li><li>Precision</li><li>Recall</li><li>F1 Score</li><li>ROC-AUC</li></ul><h3>Visual Memory: How Predictions Improve</h3><p>Think of the model as adding corrections.</p><p>Stage</p><p>Prediction</p><p>Initial</p><p>150</p><ul><li>Tree 1</li></ul><p>146</p><ul><li>Tree 2</li></ul><p>142</p><ul><li>Tree 3</li></ul><p>139</p><p>The prediction gradually moves closer to the actual value.</p><p>That is the easiest way to remember Gradient Boosting.</p><h3>Why Not Use One Huge Tree?</h3><p>A huge tree:</p><ul><li>Memorizes training data.</li><li>Has high variance.</li><li>Overfits.</li></ul><p>Gradient Boosting prefers:</p><ul><li>Many shallow trees.</li><li>Small corrections.</li><li>Better generalization.</li></ul><h3>Gradient Boosting vs Random Forest</h3><p>Random Forest{Bagging, Parallel trees, Reduces variance, Trees are independent, Harder to overfit, Faster to train in parallel}</p><p>Gradient Boosting{Boosting, Sequential trees, Reduces bias, Each tree depends on previous, Can overfit if too many trees, Slower because sequential}</p><h3>Inshort:</h3><p>Random Forest averages many independent trees; Gradient Boosting adds many dependent trees that sequentially correct errors.</p><h3>Overfitting in Gradient Boosting</h3><p>Yes, it can overfit.</p><p>Signs:</p><ul><li>Training score keeps increasing.</li><li>Validation score starts decreasing.</li></ul><h3>Control it using</h3><ul><li>Lower max_depth</li><li>Lower learning_rate</li><li>Fewer n_estimators</li><li>Use subsample &lt; 1.0</li><li>Early stopping</li></ul><h3>Where XGBoost Comes In</h3><p>Gradient Boosting is the base idea.</p><p>XGBoost = Extreme Gradient Boosting, which adds:</p><ul><li>Regularization</li><li>Faster optimization</li><li>Parallelization of some computations</li><li>Better handling of missing values</li><li>Tree pruning</li><li>Second-order gradients</li></ul><p>So:</p><p>Gradient Boosting → XGBoost is an advanced optimized version.</p><h3>QNA:</h3><h3>Q1: What does each new tree learn?</h3><p>The residual errors (negative gradients) of the current ensemble.</p><h3>Q3: What is the role of learning rate?</h3><p>It controls the contribution of each tree to the final prediction.</p><h3>Q4: Why are trees usually shallow?</h3><p>To keep each learner weak and prevent overfitting.</p><h3>Q5: Difference between AdaBoost and Gradient Boosting?</h3><p>AdaBoost reweights samples; Gradient Boosting fits new trees on residual errors.</p><h3>Gradient Boosting Inshort</h3><ul><li>Start with a simple prediction (mean for regression).</li><li>Compute residuals/errors.</li><li>Train a shallow tree on residuals.</li><li>Add the tree’s prediction to the current model.</li><li>Repeat sequentially.</li><li>Regression → residuals = y − ŷ.</li><li>Classification → pseudo-residuals from log loss.</li><li>Key parameters → n_estimators, learning_rate, max_depth.</li><li>Small learning rate → more trees.</li><li>Random Forest = parallel averaging; Gradient Boosting = sequential error correction.</li></ul><p>Basically:</p><p>Gradient Boosting = “Start with a simple model, repeatedly predict the remaining errors using shallow trees, and add those corrections until the overall loss becomes very small.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20e80567c331" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adaboost Algorithm]]></title>
            <link>https://medium.com/@ankitamohanty1919191/adaboost-algorithm-5ac7c1f2d396?source=rss-b12caf5915c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ac7c1f2d396</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[adaboost-algorithm]]></category>
            <dc:creator><![CDATA[Ankita Mohanty]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 16:40:16 GMT</pubDate>
            <atom:updated>2026-07-27T16:40:16.974Z</atom:updated>
            <content:encoded><![CDATA[<p>“One weak model makes mistakes → the next model is forced to focus more on those mistakes.”</p><p>This single sentence is the whole intuition.</p><h3>1. Intro</h3><p>AdaBoost = Adaptive Boosting</p><ul><li>It is a Boosting algorithm.</li><li>It combines many weak learners to create one strong learner.</li><li>The weak learner is usually a Decision Tree Stump.</li></ul><h3>What is a Decision Tree Stump?</h3><p>A stump is a Decision Tree of depth = 1.</p><p>It can make only one split.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9L7zDgLr-j4YE_Ui" /></figure><p>Example:</p><pre>If Glucose &amp;gt; 120 → Diabetic<br>Else → Non-Diabetic</pre><p>Only one question is asked.</p><p>So each stump is very weak, but AdaBoost combines many such stumps.</p><h3>Random Forest vs AdaBoost</h3><h3>Random Forest</h3><p>Many trees work independently and then vote.</p><h3>AdaBoost</h3><p>Trees work one after another, and each new tree learns from previous mistakes.</p><h3>2. Maths Intuition</h3><p>I remember AdaBoost using 5 steps.</p><ul><li>Create a stump.</li><li>Measure its performance.</li><li>Update weights.</li><li>Normalize weights.</li><li>Sample data for the next stump.</li></ul><h3>Step 1: Creating a Decision Tree Stump</h3><p>Initially, all data points get equal importance.</p><p>Suppose we have 10 samples.</p><p>Each sample gets weight:</p><p>wi=1/10=0.1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*30c_jCF9dVj1RuUS" /></figure><p>Then we train the first stump.</p><h3>Step 2: Performance of the Decision Tree Stump</h3><p>The stump predicts the training data.</p><p>Some points are:</p><ul><li>Correctly classified</li><li>Incorrectly classified</li></ul><p>Suppose it misclassifies 2 out of 10 points.</p><h3>Weighted Error</h3><p>AdaBoost does not count just the number of mistakes.</p><p>It uses the sum of weights of misclassified samples.</p><p>error=∑wi (for wrong predictions)</p><p>If the wrong points have weights 0.1 and 0.1:</p><p>error=0.2</p><h3>Step 3: Calculate Model Importance (Alpha)</h3><p>This is the magic step.</p><p>The stump gets a score called Alpha.</p><p>α=1/2ln⁡(1−error/error)</p><h3>Intuition</h3><ul><li>Small error → Large alpha</li><li>Large error → Small alpha</li></ul><p>So a better stump gets more voting power.</p><p>Example:</p><p>error=0.2</p><p>α=1/2ln⁡(0.8/0.2)=0.693</p><p>This stump is fairly good.</p><h3>How to Remember Alpha</h3><p>Think:</p><p>Less error → More confidence → Bigger alpha</p><h3>Step 4: Updating Weights</h3><p>This is where “Adaptive” comes from.</p><h3>Correctly Predicted Samples</h3><p>Their weights are decreased.</p><h3>Incorrectly Predicted Samples</h3><p>Their weights are increased.</p><p>Why?</p><p>Because we want the next stump to pay more attention to the difficult records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*jBw8jEvo4OMk4dZL" /></figure><h3>“Assigning Bins”</h3><p>What actually happens is:</p><p>After updating weights, we create a probability distribution from those weights.</p><p>Higher weight = higher probability of being selected for the next training set.</p><p>So “bins” can be remembered as:</p><p>Weight → Probability region → Sampling chance</p><h3>Step 5: Normalizing Weights</h3><p>After updating, weights may not sum to 1.</p><p>So we divide each weight by the total weight.</p><p>wi=wi/∑wi</p><p>Now all weights again form a valid probability distribution.</p><p>Example:</p><p>Before normalization:</p><p>[0.05, 0.05, 0.25, 0.25, 0.10]</p><p>Sum = 0.70</p><p>After normalization:</p><p>[0.071, 0.071, 0.357, 0.357, 0.143]</p><p>We should notice how the wrong samples now have much larger probabilities.</p><h3>Selecting New Data Points for the Next Tree</h3><p>Using the normalized weights, we perform weighted sampling.</p><p>Misclassified points are more likely to appear in the next dataset.</p><p>Correct points may appear fewer times.</p><p>This is the exact reason why AdaBoost gradually focuses on difficult examples.</p><h3>The Whole Algorithm in One Flow</h3><ul><li>Equal weights</li><li>Train stump</li><li>Find weighted error</li><li>Compute alpha</li><li>Increase wrong weights</li><li>Decrease correct weights</li><li>Normalize</li><li>Sample next dataset</li><li>Repeat</li></ul><h3>3. Final Prediction for AdaBoost</h3><p>After training many stumps, we do not simply take majority vote.</p><p>Each stump has a different alpha, so its vote has a different strength.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pXo--Kf4L2dB5Om8" /></figure><p>Suppose:</p><p>StumpPredictionAlphaTree 1+10.8Tree 2+10.6Tree 3–10.2</p><p>Final score:</p><p>0.8(+1)+0.6(+1)+0.2(−1)=1.20.8(+1)+0.6(+1)+0.2(-1)=1.20.8(+1)+0.6(+1)+0.2(−1)=1.2</p><p>Since the result is positive, the final class is +1.</p><h3>Easy Recall</h3><p>AdaBoost = Weighted Voting</p><ul><li>Good stump → Bigger vote.</li><li>Bad stump → Smaller vote.</li></ul><h3>4. AdaBoost Model Training (Classification)</h3><h3>Workflow</h3><p>Dataset</p><p>↓</p><p>Train-Test Split</p><p>↓</p><p>Initialize AdaBoostClassifier</p><p>↓</p><p>Fit</p><p>↓</p><p>Predict</p><p>↓</p><p>Evaluate</p><h3>Practical Code</h3><pre>from sklearn.ensemble import AdaBoostClassifier<br>from sklearn.tree import DecisionTreeClassifier</pre><pre>base = DecisionTreeClassifier(max_depth=1)</pre><pre>model = AdaBoostClassifier(<br>    estimator=base,<br>    n_estimators=50,<br>    learning_rate=1.0,<br>    random_state=42<br>)</pre><pre>model.fit(X_train, y_train)</pre><pre>y_pred = model.predict(X_test)</pre><h3>Important Parameters</h3><h3>estimator</h3><p>The weak learner (usually a stump).</p><h3>n_estimators</h3><p>Number of weak learners.</p><p>More estimators → more boosting rounds.</p><h3>learning_rate</h3><p>Controls how much each learner contributes.</p><ul><li>Small → slower learning.</li><li>Large → aggressive learning.</li></ul><h3>AdaBoost for Regression</h3><p>Yes, AdaBoost can also perform Regression.</p><p>The idea is similar:</p><ul><li>Train weak regressors sequentially.</li><li>Focus more on samples with large prediction errors.</li><li>Combine predictions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gQcf9kL43hYGpRfh" /></figure><h3>Code</h3><pre>from sklearn.ensemble import AdaBoostRegressor<br>from sklearn.tree import DecisionTreeRegressor</pre><pre>base = DecisionTreeRegressor(max_depth=3)</pre><pre>model = AdaBoostRegressor(<br>    estimator=base,<br>    n_estimators=100,<br>    learning_rate=0.1,<br>    random_state=42<br>)</pre><pre>model.fit(X_train, y_train)</pre><pre>y_pred = model.predict(X_test)</pre><p>Evaluation metrics:</p><ul><li>MAE</li><li>MSE</li><li>RMSE</li><li>R²</li></ul><h3>The “Movie Director” Analogy</h3><p>Imagine a movie director.</p><h3>Actor 1</h3><p>Forgets 20% of scenes.</p><p>Director says:</p><p>“These scenes are important. Practice them again.”</p><h3>Actor 2</h3><p>Focuses more on the forgotten scenes.</p><h3>Actor 3</h3><p>Focuses even more on the remaining mistakes.</p><p>Finally, the movie becomes good because each actor concentrated on the previous mistakes.</p><p>That is AdaBoost.</p><h3>AdaBoost vs Random Forest</h3><p>Random Forest{Bagging,Parallel trees, Reduces variance, Trees are independent, Majority vote, More robust to noise}</p><p>AdaBoost{Boosting, Sequential trees, Reduces bias, Each tree depends on previous one, Weighted vote (alpha), More sensitive to outliers/noisy labels}</p><h3>Why is AdaBoost Sensitive to Outliers?</h3><p>Suppose one data point is mislabeled.</p><p>AdaBoost keeps increasing its weight because it is repeatedly misclassified.</p><p>Eventually, the algorithm may spend too much effort trying to fit that noisy point.</p><h3>When Should We Use AdaBoost?</h3><p>Use it when:</p><ul><li>Dataset is relatively clean.</li><li>You need better accuracy than a single tree.</li><li>Relationships are not extremely complex.</li><li>You want a strong baseline boosting model.</li></ul><p>Avoid it when:</p><ul><li>There are many outliers.</li><li>Labels contain significant noise.</li><li>Dataset is extremely large (XGBoost/LightGBM may be better).</li></ul><h3>AdaBoost Inshort</h3><ul><li>Weak learner = Decision Tree Stump (depth = 1).</li><li>Start with equal weights.</li><li>Train stump.</li><li>Compute weighted error.</li><li>Calculate alpha.</li><li>Increase weights of wrong samples.</li><li>Decrease weights of correct samples.</li><li>Normalize weights.</li><li>Train next stump on weighted data.</li><li>Final prediction = weighted vote using alpha.</li></ul><p>AdaBoost = “Increase weight of mistakes, train next stump, combine all stumps using weighted voting.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ac7c1f2d396" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Random Forest Algorithm]]></title>
            <link>https://medium.com/@ankitamohanty1919191/random-forest-algorithm-6c7df0e36630?source=rss-b12caf5915c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c7df0e36630</guid>
            <category><![CDATA[random-forest-algorithm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ankita Mohanty]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 11:38:09 GMT</pubDate>
            <atom:updated>2026-07-23T11:38:09.017Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I learnt Random Forest, which is basically an improved version of Decision Trees. The biggest problem with a single Decision Tree is that it can overfit very easily, and Random Forest solves this by combining many trees together.</p><h3>1. Ensembling Techniques</h3><p>Ensembling means combining multiple machine learning models to get a better final prediction.</p><p>The two major ensemble techniques are:</p><ul><li>Bagging</li><li>Boosting</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZHhfms2Aj7zXYy3f" /></figure><h3>Bagging (Bootstrap Aggregating)</h3><p>Example: Random Forest</p><h3>Intuition</h3><p>Many models (called base learners) are trained in parallel.</p><p>Each model sees a slightly different version of the dataset.</p><p>Then all models give predictions.</p><h3>Final Output</h3><h3>Classification</h3><p>Take the majority vote.</p><p>Example:</p><p>Tree outputs → [1, 1, 0, 1, 0]</p><p>Majority = 1</p><h3>Regression</h3><p>Take the average of all predictions.</p><p>Example:</p><p>Tree outputs → [120, 125, 118, 122]</p><p>Average = 121.25</p><h3>Key Point</h3><p>Bagging reduces variance and helps prevent overfitting.</p><h3>Boosting</h3><p>Examples:</p><ul><li>AdaBoost</li><li>Gradient Boosting</li><li>XGBoost (Extreme Gradient Boosting)</li><li>LightGBM</li><li>CatBoost</li></ul><h3>Intuition</h3><p>Models are trained sequentially, not in parallel.</p><p>Workflow:</p><p>Model 1 predicts</p><p>↓</p><p>Find mistakes</p><p>↓</p><p>Give more importance to wrongly predicted samples</p><p>↓</p><p>Model 2 focuses on those mistakes</p><p>↓</p><p>Repeat</p><p>The combined set of weak learners becomes a strong learner.</p><p>In boosting, predictions are usually combined using weighted sums or additive modeling, not simply majority voting.</p><ul><li>AdaBoost → weighted vote of weak learners.</li><li>Gradient/XGBoost → adds predictions sequentially to reduce residual errors.</li></ul><h3>2. Random Forest Classification and Regression</h3><p>Suppose the dataset has n features.</p><p>Random Forest creates many Decision Trees, but each tree is intentionally made different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*71JwGMy0y5KAL44d" /></figure><h3>Two Types of Sampling</h3><h3>A. Row Sampling (Bootstrap Sampling)</h3><p>For each tree:</p><ul><li>Randomly select rows from the dataset.</li><li>Selection is done with replacement.</li></ul><p>Meaning:</p><ul><li>A row can appear multiple times in one tree.</li><li>Some rows may not appear at all.</li></ul><p>This is called Bootstrap Sampling.</p><h3>B. Feature Sampling</h3><p>At each split, the tree does not look at all features.</p><p>It randomly selects only a subset of features and chooses the best split among them.</p><p>This makes trees less correlated with each other.</p><h3>Classification in Random Forest</h3><p>Each tree predicts a class.</p><p>Final prediction = Majority Vote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ifh-ElvI1_ntMU7R" /></figure><h3>Regression in Random Forest</h3><p>Each tree predicts a number.</p><p>Final prediction = Average of all tree outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IsAb09_C_PdNUYvI" /></figure><h3>Why use Random Forest instead of a Single Decision Tree?</h3><p>A single Decision Tree:</p><ul><li>Can grow very deep.</li><li>Memorizes training data.</li><li>Has high variance.</li><li>Overfits easily.</li></ul><p>Random Forest:</p><ul><li>Uses many different trees.</li><li>Averages their predictions.</li><li>Reduces variance.</li><li>Generalizes much better.</li></ul><h3>One-line Interview Answer</h3><p>Decision Tree = high variance</p><p>Random Forest = low variance due to averaging multiple trees</p><h3>Important Random Forest Parameters</h3><h3>n_estimators</h3><p>Number of trees in the forest.</p><p>More trees → usually better performance (up to a point).</p><h3>max_depth</h3><p>Maximum depth of each tree.</p><p>Controls overfitting.</p><h3>min_samples_split</h3><p>Minimum samples required to split a node.</p><h3>min_samples_leaf</h3><p>Minimum samples required in a leaf node.</p><h3>max_features</h3><p>Number of features considered at each split.</p><p>Common defaults:</p><ul><li>Classification → sqrt(n_features)</li><li>Regression → n_features</li></ul><h3>bootstrap</h3><p>Whether row sampling is done with replacement.</p><p>Usually True in Random Forest.</p><h3>3. Model Training</h3><p>Initializing the model as a dictionary is often done when comparing multiple models, but the Random Forest model itself is initialized as an object.</p><h3>Typical Workflow</h3><p>Initialize Model</p><p>↓</p><p>Fit</p><p>↓</p><p>Predict</p><p>↓</p><p>Evaluate Training Performance</p><p>↓</p><p>Evaluate Test Performance</p><p>↓</p><p>Hyperparameter Tuning</p><h3>Classification Example</h3><pre>from sklearn.ensemble import RandomForestClassifier</pre><pre>rf = RandomForestClassifier(<br>    n_estimators=100,<br>    max_depth=5,<br>    random_state=42<br>)</pre><pre>rf.fit(X_train, y_train)<br>y_pred = rf.predict(X_test)</pre><h3>Regression Example</h3><pre>from sklearn.ensemble import RandomForestRegressor</pre><pre>rf = RandomForestRegressor(<br>    n_estimators=100,<br>    max_depth=5,<br>    random_state=42<br>)</pre><pre>rf.fit(X_train, y_train)<br>y_pred = rf.predict(X_test)</pre><h3>Training vs Test Performance</h3><p>This is very important.</p><h3>If:</h3><ul><li>Training Accuracy = 99%</li><li>Test Accuracy = 70%</li></ul><p>→ Overfitting</p><h3>If:</h3><ul><li>Training Accuracy = 85%</li><li>Test Accuracy = 83%</li></ul><p>→ Good Generalization</p><p>Random Forest usually has a smaller gap between training and test performance compared to a single Decision Tree.</p><h3>Hyperparameter Tuning</h3><p>We can “play with parameters” , but the proper approach is to use GridSearchCV or RandomizedSearchCV.</p><h3>Parameters commonly tuned</h3><pre>params = {<br>    &#39;n_estimators&#39;: [100, 200, 500],<br>    &#39;max_depth&#39;: [None, 5, 10, 20],<br>    &#39;min_samples_split&#39;: [2, 5, 10],<br>    &#39;min_samples_leaf&#39;: [1, 2, 4],<br>    &#39;max_features&#39;: [&#39;sqrt&#39;, &#39;log2&#39;]<br>}</pre><h3>Grid Search</h3><pre>from sklearn.model_selection import GridSearchCV</pre><pre>grid = GridSearchCV(<br>    RandomForestClassifier(random_state=42),<br>    params,<br>    cv=5,<br>    scoring=&#39;accuracy&#39;<br>)</pre><pre>grid.fit(X_train, y_train)</pre><pre>print(grid.best_params_)<br>print(grid.best_score_)</pre><h3>4. Random Forest Practical</h3><h3>A. Classification Practical</h3><h3>Workflow</h3><p>Load Dataset</p><p>↓</p><p>Train-Test Split</p><p>↓</p><p>Initialize RandomForestClassifier</p><p>↓</p><p>Fit</p><p>↓</p><p>Predict</p><p>↓</p><p>Accuracy, Confusion Matrix, Precision, Recall, F1</p><h3>B. Regression Practical</h3><h3>Workflow</h3><p>Load Dataset</p><p>↓</p><p>Train-Test Split</p><p>↓</p><p>Initialize RandomForestRegressor</p><p>↓</p><p>Fit</p><p>↓</p><p>Predict</p><p>↓</p><p>MAE, MSE, RMSE, R²</p><h3>Feature Importance (Very Important)</h3><p>One of the best things about Random Forest is that it can tell us which features are most important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/0*SST90mvyhQwyKZo6" /></figure><pre>import pandas as pd</pre><pre>importance = pd.Series(rf.feature_importances_, index=X.columns)<br>importance.sort_values(ascending=False)</pre><p>Higher importance → feature contributes more to predictions.</p><p>This is extremely useful for:</p><ul><li>Feature selection</li><li>Business interpretation</li><li>Interview discussions</li></ul><h3>Out-of-Bag (OOB) Score</h3><p>Because bootstrap sampling leaves some rows unused for each tree, those unused rows are called Out-of-Bag samples.</p><p>Random Forest can evaluate itself using these samples without needing a separate validation set.</p><pre>rf = RandomForestClassifier(<br>    n_estimators=100,<br>    oob_score=True,<br>    random_state=42<br>)</pre><pre>rf.fit(X_train, y_train)<br>print(rf.oob_score_)</pre><h3>Random Forest vs Decision Tree</h3><p>Decision Tree{Single tree, High variance, Overfits easily, Highly interpretable, Fast training}</p><p>Random Forest{Many trees, Low variance, More robust, Less interpretable, Slower training}</p><h3>When should we use Random Forest?</h3><p>Use it when:</p><ul><li>Dataset is tabular.</li><li>Features may have non-linear relationships.</li><li>You want strong baseline performance quickly.</li><li>Overfitting is a concern with Decision Trees.</li><li>Interpretability is less important than accuracy.</li></ul><p>Avoid it when:</p><ul><li>You need a very interpretable model.</li><li>Real-time prediction must be extremely fast.</li><li>Dataset is extremely sparse text data (Naive Bayes / linear models may be better).</li></ul><h3>IMP. points:</h3><h3>Why is it called “Random” Forest?</h3><p>Because randomness is introduced in two places:</p><ul><li>Random row sampling (bootstrap).</li><li>Random feature sampling.</li></ul><h3>What is the main advantage of Random Forest?</h3><p>It reduces overfitting by averaging predictions from many diverse decision trees.</p><h3>Does Random Forest need feature scaling?</h3><p>Usually No.</p><p>Since Decision Trees split based on thresholds, they are not sensitive to feature scales.</p><p>This is a common interview trick question.</p><h3>What is the difference between Bagging and Random Forest?</h3><ul><li>Bagging can use any base model.</li><li>Random Forest is specifically bagging + decision trees + random feature selection.</li></ul><h3>Random Forest Inshort</h3><ul><li>Bagging → Parallel models + averaging/voting.</li><li>Boosting → Sequential models correcting previous errors.</li><li>Random Forest = Bagging + Decision Trees + Random Feature Sampling.</li><li>Row sampling = Bootstrap (with replacement).</li><li>Feature sampling = Random subset at each split.</li><li>Classification → Majority vote.</li><li>Regression → Average prediction.</li><li>Main benefit → Reduces variance and overfitting.</li><li>Most important parameters → n_estimators, max_depth, max_features.</li><li>OOB score = Built-in validation using unused bootstrap samples.</li><li>Feature scaling → Usually not required.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c7df0e36630" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decision Tree]]></title>
            <link>https://medium.com/@ankitamohanty1919191/decision-tree-39902a45776b?source=rss-b12caf5915c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/39902a45776b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Ankita Mohanty]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 11:21:19 GMT</pubDate>
            <atom:updated>2026-07-22T11:21:19.400Z</atom:updated>
            <content:encoded><![CDATA[<p>Decision Trees are one of the easiest algorithms to visualize because they work like nested if–else conditions.</p><p>Example:</p><p>If Glucose &gt; 120 → Check BMI</p><p>Else → Check Age</p><p>This continues until we reach a final prediction.</p><p>A Decision Tree can be used for both Classification and Regression.</p><h3>1. Introduction</h3><h3>Types of Decision Trees</h3><h3>ID3</h3><ul><li>Uses Entropy and Information Gain.</li><li>Originally designed for classification.</li></ul><h3>CART (Classification and Regression Trees)</h3><ul><li>Uses Gini Impurity for classification.</li><li>Uses Variance Reduction for regression.</li><li>Produces binary splits (left/right).</li><li>This is the algorithm most commonly implemented in scikit-learn.</li></ul><p>A Decision Tree is built in a top-down recursive splitting approach.</p><p>We start from the root node and keep splitting downward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-Bc9jew7_9c8ci6z" /></figure><h3>Pure vs Impure Split</h3><h3>Pure Split (Leaf Node)</h3><p>All samples belong to the same class.</p><p>Example:</p><ul><li>10 Yes</li><li>0 No</li></ul><p>No further splitting is needed.</p><h3>Impure Split</h3><p>A node contains mixed classes.</p><p>Example:</p><ul><li>6 Yes</li><li>4 No</li></ul><p>Further splitting is required.</p><h3>How do we measure purity?</h3><p>We use:</p><ul><li>Entropy</li><li>Gini Impurity</li></ul><h3>Which feature should be selected for splitting?</h3><p>We choose the feature that gives the highest Information Gain, i.e., the feature that reduces impurity the most and reaches pure nodes faster.</p><h3>2. Entropy and Gini Impurity</h3><h3>Entropy</h3><p>Formula:</p><p>Entropy(S)=−∑pilog⁡2pi</p><h3>Interpretation</h3><ul><li>Entropy = 0 → Completely pure.</li><li>Entropy = 1 → Maximum impurity for a binary classification problem.</li></ul><h3>Range</h3><p>0 to 1 (for binary classes).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5wHj4-hcRYwNvpSa" /></figure><h3>Gini Impurity</h3><p>Formula:</p><p>Gini(S)=1−∑pi^2</p><h3>Interpretation</h3><ul><li>Gini = 0 → Pure node.</li><li>Gini = 0.5 → Maximum impurity for a binary classification problem.</li></ul><h3>Range</h3><p>0 to 0.5 (for binary classes).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/0*76GgkgW5sTcxS_65" /></figure><h3>3. Information Gain</h3><p>Information Gain tells us how much impurity is reduced after a split.</p><p>Formula:</p><p>IG(S,F)=Entropy(S)−∑(∣Sᵥ∣/∣S∣)Entropy(Sᵥ)</p><p>Where:</p><ul><li>S = parent/root node</li><li>F = feature used for splitting</li><li>Sᵥ = child nodes after the split</li></ul><h3>Intuition</h3><p>Information Gain = Impurity before split − Weighted impurity after split</p><p>Higher Information Gain → Better feature for splitting.</p><h3>4. Entropy vs Gini</h3><h3>Entropy</h3><ul><li>Uses logarithms.</li><li>Slightly more computationally expensive.</li><li>Can be useful for smaller datasets when we want a more information-theoretic measure.</li></ul><h3>Gini</h3><ul><li>Simpler calculation.</li><li>Faster</li><li>Most libraries (including scikit-learn CART) use Gini by default.</li></ul><p>So in practice:</p><p>Small dataset → Entropy can be used</p><p>Large dataset / speed important → Gini is usually preferred</p><h3>5. Decision Tree Split for Numerical Features</h3><p>This is an important interview topic.</p><p>Suppose a feature has values:</p><p>10, 15, 20, 30</p><h3>Correct Process</h3><p>First sort the values.</p><p>Then we do not use the value itself as the threshold.</p><p>We take the midpoints between consecutive values.</p><p>Possible thresholds:</p><ul><li>(10 + 15) / 2 = 12.5</li><li>(15 + 20) / 2 = 17.5</li><li>(20 + 30) / 2 = 25</li></ul><p>For each threshold:</p><ul><li>Split the data.</li><li>Calculate Entropy/Gini.</li><li>Compute Information Gain.</li></ul><p>Choose the threshold with the highest Information Gain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/0*Ri4G2oJWsS9ZQvmo" /></figure><h3>6. Pre-Pruning and Post-Pruning (Very Important)</h3><p>If we keep splitting deeper and deeper to make every leaf pure, the tree may memorize the training data.</p><p>This leads to:</p><ul><li>Low Bias</li><li>High Variance</li><li>Overfitting</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/0*_d4hM-KAZyuAm2YG" /></figure><p>To control this, we use pruning.</p><h3>Pre-Pruning</h3><p>Also called Early Stopping.</p><p>We stop the tree from growing too much while constructing the tree.</p><p>Common hyperparameters:</p><ul><li>max_depth</li><li>min_samples_split</li><li>min_samples_leaf</li><li>max_leaf_nodes</li><li>max_features</li></ul><p>This is the most commonly used approach in practice.</p><h3>Post-Pruning</h3><p>First build the full tree, then remove unnecessary branches.</p><p>Scikit-learn uses Cost Complexity Pruning with parameter:</p><p>ccp_alpha</p><p>Larger ccp_alpha → More pruning.</p><p>Your note “first make the decision tree then prune it” is correct.</p><h3>7. Decision Tree Regression</h3><p>Used when the output feature is continuous.</p><p>Example:</p><ul><li>House Price</li><li>Salary</li><li>Temperature</li></ul><h3>Which split should be chosen?</h3><p>We use Variance Reduction (or equivalently MSE reduction)</p><h3>What is this weight?</h3><p>The weight is the proportion of samples in that child node.</p><p>Formula:</p><p>Weighted Variance=(nL/n)Var(L)+(nR/n)Var(R)</p><p>Where:</p><ul><li>n = total samples in parent</li><li>nL = samples in left child</li><li>nR = samples in right child</li></ul><h3>Variance Reduction</h3><p>VR=Var(Parent)−WeightedVariance(Children)</p><p>Choose the split with the maximum variance reduction.</p><h3>8. Decision Tree Practical</h3><h3>A. Post-Pruning Practical</h3><h3>Workflow</h3><p>Import Libraries</p><p>↓</p><p>Load Dataset</p><p>↓</p><p>Import DecisionTreeClassifier</p><p>↓</p><p>Fit Model</p><p>↓</p><p>Visualize Tree</p><p>↓</p><p>Prune using ccp_alpha</p><pre>from sklearn.tree import DecisionTreeClassifier, plot_tree</pre><pre>model = DecisionTreeClassifier(random_state=42)<br>model.fit(X_train, y_train)</pre><pre>plot_tree(model)</pre><h3>Which number should be selected as max_depth?</h3><p>There is no fixed number.</p><p>We choose it using Cross Validation.</p><p>Typical approach:</p><p>Try:</p><ul><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>8</li><li>10</li></ul><p>Then select the depth that gives the best validation score, not necessarily the highest training accuracy.</p><p>A good sign:</p><ul><li>Training accuracy high</li><li>Validation accuracy also high</li><li>Gap between them is small</li></ul><h3>B. Pre-Pruning Practical</h3><h3>Important Parameters</h3><pre>params = {<br>    &#39;criterion&#39;: [&#39;gini&#39;, &#39;entropy&#39;],<br>    &#39;max_depth&#39;: [2,3,4,5,6,8,10],<br>    &#39;min_samples_split&#39;: [2,5,10],<br>    &#39;min_samples_leaf&#39;: [1,2,4],<br>    &#39;max_features&#39;: [&#39;sqrt&#39;, &#39;log2&#39;, None]<br>}</pre><h3>Grid Search</h3><pre>from sklearn.model_selection import GridSearchCV<br>from sklearn.tree import DecisionTreeClassifier</pre><pre>tree = DecisionTreeClassifier(random_state=42)</pre><pre>grid = GridSearchCV(tree, params, cv=5, scoring=&#39;accuracy&#39;)<br>grid.fit(X_train, y_train)</pre><pre>print(grid.best_params_)<br>print(grid.best_score_)</pre><p>This automatically checks many parameter combinations and returns the best one.</p><h3>9. Diabetic Prediction using Decision Tree</h3><h3>Features (X)</h3><ul><li>Glucose</li><li>Blood Pressure</li><li>BMI</li><li>Age</li><li>Insulin</li><li>Skin Thickness</li><li>Pregnancies</li></ul><h3>Target (Y)</h3><ul><li>1 → Diabetic</li><li>0 → Non-Diabetic</li></ul><h3>Pipeline</h3><p>Dataset</p><p>↓</p><p>Handle Missing Values</p><p>↓</p><p>Train-Test Split</p><p>↓</p><p>DecisionTreeClassifier</p><p>↓</p><p>Fit</p><p>↓</p><p>Predict</p><p>↓</p><p>Confusion Matrix, Precision, Recall, F1</p><p>In medical problems, Recall is often very important because missing an actual diabetic patient (False Negative) can be dangerous.</p><h3>Important things to note:</h3><h3>Why are Decision Trees easy to interpret?</h3><p>Because every prediction can be traced through a sequence of if–else rules from root to leaf.</p><h3>Why do Decision Trees overfit easily?</h3><p>They can keep splitting until each leaf contains very few samples, effectively memorizing the training data.</p><h3>Difference between Pre-Pruning and Post-Pruning</h3><p>Pre-Pruning {Stop growth early then cut branches, Can be more accurate, Uses pruning criteria (ccp_alpha)}</p><p>Post-Pruning{Grow fully, Faster, Uses hyperparameters}</p><h3>Gini vs Entropy in One Line</h3><ul><li>Gini → Faster, default in CART.</li><li>Entropy → More information-theoretic, slightly slower.</li></ul><h3>Decision Tree Inshort</h3><ul><li>ID3 → Entropy + Information Gain.</li><li>CART → Gini (classification) + Variance Reduction (regression).</li><li>Tree grows → Top-down recursively.</li><li>Entropy = 0 → Pure node.</li><li>Gini = 0 → Pure node.</li><li>Best split → Highest Information Gain / Variance Reduction.</li><li>Numerical threshold → Use midpoints between sorted values.</li><li>Overfitting → Very deep trees.</li><li>Pre-pruning → Stop growth early.</li><li>Post-pruning → Grow first, then prune with ccp_alpha.</li><li>Regression split → Maximize variance reduction.</li><li>Choose max_depth → Use cross-validation, not a fixed number.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39902a45776b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K Nearest Neighbour Algorithm]]></title>
            <link>https://medium.com/@ankitamohanty1919191/k-nearest-neighbour-algorithm-43ad1fd92355?source=rss-b12caf5915c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/43ad1fd92355</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[knn-algorithm]]></category>
            <dc:creator><![CDATA[Ankita Mohanty]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 10:52:34 GMT</pubDate>
            <atom:updated>2026-07-22T10:52:34.094Z</atom:updated>
            <content:encoded><![CDATA[<p>KNN was actually fun because it is one of the few ML algorithms where I can literally imagine the points on a graph and see how the prediction is happening.</p><p>KNN can be used for both Classification and Regression.</p><h3>1. KNN In-Depth Intuition</h3><h3>KNN for Classification</h3><h3>Step 1: Initialize K</h3><p>We first choose a K value.</p><p>K = number of nearest neighbors to consider.</p><p>K is a Hyperparameter because its value is not learned by the model; we choose it and it can change based on the dataset.</p><h3>Step 2: Find K Nearest Neighbors</h3><p>For a new test data point, calculate the distance from all training points.</p><p>Then select the K closest points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DeU6-jEYlgHXGhTf" /></figure><h3>Step 3: Majority Voting</h3><p>Suppose K = 5.</p><p>Among the 5 nearest neighbours:</p><ul><li>3 belong to Class 1</li><li>2 belong to Class 0</li></ul><p>Since Class 1 has the majority, the output becomes 1.</p><p>So,</p><p>Maximum category among the K neighbours decides the classification output.</p><h3>Distance Formulas</h3><h3>Euclidean Distance</h3><p>This is the straight-line distance between two points.</p><p>d=(x2−x1)2+(y2−y1)2d=\sqrt{(x_2-x_1)²+(y_2-y_1)²}d=(x2−x1)2+(y2−y1)2</p><p>This is the same formula we studied in school.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*u27LAkYQdwfOgljQ" /></figure><h3>Manhattan Distance</h3><p>Distance is measured by moving horizontally and vertically, like roads in a city grid.</p><p>d=∣x2−x1∣+∣y2−y1∣d=|x_2-x_1|+|y_2-y_1|d=∣x2−x1∣+∣y2−y1∣</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5roFzhAMkpji0zO1" /></figure><p>It is called L1 distance, while Euclidean is L2 distance.</p><h3>KNN for Regression</h3><p>The steps are almost the same.</p><h3>Step 1: Choose K</h3><p>Initialize the K value.</p><h3>Step 2: Find K Nearest Neighbors</h3><p>Calculate distances and select the K closest points.</p><h3>Step 3: Average Their Target Values</h3><p>Instead of majority voting, we take the average of the target values.</p><p>Example:</p><p>Nearest target values = [10, 12, 14]</p><p>Prediction = (10 + 12 + 14) / 3 = 12</p><p>So,</p><p>Classification → Majority Vote</p><p>Regression → Average of Neighbour Values</p><h3>Why KNN Can Become Slow</h3><p>For every test point, KNN may need to calculate the distance from all training points.</p><p>If we have:</p><ul><li>1,000,000 training samples</li><li>10,000 test samples</li></ul><p>the number of distance calculations becomes huge.</p><p>This increases time complexity.</p><p>To reduce this, we use optimized data structures.</p><h3>2. Optimization of KNN</h3><h3>KDTree</h3><p>KDTree (K-Dimensional Tree) is a binary tree that recursively splits the feature space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*RKRkUXhEWpHq7NrW" /></figure><h3>When x projection and when y projection? Can we do anything?</h3><p>In a 2D dataset, KDTree usually alternates the splitting axis.</p><ul><li>Level 1 → split using X-axis</li><li>Level 2 → split using Y-axis</li><li>Level 3 → split using X-axis</li><li>Level 4 → split using Y-axis</li></ul><p>and so on.</p><p>The split is typically done at the median value of that feature so that the tree remains balanced.</p><p>Example:</p><ul><li>Root split → X median</li><li>Left/right child split → Y median</li><li>Next level → X median again</li></ul><p>So we do not randomly choose the axis; it is usually selected in an alternating manner (or sometimes based on variance in advanced implementations).</p><h3>How KDTree Helps</h3><p>When a test point arrives:</p><ul><li>We first locate the region in which the point lies.</li><li>Then we search nearby points in that region.</li><li>We do not need to check every training sample.</li></ul><p>This reduces search complexity significantly.</p><h3>Backtracking</h3><p>Sometimes the true nearest neighbor may lie in a neighboring region.</p><p>So after searching one branch, KDTree may backtrack and check another branch if it could contain a closer point.</p><p>This is why KDTree is faster than brute force, but it may still perform some additional searches.</p><h3>BallTree</h3><p>BallTree groups nearby points into spherical regions (balls).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*2hbJxGBOVnvIe4OS" /></figure><p>Instead of axis-aligned splits, it uses distances from cluster centers.</p><h3>Why BallTree Is Often Better</h3><p>For higher-dimensional data:</p><ul><li>KDTree performance degrades.</li><li>BallTree handles arbitrary-shaped clusters more effectively.</li></ul><h3>Small Correction</h3><p>You wrote “better because no backtracking.”</p><p>Actually, BallTree can also perform backtracking/pruning. The main advantage is that it often works better in higher dimensions because it organizes points using hyperspheres rather than axis-aligned regions.</p><h3>Intuition</h3><ul><li>Group nearby points.</li><li>Create a ball around them.</li><li>Combine balls into larger balls.</li><li>Continue until a hierarchical tree is formed.</li></ul><p>During search, entire balls that cannot contain a closer neighbor are discarded quickly.</p><h3>3. KNN Practical (Classification)</h3><h3>Workflow</h3><p>Import Libraries</p><p>↓</p><p>Create Dataset</p><p>↓</p><p>Train-Test Split</p><p>↓</p><p>Initialize KNN</p><p>↓</p><p>Fit</p><p>↓</p><p>Predict</p><p>↓</p><p>Evaluate</p><h3>Create Dataset</h3><pre>from sklearn.datasets import make_classification</pre><pre>X, y = make_classification(<br>    n_samples=1000,<br>    n_features=2,<br>    n_classes=2,<br>    random_state=42<br>)</pre><h3>Train-Test Split</h3><pre>from sklearn.model_selection import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)</pre><h3>Initialize KNN</h3><pre>from sklearn.neighbors import KNeighborsClassifier</pre><pre>knn = KNeighborsClassifier(<br>    n_neighbors=5,<br>    weights=&#39;uniform&#39;,<br>    algorithm=&#39;auto&#39;,<br>    p=2<br>)</pre><h3>Three Important Parameters</h3><h3>1. weights</h3><h3>uniform</h3><p>All neighbors get equal importance.</p><h3>distance</h3><p>Closer neighbors get more importance than farther neighbors.</p><p>This is often useful when nearby points should influence the prediction more strongly.</p><h3>2. algorithm</h3><p>Options:</p><ul><li>auto</li><li>kd_tree</li><li>ball_tree</li><li>brute</li></ul><h3>auto</h3><p>Scikit-learn automatically chooses the best algorithm.</p><h3>brute</h3><p>Checks distances from all points.</p><h3>kd_tree</h3><p>Uses KDTree optimization.</p><h3>ball_tree</h3><p>Uses BallTree optimization.</p><h3>3. p</h3><p>This controls the distance metric.</p><h3>p = 1</h3><p>Manhattan Distance (L1).</p><h3>p = 2</h3><p>Euclidean Distance (L2).</p><p>This is the most commonly used value.</p><h3>Fit the Model</h3><pre>knn.fit(X_train, y_train)</pre><h3>Predict</h3><pre>y_pred = knn.predict(X_test)</pre><h3>Metrics</h3><p>Common metrics:</p><ul><li>Accuracy</li><li>Confusion Matrix</li><li>Precision</li><li>Recall</li><li>F1 Score</li></ul><pre>from sklearn.metrics import accuracy_score</pre><pre>accuracy = accuracy_score(y_test, y_pred)<br>print(accuracy)</pre><h3>Choosing the Best K</h3><p>This is one of the most common interview questions.</p><h3>Small K (K = 1)</h3><ul><li>Very sensitive to noise.</li><li>Can overfit.</li><li>Decision boundary becomes highly irregular.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*eHxseL4mLt7Zf39S" /></figure><h3>Large K</h3><ul><li>Smoother decision boundary.</li><li>More stable predictions.</li><li>Can underfit if K becomes too large.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*LC42bXoe4fJtABkw" /></figure><h3>Practical Way</h3><p>Use Cross Validation and choose the K with the best validation score.</p><p>A common heuristic is:</p><p>K≈N</p><p>where N is the number of training samples.</p><h3>IMP. Ques.:</h3><h3>Why is KNN called a “Lazy Learner”?</h3><p>Because it does not learn a model during training.</p><p>Training is almost just storing the dataset.</p><p>Most of the computation happens during prediction time.</p><h3>Why is Standardization Important in KNN?</h3><p>KNN is entirely based on distances.</p><p>Example:</p><ul><li>Age: 20–60</li><li>Salary: 20,000–2,00,000</li></ul><p>Salary has a much larger scale and would dominate the distance calculation.</p><p>So we usually apply StandardScaler before KNN.</p><h3>KNN vs Logistic Regression</h3><p>KNN {Non-parametric, Lazy learner, Slow prediction, Captures non-linear boundaries}</p><p>Logistic Regression{ Parametric, Eager learner, Fast prediction, Linear decision boundary (unless engineered)}</p><h3>When to Use KNN?</h3><p>Use KNN when:</p><ul><li>Dataset is small to medium.</li><li>Decision boundary is non-linear.</li><li>You want a simple baseline model.</li><li>Feature relationships are local.</li></ul><p>Avoid KNN when:</p><ul><li>Dataset is extremely large.</li><li>Features are very high-dimensional.</li><li>Prediction speed is critical.</li></ul><h3>KNN inshort</h3><ul><li>KNN = Classification + Regression.</li><li>Classification = Majority vote of K neighbours.</li><li>Regression = Average of K neighbours.</li><li>K is a hyperparameter.</li><li>p=1 → Manhattan distance.</li><li>p=2 → Euclidean distance.</li><li>Small K → Overfitting.</li><li>Large K → Underfitting.</li><li>KDTree = Axis-based partitioning + possible backtracking.</li><li>BallTree = Sphere-based partitioning, often better for higher dimensions.</li><li>Always scale features before KNN.</li><li>KNN is a Lazy Learner → training is cheap, prediction is expensive.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43ad1fd92355" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Naive Baye’s Algorithm]]></title>
            <link>https://medium.com/@ankitamohanty1919191/naive-bayes-algorithm-7b55aec3e529?source=rss-b12caf5915c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b55aec3e529</guid>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ankita Mohanty]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 20:01:03 GMT</pubDate>
            <atom:updated>2026-07-20T20:01:03.709Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I also learnt Naive Bayes Algorithm, which is a Classification algorithm based on Probability and Bayes Theorem. Initially the formulas looked confusing, but once I connected them with machine learning, it became much easier.</p><h3>1. Naive Bayes Algorithm (Classification)</h3><p>Naive Bayes predicts the class using probabilities.</p><p>Example:</p><ul><li>Spam or Not Spam</li><li>Yes or No</li><li>Positive or Negative</li><li>Disease or No Disease</li></ul><h3>Probability Basics</h3><h3>Independent Events</h3><p>One event does not affect the probability of another event.</p><p>Example: Rolling a dice.</p><p>Getting a 6 in the first roll does not change the probability of getting a 6 in the second roll.</p><h3>Dependent Events</h3><p>One event does affect the probability of another event.</p><p>Examples:</p><ul><li>Drawing cards without replacement.</li><li>Taking marbles from a bag.</li></ul><p>Here we use Conditional Probability.</p><h3>Conditional Probability Formula</h3><p>P(A∩B)=P(A)×P(B∣A)</p><p>Meaning:</p><p>Probability of both A and B occurring = Probability of A × Probability of B given that A has already occurred.</p><h3>Bayes Theorem</h3><p>The key idea is:</p><p>P(A∩B)=P(B∩A)</p><p>From this we derive:</p><p>P(A∣B)=(P(B∣A) P(A))/P(B)</p><p>Where:</p><ul><li>P(A|B) = Probability of event A given B has occured (Posterior Probability)</li><li>P(B|A) = Probability of event B given A has occured (Likelihood)</li><li>P(A) = Probability of event A (Prior Probability)</li><li>P(B) = Probability of event B (Evidence)</li></ul><h3>Bayes Theorem in Machine Learning</h3><p>Suppose:</p><ul><li>Y = Output feature (class)</li><li>x₁, x₂, x₃ = Input features</li></ul><p>Then,</p><p>P(Y∣x1,x2,x3)=P(Y) P(x1,x2,x3∣Y)/P(x1,x2,x3)</p><h3>The “Naive” Assumption</h3><p>Naive Bayes assumes that all input features are independent of each other given the class.</p><p>So,</p><p>P(x1,x2,x3∣Y)=P(x1∣Y)*P(x2∣Y)*P(x3∣Y)</p><p>Substituting:</p><p>P(Y∣x1,x2,x3)=P(Y) P(x1∣Y) P(x2∣Y) P(x3∣Y)/P(x1,x2,x3)</p><p>Since the denominator is the same for all classes, we usually compare only the numerator.</p><h3>Intuition</h3><p>Suppose Y has two classes:</p><ul><li>Yes</li><li>No</li></ul><p>For a new data point, we calculate:</p><p>Probability of Yes</p><p>P(Yes)×P(x1∣Yes)×P(x2∣Yes)×P(x3∣Yes)</p><p>Probability of No</p><p>P(No)×P(x1∣No)×P(x2∣No)×P(x3∣No)</p><p>Whichever probability is larger becomes the predicted class.</p><p>That is the entire core idea of Naive Bayes.</p><h3>2. Variants of Naive Bayes</h3><p>Different variants are used for different types of data.</p><h3>Bernoulli Naive Bayes</h3><p>Use when features are binary (0 or 1).</p><p>Examples:</p><ul><li>Word present or not present.</li><li>Clicked or not clicked.</li><li>Purchased or not purchased.</li></ul><p>So Bernoulli NB is suitable when features follow a Bernoulli distribution and the task is classification.</p><h3>Multinomial Naive Bayes</h3><p>Use when input data is in the form of text or word counts.</p><p>Example:</p><p>Input: Emails</p><p>Output: Spam / Not Spam</p><p>Before applying the model, sentences must be converted into numerical vectors.</p><p>Common NLP vectorization techniques:</p><ul><li>Bag of Words (BoW)</li><li>TF-IDF</li><li>Word2Vec</li><li>Count Vectorizer</li></ul><p>This is why Multinomial NB is widely used in NLP and Text Classification.</p><h3>Gaussian Naive Bayes</h3><p>Use when features are continuous numerical values and are assumed to follow a Gaussian (Normal) Distribution.</p><p>Examples:</p><ul><li>Height</li><li>Weight</li><li>Temperature</li><li>Blood Pressure</li></ul><p>Gaussian NB models each feature using a normal distribution.</p><p>If data is not perfectly normal, we can sometimes apply transformations (log, Box-Cox, etc.) to make it closer to a normal distribution.</p><h3>Quick Difference</h3><p>VariantData TypeBernoulli NBBinary (0/1)Multinomial NBText / word countsGaussian NBContinuous numerical data</p><h3>3. Naive Bayes Practical</h3><h3>Workflow</h3><p>Load Dataset</p><p>↓</p><p>Separate Independent and Dependent Features</p><p>↓</p><p>Train Test Split</p><p>↓</p><p>Import Variant</p><p>↓</p><p>Initialize Model</p><p>↓</p><p>Fit</p><p>↓</p><p>Predict</p><p>↓</p><p>Evaluate</p><h3>Step-by-Step</h3><h3>Load Dataset</h3><p>Python</p><p>Run</p><pre>X = df.drop(&quot;target&quot;, axis=1)<br>y = df[&quot;target&quot;]</pre><h3>Train Test Split</h3><p>Python</p><p>Run</p><pre>from sklearn.model_selection import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)</pre><h3>Import Variant</h3><p>For numerical data we usually use GaussianNB.</p><p>Python</p><p>Run</p><pre>from sklearn.naive_bayes import GaussianNB</pre><h3>Initialize and Train</h3><p>Python</p><p>Run</p><pre>model = GaussianNB()<br>model.fit(X_train, y_train)</pre><h3>Predict</h3><p>Python</p><p>Run</p><pre>y_pred = model.predict(X_test)</pre><p>We can also get class probabilities:</p><p>Python</p><p>Run</p><pre>model.predict_proba(X_test)</pre><h3>Metrics</h3><p>Evaluate using:</p><ul><li>Accuracy</li><li>Confusion Matrix</li><li>Precision</li><li>Recall</li><li>F1 Score</li></ul><h3>My Doubts:</h3><h3>Why is Naive Bayes called “Naive”?</h3><p>Because it makes a naive assumption that all features are independent of each other given the class.</p><p>In real life, features are often correlated, but surprisingly the algorithm still works very well.</p><h3>Why is Naive Bayes so fast?</h3><p>It only needs to estimate probabilities from the data.</p><p>There is no iterative optimization like Gradient Descent used in Logistic Regression or SVM.</p><h3>Naive Bayes vs Logistic Regression</h3><p>Naive BayesLogistic RegressionProbabilisticDiscriminativeAssumes feature independenceDoes not require that assumptionVery fastSlightly slowerGreat for text classificationOften gives better calibrated probabilities</p><h3>When should I use Naive Bayes?</h3><p>Use it when:</p><ul><li>Dataset is large.</li><li>Training speed is important.</li><li>Problem is text classification.</li><li>Features are approximately independent.</li><li>You need a strong baseline model quickly.</li></ul><h3>Naive Bayes Inshort</h3><ul><li>Naive Bayes = Probability-based classification algorithm.</li><li>Core formula = Posterior = Prior × Likelihood / Evidence.</li><li>Naive assumption = Features are independent given the class.</li><li>Bernoulli NB = Binary features (0/1).</li><li>Multinomial NB = Text / word-count problems.</li><li>Gaussian NB = Continuous numerical features with approximately normal distribution.</li><li>NLP preprocessing = Convert text to vectors using BoW, TF-IDF, or Word2Vec.</li><li>Why fast? = No gradient descent or iterative optimization.</li><li>Best use case = Spam detection and document classification.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b55aec3e529" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Support Vector Machine Algorithm]]></title>
            <link>https://medium.com/@ankitamohanty1919191/support-vector-machine-algorithm-54a34ac6cee8?source=rss-b12caf5915c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/54a34ac6cee8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[svm-algorithm]]></category>
            <dc:creator><![CDATA[Ankita Mohanty]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 19:46:16 GMT</pubDate>
            <atom:updated>2026-07-20T19:46:16.930Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I learnt Support Vector Machine (SVM). Initially I thought it only draws a best fit line, but actually it tries to find a boundary that separates classes with the maximum possible margin.</p><h3>1. SVM</h3><p>SVM has two main types:</p><ul><li>SVC (Support Vector Classifier) → used for Classification</li><li>SVR (Support Vector Regressor) → used for Regression</li></ul><h3>Intuition</h3><p>Imagine two classes of points.</p><p>SVM draws a Decision Boundary (Hyperplane) between them.</p><p>Then it draws two parallel marginal planes on both sides of that boundary such that the distance between the planes is maximum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*5JU9hbq6XXcCTjLh" /></figure><p>The points that touch these margins are called Support Vectors.</p><p>These support vectors are the most important points because they decide the position of the hyperplane.</p><h3>2. Soft Margin vs Hard Margin</h3><h3>Hard Margin</h3><ul><li>Data is perfectly separable.</li><li>No overlapping.</li><li>No misclassification.</li><li>Margin completely separates both classes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VIytLxOTyxXnHqnT" /></figure><p>Use Case: Ideal clean dataset.</p><p>Problem: Real-world data is rarely perfectly separable.</p><h3>Soft Margin</h3><ul><li>Some overlap is allowed.</li><li>Some points may lie inside the margin.</li><li>A few points can even be misclassified.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*DIcL21e4W_86J0Wn" /></figure><p>This is what is usually used in practice because real datasets contain noise and outliers.</p><h3>3. SVC (Support Vector Classifier)</h3><h3>Goal</h3><p>Find w and b such that:</p><ul><li>Margin becomes maximum.</li><li>Classification error becomes minimum.</li></ul><p>The hyperplane equation is:</p><p>w^T x + b = 0</p><p>SVM optimizes a cost function that tries to maximize the margin while penalizing misclassified points.</p><h3>Constraints</h3><p>For correctly classified points:</p><p>yi(w^Txi+b)≥1</p><p>For soft margin, slack variables are introduced:</p><p>yi(w^Txi+b)≥1−ξi</p><p>where ξᵢ (Xi) measures how much a point violates the margin.</p><h3>Hyperparameter: C</h3><p>C controls the trade-off between:</p><ul><li>Maximizing margin</li><li>Minimizing misclassification</li></ul><p>C valueEffectLarge CTries very hard to avoid misclassification; margin becomes smaller; may overfit.Small CAllows some misclassification; margin becomes wider; may generalize better.</p><h3>Hinge Loss</h3><p>SVC uses Hinge Loss.</p><ul><li>Correctly classified points outside the margin → loss = 0</li><li>Points inside the margin or misclassified → loss &gt; 0</li></ul><p>This is why SVM focuses mainly on the difficult points near the boundary.</p><h3>4. SVR (Support Vector Regression)</h3><p>SVR is the regression version of SVM.</p><p>Instead of separating classes, it tries to fit a function while allowing a small acceptable error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*LwenAG2dg1kJI2mA" /></figure><h3>Important Terms</h3><h3>Epsilon (ε)</h3><p>A tube is drawn around the regression line.</p><p>Any prediction error within this tube is ignored.</p><p>This tube is called the epsilon-insensitive margin.</p><h3>Eta / ξ (Slack for SVR)</h3><p>If a point lies outside the epsilon tube, then the excess error is measured using slack variables.</p><h3>Difference between SVC and SVR Cost Functions</h3><h3>SVC</h3><ul><li>Objective: Correct classification.</li><li>Penalizes margin violations.</li><li>Uses Hinge Loss.</li></ul><h3>SVR</h3><ul><li>Objective: Accurate regression.</li><li>Ignores errors within ε.</li><li>Penalizes only errors greater than ε.</li></ul><p>So the main difference is:</p><ul><li>SVC → classification + hinge loss</li><li>SVR → regression + epsilon-insensitive loss</li></ul><h3>5. SVM Kernels</h3><p>Sometimes data is not linearly separable in 2D.</p><p>Example: points arranged in circles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gmgA1EEcYtpqRmVU" /></figure><p>A straight line cannot separate them.</p><p>SVM solves this using the Kernel Trick.</p><p>Instead of manually converting 2D to 3D, the kernel computes similarities as if the data were transformed into a higher-dimensional space.</p><p>After transformation, a simple hyperplane can separate the data.</p><h3>Types of Kernels</h3><h3>Polynomial Kernel</h3><p>Creates curved decision boundaries.</p><p>Useful when relationships follow polynomial patterns.</p><h3>RBF (Radial Basis Function) Kernel</h3><p>Most commonly used.</p><p>Can create highly flexible non-linear boundaries.</p><p>Works well for many real-world datasets.</p><h3>Sigmoid Kernel</h3><p>Behaves somewhat like a neural network activation function.</p><p>Less commonly used in practice.</p><h3>6. SVC Practical</h3><p>Typical workflow:</p><ul><li>Create or load dataset.</li><li>Train-test split.</li><li>Standardize features (important for SVM).</li><li>Initialize SVC().</li><li>Fit the model.</li><li>Predict.</li><li>Evaluate using accuracy, confusion matrix, precision, recall, F1 score, and ROC-AUC when needed.</li></ul><p>Python</p><p>Run</p><pre>from sklearn.svm import SVC</pre><pre>svc = SVC()<br>svc.fit(X_train, y_train)<br>y_pred = svc.predict(X_test)</pre><h3>Why is Standardization Important?</h3><p>SVM depends on distance calculations.</p><p>If one feature has values in thousands and another in decimals, the large-scale feature dominates the margin calculation.</p><p>So scaling is almost always recommended.</p><h3>7. SVM Kernel Practical</h3><h3>Linear Kernel</h3><pre>SVC(kernel=&#39;linear&#39;)</pre><h3>Polynomial Kernel</h3><pre>SVC(kernel=&#39;poly&#39;, degree=3)</pre><h3>RBF Kernel</h3><pre>SVC(kernel=&#39;rbf&#39;, gamma=&#39;scale&#39;)</pre><h3>Sigmoid Kernel</h3><pre>SVC(kernel=&#39;sigmoid&#39;)</pre><p>Then compare their performance using:</p><ul><li>Accuracy</li><li>Cross-validation score</li><li>Decision boundary visualization</li></ul><p>Usually RBF performs best for non-linear datasets.</p><h3>8. SVR Practical</h3><p>Workflow:</p><ul><li>Load regression dataset.</li><li>Train-test split.</li><li>Standardize X (and sometimes y).</li><li>Initialize SVR().</li><li>Fit.</li><li>Predict.</li><li>Evaluate using MAE, MSE, RMSE, and R².</li></ul><pre>from sklearn.svm import SVR</pre><pre>svr = SVR(kernel=&#39;rbf&#39;, C=100, epsilon=0.1)<br>svr.fit(X_train, y_train)<br>y_pred = svr.predict(X_test)</pre><h3>Important Hyperparameters</h3><ul><li>C → penalty for errors.</li><li>epsilon → width of the no-penalty tube.</li><li>gamma → influence of individual training points (for RBF kernel).</li></ul><h3>My doubts:</h3><h3>Why is SVM called “Support Vector” Machine?</h3><p>Because only the support vectors (points closest to the margin) determine the final hyperplane.</p><h3>What is the main objective of SVM?</h3><p>Maximize the margin between classes while minimizing classification errors.</p><h3>When should we use SVM?</h3><ul><li>High-dimensional data.</li><li>Text classification.</li><li>Image classification.</li><li>Smaller to medium-sized datasets with clear class boundaries.</li></ul><h3>When is SVM not a great choice?</h3><ul><li>Very large datasets (training can become slow).</li><li>When interpretability is more important than accuracy.</li><li>When data contains many noisy overlapping classes.</li></ul><h3>Difference between Linear Regression and SVR</h3><ul><li>Linear Regression minimizes overall squared error.</li><li>SVR ignores small errors within ε and focuses only on larger deviations.</li></ul><h3>SVM inshort:</h3><ul><li>SVC → Classification</li><li>SVR → Regression</li><li>Hard Margin → No misclassification</li><li>Soft Margin → Allows some misclassification</li><li>C ↑ → Fewer errors, narrower margin, possible overfitting</li><li>C ↓ → Wider margin, better generalization</li><li>SVC uses → Hinge Loss</li><li>SVR uses → Epsilon-insensitive loss</li><li>Kernel Trick → Handles non-linear data</li><li>Most common kernel → RBF</li><li>Always remember → Standardize features before SVM</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54a34ac6cee8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>