<?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 Adesh Anurag on Medium]]></title>
        <description><![CDATA[Stories by Adesh Anurag on Medium]]></description>
        <link>https://medium.com/@adexxhh?source=rss-c6a87246f735------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2RI5OmmjAcinsKPR6rn2-w.jpeg</url>
            <title>Stories by Adesh Anurag on Medium</title>
            <link>https://medium.com/@adexxhh?source=rss-c6a87246f735------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:18:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adexxhh/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[OpenLearn |  PCA for Dimensionality Reduction (Alchemy Edition)]]></title>
            <link>https://adexxhh.medium.com/openlearn-cohort-1-0-w2d13-pca-for-dimensionality-reduction-alchemy-edition-b6eaf33bc866?source=rss-c6a87246f735------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6eaf33bc866</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[openlearn]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[principal-component]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <dc:creator><![CDATA[Adesh Anurag]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 20:49:54 GMT</pubDate>
            <atom:updated>2025-08-28T19:07:41.291Z</atom:updated>
            <content:encoded><![CDATA[<h3>OpenLearn | PCA for Dimensionality Reduction (Alchemy Edition)</h3><blockquote><strong>“When you have eliminated the impossible, whatever remains, however improbable, must be the truth.”</strong><br> ― <em>Sherlock Holmes</em> (The Sign of the Four)</blockquote><h4>Howdy Ninjas!</h4><p><em>(Above is your sign to go read Sherlock Holmes, literary gem!)</em></p><p>Crazy that you all have been learning relentlessly for a while now, pat your backs! 👏 <br>You’ve probably trained models, handled dozens of features, and scratched your head over slow training times, overfitting curves, and confusing feature importance. <em>On the road to becoming a great data scientist? Goodjob.</em></p><p>Today, let’s just work on the problems that y’all have been facing these days (<em>best senior? I know</em> 🆒) Let’s talk — <br>At number 1, we have too many features thus very slow models,<br>Next at 2, multicollinearity and the curse of dimensionality,<br>And finally, high dimensions of data and a very hard time visualizing them all.</p><p>After all this grind this past week, you know now that not all features are equally important to train any kind of model. Some are redundant, noisy or just useless as such. What if you could just compress the data from useless crap to pure gold?<strong><em> Let me pass to you, the mighty scroll of Alchemy — turn all junk data into pure gold.</em></strong></p><p><strong>Today’s Checklist — </strong><br>✅Introduction<br>✅Feature Selection vs Feature Extraction<br>✅Why need PCA?<br>✅Intuition — logical and mathematical <em>(cool math tho)</em><br>✅PCA — when, limitations, real life application<br>✅Implementation — notebook edition</p><h3>Section 1: Introduction</h3><blockquote><strong>“It is a capital mistake to theorize before one has data. Insensibly one begins to twist facts to suit theories.”</strong><br> — <em>Sherlock Holmes (Arthur Conan Doyle)</em></blockquote><p><strong>PCA or <em>Principal Component Analysis</em> </strong>is a mathematical technique that transforms your features into a new set of variables called <strong>principal components</strong>. These components are <strong>uncorrelated</strong> and ordered by how much <strong>variance</strong> they capture from the original data. <em>(so many jargons, we’ll come back to this soon)</em></p><p>We already know about the curse of dimensionality and how multicollinearity can hamper the model to great extents. Modern dataset can have hundreds of features, and not all of them is needed, so the actual game is about handling the right data and let go of the ones that don’t yield us any good. So what do we do?</p><h3>Section 2: Feature Selection vs Feature Extraction</h3><p>In the pool of so many features, we need to be very picky while choosing the right ones <em>(experts at picking? lol)</em> , and we generally have two methods of doing things the right way.</p><p>So, to begin with let’s understand with some examples. <br>Let’s say you are going to organize a hackathon on campus, and you have to make teams and assign work to your peers.</p><p><strong>Scenario 1: </strong>You see there are three people, say Tom, Dick and Harry and all of them have varied skills and could contribute to different domains. Now you have to get the website made, and only Harry knows Web Development. So very apparent, you choose Harry for the job and drop Dick and Harry. (<em>for they would be plain noise in the web-dev team with no skills</em>) <strong>This is Feature Selection.</strong></p><p><strong>Scenario 2: </strong>This time let’s say, all three of them possess the same skill-set and are equally capable of making the website really cool. So you pick all three of them and make a team where all of them can contribute. <strong>This is Feature Extraction.</strong> (cause you made a whole team, so you extracted a new feature and now individually all three of them are irrelevant)</p><p>If you look very closely at both of these examples, you’d notice that, in Scenario 1, the features that all three of them possess are very different and do not overlap (low collinearity), so you went with Feature Selection.</p><p>While in scenario 2, all of them had same kind of features and they overlapped (high collinearity), so you went with Feature Extraction.</p><p><strong><em>The big takeaway — </em></strong><em><br></em>Watchout for how much are the features correlated and what direction they all point at!<br>Also, don’t forget the primary of goal of it all — that is to reduce the number of features needed to train the model, or in simpler terms, <em>cut the noise.</em></p><h3>Section 3 : Why need PCA?</h3><p>You already know that PCA shows up and solves this problem of the curse of dimensionality and multicollinearity. When the dimensions are too much, the data becomes too sparse and hence hard to visualize and for the model to train upon. <br>And when there’s a lot of multicollinearity then it’s very difficult for models like LinearRegression to train over the data without being confused. <br>Another example to understand things better — <br>Let’s say you are building a model, which predicts the price of a housing apartment, and you have features like Room size, Number of rooms, etc., now here both of these features are very important in finding the price of the house, so you can’t dump any of them here. <br><em>Now few check points — <br> </em>✔️ Both room size and number of rooms are important features. Can’t dump anything.<br><em> </em>✔️ Room size and number are rooms, are somehow equally important and there is high correlation, so we need to get it done by Feature Extraction.<br><em> </em>✔️ PCA is one Feature Extraction technique, wherein, we try plotting new axes which captures maximum variance of the data points and not much of the information is lost. (Confusing eh?)</p><p>Let’s zoom out a lil — <br>Presenting to you ninjas some visual cue to understand things better!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iE-my38gXIiGB1Lztca6Ug.png" /></figure><p>Here, in this plot I have tried showing you a linearly related scatter plot between number of rooms and the room size. The dotted lines project these data points on both the axes and shows the <strong><em>spread (variance) </em></strong>of the data points. <br>Now the tricky part is convert this 2 dimensional dataset into 1 dimensional without losing much of the variance. And this is what PCA would do for us, it would draw a line that covers the maximum spread of the data and that would be the new feature (<em>bingo, you’ve extracted a new feature</em>) and the original ones would be now obsolete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBv9xOX2k67H0jB3bmGO6g.png" /><figcaption>here you go</figcaption></figure><p>This red line here, is what we call our <strong><em>Principal Component</em></strong>, and now is the one which accounts for both room size and number of rooms, train you model on this one single feature, and boom you have your model ready.</p><p>Adding to this, when the data points are way too scattered then the direction which has the maximum variance give us the direction of the Principal Component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6ThAKkHxm-a2Wuq_2J7dQ.gif" /><figcaption>something like this</figcaption></figure><p>Sometimes, the data points are so scattered that one single Principal Component could not account for all the variance (<em>again, spread of your dataset</em>), then you need to have one more principal component which is generally perpendicular to the direction of the previous component.<br><strong><em> But why perpendicular to each other? <br></em></strong> — first of all every PC should bring in completely new information.<br> — remember that the prime goal is to reduce the dimensions, so having pc(s) at random slopes would only increase the complexity again, <em>shit show.<br> — </em>generally two orthogonal PCs account for most of your data spread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PH2SP-YpfocDAIT0RqM-ig.png" /><figcaption>something like this, assume them both perpendicular to each other.</figcaption></figure><p>Think of variance as <strong>chaos</strong> — PCA tries to find the <strong>most chaotic direction</strong> in your data.<br>Because the more your data spreads in a direction, the <strong>more there is to learn from it</strong>.<br>That’s why PCA chases variance — not labels, not values — just <strong>spread</strong>.</p><h3>Section 4 : Intuition — logical and mathematical</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mXHZYMsPuoNzBO-81lpa6Q.gif" /><figcaption>me when its math</figcaption></figure><blockquote><strong>PCA finds the directions (axes) along which the data varies the most</strong>, and projects the data onto those axes to reduce dimensionality without losing much information.</blockquote><h3>Step 1: Think of Your Data as Vectors</h3><p>Your dataset is a collection of <strong>data points</strong> (rows), each having <strong>features</strong> (columns).</p><p>If you have:</p><ul><li>n samples (rows)</li><li>d features (columns)</li></ul><p>Then your data is a matrix <strong>X</strong> of shape [n x d].<br>Each data point is a vector in <strong>d-dimensional space</strong>. <em>(1st sem refresher? lol)</em></p><h3>Step 2: Center the Data (Subtract the Mean)</h3><p>To make the math work cleanly:</p><ul><li>You <strong>center</strong> the data by subtracting the <strong>mean</strong> of each column</li><li>So the data is now centered at the origin</li></ul><p>It might be a little difficult to visualize how centering of data is, and what actually happens, so let’s look at an example.<br>Let’s say you have 3 data points with two features: X1 and X2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*qLzLz8SRDLUiinrtc8PeZQ.png" /></figure><p>Now, for these values calculate the mean of each column —</p><ul><li>Mean of X1:<br>(2 + 4 + 6) / 3 = 4</li><li>Mean of X2:<br>(4 + 6 + 8) / 3 = 6<br><strong>So, the mean vector is: μ=(4, 6)</strong></li></ul><p>Now subtract the mean from each of the points —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*JksbNnP0I7HCXuR5EjRS_Q.png" /></figure><p>Hence your centered data looks like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*CxBLUw0VeXLpf2EdD36EAg.png" /></figure><p>Now if it is centered around (0,0) then the mean of this centered data should be 0.</p><ul><li>Mean of centered X1 = -2 + 0 + 2)/3 = 0</li><li>Mean of centered X2 = (-2 + 0 + 2)/3 = 0</li></ul><p><strong><em>What to infer?<br></em></strong>If you plot the <strong>original data</strong>, the points are centered around (4, 6).<br>After centering, they’re centered at (0, 0) — same shape, just <strong>shifted</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1XYkCobmqeLTRUu2aIPbVg.png" /><figcaption>we all need some visuals (enjoy)</figcaption></figure><h3>Step 3: <strong>Compute the Covariance Matrix</strong></h3><p>PCA is all about <strong>finding variance</strong>, and the best way to see how features vary <strong>together</strong> is using a <strong>covariance matrix</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*vqNrMxpcWUL-CZKyzodzWQ.png" /><figcaption>formula for finding covariance matrix.</figcaption></figure><p>where,<br>X(centered) is your data matrix after centering,<br>X^(T)(centered) is the transpose of that centered matrix,<br>1/n is to average the value over all the points.</p><p><strong><em>What actually happens?<br></em></strong>X^(T)(centered) flips your data — now features are <strong>rows</strong> instead of columns.<br>X^(T)(centered) . X(centered) gives you a square matrix that shows <strong>how every feature correlates with every other feature</strong>.<br><strong>1/n</strong> divides by the number of data points to get the <strong>average co-variation</strong>.</p><p>Let’s take another example to understand the intuition behind — <br>Let’s say your dataset (after centering) is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*muTHJyJJMbNT3yOUTQeKBQ.png" /></figure><p>then,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*g81YVRgInms6ywQAivDnyg.png" /></figure><p>and,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*JX_Nj9ka9QEdYgTgEfzkJw.png" /></figure><p>his matrix shows that both features are:</p><ul><li><strong>Positively related</strong> (covariance = 2.67)</li><li><strong>Equally varying</strong> with each other</li></ul><h3>Step 4: <strong>Find the Eigenvectors and Eigenvalues</strong></h3><p>Let’s understand what is PCA’s intention with you data, is he worth your little princess <em>kumari data</em>?</p><blockquote>“I want to rotate the data and find the best <strong>new axes</strong> — the directions in which the data is most spread out (has most variance).” <strong>(open to interpretations)</strong><br> — PCA (the suitable boy)</blockquote><p>So to find these right directions, or to help PCA rotate the data we apply eigen decomposition to the covariance matrix.<br>In PCA’s lingo, <br>Eigenvectors are the directions of the new axes (principal components)<br>while, eigenvalues are the measure of how much variance is captured along each axis.</p><p>Imagine you shine a flashlight from different directions on a cloud of points.</p><ul><li>Each direction you shine the light from = a <strong>candidate eigenvector</strong></li><li>The <strong>length of the shadow</strong> = how much <strong>variance</strong> that direction captures</li></ul><p>PCA says:<br> ➤ <em>“Let’s pick the direction where the shadow is longest.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fYJvW2CXlh3Mb704cCNI3w.png" /><figcaption>i can’t explain why, but yes.</figcaption></figure><h3>Step 5: <strong>Sort and Choose the Top k Eigenvectors</strong></h3><ul><li>Sort eigenvectors by their <strong>eigenvalues</strong> (i.e., how much variance they capture)</li><li>Pick the <strong>top k</strong> to keep</li><li>Form a <strong>projection matrix</strong> from these top eigenvectors</li></ul><p>Just as simple as that, PCA selects the top eigenvectors and that becomes the principal component.</p><h3>Step 6: <strong>Project Data onto New Axes</strong></h3><p>Now in this step, we just project the data points onto this new axes that you have already found out. <br>Finally, you multiply the centered data with the matrix of top eigenvectors:</p><pre>X_reduced = X_centered · W</pre><p>where, W is the projection matrix, that contains the top eigen vectors.</p><p><strong><em>The Result? </em></strong>your data is now in <strong>k-dimensional space</strong> (compressed form) and bingo you just reduced the dimensions and saved your model some serious underperformance and setbacks, <em>it’ll love you forever now! </em>❤️</p><h3>Section 5 : PCA — when, limitations, real life application</h3><p>Now I have already walked you through everything that happens behind the scenes, and you might already know all of this now! PCA is a great tool that makes multiple lives easier — yours, and ofc your model’s too! So let’s look into when to use it, what limitations does this mighty here have and where in real life it comes handy!</p><h3>When Should You Use PCA?</h3><p>Think of PCA as a tool to clean up your dataset by removing redundancy and focusing on what truly matters. It’s helpful when:</p><ul><li>You have a large number of features and want to reduce dimensionality</li><li>You suspect some features are correlated or not contributing much</li><li>You want to improve model performance and reduce overfitting</li><li>You need to visualize high-dimensional data (e.g., reduce to 2D or 3D for plotting.</li></ul><p>In essence:<br> <strong>Use PCA when your data feels noisy, bloated, or overwhelming — and you need a smarter, more compact version of it.</strong></p><h3>Limitations of PCA</h3><p>Despite its usefulness, PCA has a few important limitations to be aware of:</p><ul><li><strong>Assumes linear relationships</strong>: PCA only captures straight-line patterns — it won’t detect curved or complex structures in the data.<em>(oops yes, use it when the relationship between the features that are correlated is linear)</em></li><li><strong>Difficult to interpret</strong>: Principal components are combinations of original features, which can make them hard to explain or relate back to the original problem.</li><li><strong>Sensitive to scaling</strong>: If your features are on different scales, PCA may give biased results. Always standardize your data first.</li><li><strong>Unsupervised nature</strong>: PCA doesn’t consider the target variable. It’s focused purely on the features and variance, not prediction accuracy.</li></ul><h3>Real-Life Applications of PCA</h3><p>PCA is widely used in data science and beyond. Here are a few practical examples:</p><ul><li><strong>Image compression</strong>: Reduce the number of pixels while preserving the visual content by keeping the most informative components.</li><li><strong>Genomics</strong>: Explore relationships and patterns across thousands of gene expression features.</li><li><strong>Finance</strong>: Simplify and analyze stock market data by identifying major trends and reducing noise.</li><li><strong>Anomaly detection</strong>: Find unusual behavior in systems like fraud detection or network monitoring by projecting data into a lower-dimensional space.</li><li><strong>Preprocessing for machine learning</strong>: When working with high-dimensional datasets, PCA helps reduce computational load and improve model performance by eliminating less important features.</li></ul><h3>Section 6 : Implementation of PCA (notebook edition)</h3><p>So, I tried implementing PCA on an easy dataset for you all to see how to do it in actual terms after all this theory. This completes this package that comes with classified theory and hands on training on this beautiful ML tool. Go on now, get some dirt onto your cuffs and enjoy.</p><p><em>Follow this hyperlink, to land onto my kaggle notebook —</em></p><p><a href="https://www.kaggle.com/code/adeshanurag/pca-trial-run">PCA Trial Run — a beginner’s edition made with love</a></p><h4><strong>So now it’s homework time! ⏰</strong></h4><ul><li>Try appling your PCA skills on this notebook, and also try predicting using the models that you have learnt till now. <em>(No pressure) — <br></em><a href="https://www.kaggle.com/code/kamyarazar/breast-cancer-classification-using-pca-in-python/notebook">Homework kaggle notebook</a></li><li>Keep posting up on socials, enjoy the small wins! Clapping for you all always.</li></ul><h4>Previous and Next-</h4><ul><li>previous — <a href="https://medium.com/@sharmaachintya49/bfca107eeb48">OpenLearn Cohort 1.0 | W2D12 : Hierarchical Clustering — The K-Means Killer?</a></li><li>next —<a href="https://medium.com/@thackershubham374/805b821271e8"> OpenLearn Cohort 1.0 | W2D14: From Chaos to Clarity: Visualizing Data with t-SNE</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6eaf33bc866" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenLearn Cohort 1.0 | W1D7 : k-NN Classifier on Iris Dataset]]></title>
            <link>https://adexxhh.medium.com/openlearn-cohort-1-0-w1d7-k-nn-classifier-on-iris-dataset-9191dad1d22e?source=rss-c6a87246f735------2</link>
            <guid isPermaLink="false">https://medium.com/p/9191dad1d22e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[knn-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Adesh Anurag]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 19:09:04 GMT</pubDate>
            <atom:updated>2025-08-29T04:57:11.784Z</atom:updated>
            <content:encoded><![CDATA[<h3>OpenLearn | k-NN Classifier on Iris Dataset</h3><blockquote>“Simplicity is the ultimate sophistication.”<br> — Leonardo da Vinci</blockquote><h4>Here we meet again ninjas!</h4><p>You all have made it to the week of actual battles, you’ve bled data, you reek of python’s venom and you’ve mastered regression the old friend. Now I have the honor to welcome you to the new chapter of this training.</p><p><strong><em>The mighty classification! <br></em></strong>In this chapter you’d have to conquer some classification rolls (ninja shit is real in my head) and add new weapons into your arsenal!</p><p>Today we are going to go a little easy on this starter villain (soon to be a friend), <em>since he’s the infamous lazy algorithm!</em></p><p><em>Ninja checkpoints for today — </em><br>🥷Introduction to k-NN<br>🥷When to use k-NN<br>🥷Dataset Overview <br>🥷How does it work?? (Reading the scroll)<br>🥷Implementation<br>🥷Counting + and -</p><h4>Section 1: Introduction to k-NN</h4><blockquote><strong>“The best way to understand a data point is to see who it hangs out with.”</strong><br> —one of Vatsal’s close friend</blockquote><p>k-NN or <strong><em>“k” Nearest Neighbors</em></strong> is one of the simplest and the most popular classification and regression classifier used in machine learning today. <br>In the world of machine learning, not all models have the same learning trajectory, some like most of engineering students sit back and relax. <em>k-NN is one of those brats, it likes to relax, observe, remember, and act only when asked to. <br></em>So, why are we even talking about k-NN? Seems like some guy who is good for nothing, but remember that’s what people think of us engineering students until we show what we are truly made of! <br>k-NN despite being one of the simplest classification algo but is super effective at times (<em>king of good times? RCB yay</em>)</p><p>Now what is the basic principle that this algo works upon? As Vatsal’s close friend rightly quoted, <strong>k-NN classifies new data points based on the majority class of their “k” closest data points</strong> in the training set (okay, go back, read again)<br>Let’s imagine you’re going to buy a flat (one day🤞) and you don’t know if the flat is haunted or not, so you go on and ask the nearest neighbors (guy living opposite, above and below maybe). Two of your beloved neighbors confirm of no hauntings, while the one living below confirms the ghost (bro wants some peace above), so 2–1, clearly the house is not haunted, and bingo you just classified it.</p><p>This is how simple working with k-NN could be, all you need to do is — <br>1️⃣ Ask the right question,<br>2️⃣ Ask to the right number of people.<br>Also before we move on, and just in case you didn’t catch it, the <strong><em>“k”</em></strong> in k-NN is the number of neighbors we’re asking the question, or technically its the number of neighboring data points that we consider to classify our query data point.</p><h4>Section 2: When to use k-NN</h4><blockquote>“No equations, no assumptions — just let the data speak for itself. That’s the k-NN way.”<br>- some k-NN junkie</blockquote><p>Now we know that k-NN is one simple, lazy algorithm, which means that the use case of this algo is quite limited and using it at the right time is very very important.<em> You miss out on this and all you have is : bananas being classified as humans. 🍌<br></em>Use this in situations where intuition matters as much as math, and we call it lazy because it doesn’t build any model while training and only give results when asked to.</p><p>🔴Before we move on to opening the scroll, let’s get to know some of the technical terms that you should be aware of —</p><p>k-NN requires two main parameters to classify any data point<br><strong><em>First being the distance of the query point</em></strong> (the data point in question) t<strong><em>o all the data points nearby </em></strong>(nearest neighbors)<br>And <strong><em>second is the number of neighbors we want our algorithm to look at</em></strong>.</p><p><strong><em>Pro tip: A</em></strong>lways try choosing an odd number, as even number can cause ties, and hence faulty classification. <br>For example, in the haunted house case if we had asked <em>4 nearest neighbors about the ghost and had it ended on a tie, i.e., 2–2 votes then it would have been a confusing task to decide for the pyaasi aatma.</em></p><p><strong>Understanding what is distance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRhvMTI4NQ3a4IIpgNQhfQ.png" /><figcaption>distance is all that matters</figcaption></figure><p><strong><em>Highlights of the ninja scroll</em></strong></p><p>📜 <strong>Small to medium-sized datasets</strong>: k-NN checks every point at prediction time, so it works best when data is manageable in size.<br>📜<strong>Well-labeled, clean data</strong>: It performs well when your data is labeled correctly and doesn’t have too much noise (<em>noise is the random and meaningless data that doesn’t represent the true pattern you’re trying to learn, makes it harder for your model to hear the real message</em>)<br>📜<strong>When relationships are local</strong>: If nearby data points tend to share the same label (like handwritten digits or flower species), k-NN works beautifully. (That we’d see with the Iris dataset :))<br>📜<strong>Low-dimensional data</strong>: Works better when there aren’t too many features — because in high dimensions, “closeness” loses meaning (<em>curse of dimensionality</em>).</p><p>The fault of simple things is that they have a very narrow sphere for application, it’s important to know where not to apply them —</p><p>❌<strong>Large datasets</strong>: It gets slow, since it has to scan the whole dataset every time you predict. (it’s like classifying a fish, in an ocean full of fishes. Any random fish can be in the nearest neighborhood of your fish)<br>❌<strong>High-dimensional data</strong>: Distance calculations become unreliable when there are too many features. <br>❌<strong>Unscaled features</strong>: If your data isn’t normalized, some features might dominate the distance metric and lead to poor results. (okay, here we need some talking. I believe most of you know what normalization is, but for the sake of this blog,</p><p><strong><em>Example time —</em></strong></p><p>Let’s say you are comparing two people on how similar they are. And you are using parameters like “height” and “salary”. <br>Now, when k-NN tries to find the “distance” between people, it adds these numbers together. But here’s the problem:</p><ul><li>Height values usually range from 150 to 200 in cms.</li><li>Income values can range from 1000 to 10000 maybe in rupees.</li></ul><p>Since income is in a much larger range, it dominates the calculation — even though <strong>height might be more important</strong> for your problem. Hence it’s like judging people on the basis of money just because it’s a bigger number, k-NN would ignore important features like height, weight, age, etc., to compare two people, which is kinda wrong.</p><p>This is why we normalize that is to bring all the parameters in the same range (like 0 and 1), so that each feature contributes fairly to the distance calculation.</p><blockquote>“If your data is compact, well-behaved, and locally clustered — k-NN might just be the friend you need.”</blockquote><p>Now you know what is k-NN and when to use it, let’s now use it on some real dataset, and find the right flower for your partner. (hehe 😆)</p><h4>Section 3: Database Overview (Iris)</h4><p>The <strong>Iris dataset</strong> is one of the most famous datasets in machine learning and statistics. It was introduced by the British statistician <strong>Ronald A. Fisher</strong> in 1936 and is often the “hello world” for classification problems.</p><p>What all is in this dataset?<br>It contains <strong>150 samples</strong> of flowers from <strong>3 species</strong> of iris:</p><ul><li><strong>Setosa</strong></li><li><strong>Versicolor</strong></li><li><strong>Virginica</strong></li></ul><p>Each sample (row) has <strong>4 numerical features</strong>:</p><ol><li><strong>Sepal Length (cm)</strong></li><li><strong>Sepal Width (cm)</strong></li><li><strong>Petal Length (cm)</strong></li><li><strong>Petal Width (cm)</strong></li></ol><p>And one <strong>target label</strong>: the species of the flower.</p><p><strong><em>Structure of the Data:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*mzyDFd7cVxOowec8IW2mVg.png" /></figure><ul><li>There are <strong>50 samples</strong> for each class.</li><li>Features are continuous and fairly well-behaved.</li><li>Some classes (like Setosa) are clearly separable, while others (Versicolor vs Virginica) overlap a bit.</li></ul><p>The <em>reason for the popularity </em>of this data set is simply because <em>it’s small and easy to handle</em>, this makes it perfect for classification. Also it could be <em>visualized very easily</em> as we’ll see later in this blog. It comes <em>built in with scikit-learn, so no need for any download</em>. (Hassle free)</p><p><strong><em>How is this “The Dataset” for learning classification?</em></strong></p><ul><li>It’s <strong>balanced</strong> across classes,</li><li>The features are <strong>numeric</strong>, ideal for distance-based algorithms,</li><li>You rookie ninjas can clearly see how distance between points affects classification.</li></ul><h4>Section 4: How does it work? + Implementation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*s-IuFkogfzU4CdIN3iYbuA.gif" /><figcaption>let’s roll in</figcaption></figure><p>Remember how you’d think all the flowers are the same, but she wouldn’t ? — (for boys)<br>Remember how he only knows roses and chameli / jasmine(thankyou bollywood) — (for girls)</p><p>Let me solve that problem for once and for all! (i still think marigold and sunflower are the same, but who cares it’s my blog HAHAHA)</p><p>We’ll now walk through how to apply k-NN step by step using Python and scikit-learn, one of the most popular machine learning libraries. The goal? To predict the species of an iris flower based on its sepal and petal measurements.</p><blockquote>Think of it like a flower-picking ninja: we’ll measure the petals and sepals, compare distances, and classify our flower with confidence!</blockquote><p><em>First Step:</em> Ninja, first up is something you’ve been doing all week, import all the libraries:</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.metrics import accuracy_score, confusion_matrix, classification_report</pre><p>Here, I believe you know almost all of the libraries, the only new thing here is <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html"><strong>KNeighborsClassifier</strong></a>, which but obvious is the ML model which implements the k-NN classification algorithm on the provided dataset.</p><p><em>The things that it does, in a nutshell — </em><br>📜<strong><em>Looks at the “k” nearest neighbors in the training data set</em></strong> (using the distance metric, found using Euclidean or Manhattan distance, search them up — homework)(hint — both stand true to their names, very funny)</p><p>📜<strong><em>Checks the majority class among those </em></strong><strong><em>k neighbors. </em></strong>(same old democracy shit)</p><p>📜<strong><em>Assigns that class to the new data point. </em></strong>(just how Trump wins American election, but not Elon’s heart aww)</p><p><em>Step 2 boss:</em> Load the Iris Data from scikit-learn, this is what you would have been expecting right? (right? don’t say no 🔪)</p><pre>iris = load_iris()<br>X = iris.data         # Features (sepal &amp; petal length/width)<br>y = iris.target       # Target (species)</pre><p>Now, understand why we have two parameters X and y, this is because remember at the start of this blog while discussing what is distance, we had seen a plot, <strong>where there were two axes</strong>? k-NN works in a way which is very easy to visualize. <br>You put the features on the x-axis, and the target on the y-axis and you plot all the know data points, then the query point is put on this plot with the values of its features and the closest neighbor points decide it’s class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQILTIL6X6FoouMa_np5pw.png" /></figure><p>Here, in this plot if you put any random fruit anywhere using the parameter of crunchiness (feature) and sweetness as the target, <em>k-NN would measure the distance from it’s nearest neighbors and classify it as either a banana or a potato.</em> (don’t ignore the orange, go eat one and stay hydrated 🍊)</p><p><em>Step 3 Ninja: </em>Some basic data exploration (ik you’ve all mastered it by now)</p><pre>print(&quot;Feature names:&quot;, iris.feature_names)<br>print(&quot;Target names:&quot;, iris.target_names)<br>print(&quot;First 5 samples:\n&quot;, X[:5])</pre><p><em>Step 4</em>: Another known step, split the data so that you can use some for testing later.</p><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42<br>)</pre><p><em>Step 5:</em> Okay so we have already discussed this next step, that is, to scale the data, if you don’t remember scroll up (if you do it I’d kill you, but nvm 👌)</p><pre>scaler = StandardScaler()<br>X_train = scaler.fit_transform(X_train)<br>X_test = scaler.transform(X_test)</pre><p>Remember scaling is very important to maintain accuracy while using k-NN, never skip this step. Let master Oogway rest in peace 🐢</p><p><em>Step 6: </em>Train the k-NN Classifier, here it comes, yoohoo machine learning</p><pre>knn = KNeighborsClassifier(n_neighbors=3)  # You can tweak k later!<br>knn.fit(X_train, y_train)</pre><p>And there it goes, it seems very funny to me how to make you guys understand these two lines of code, we had to go through all this writing and reading, but for what it is worth, kudos you are now a classifier.</p><p>Here, <strong><em>n_neighbors = 3</em></strong> , is the number of neighbors that you’ve made your k-NN model pick from the dataset. <em>By default this value is 5.</em></p><p><em>Step 7:</em> Let’s do some predictions, machine learning paying off!!</p><pre>y_pred = knn.predict(X_test)</pre><p>Step 8: Let’s now use the metrics and see how good does our model perform over the test data —</p><pre>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))<br>print(&quot;Confusion Matrix:\n&quot;, confusion_matrix(y_test, y_pred))<br>print(&quot;Classification Report:\n&quot;, classification_report(y_test, y_pred, target_names=iris.target_names))</pre><p>Here the only thing that I think you would be unaware about is the Confusion Matrix, so let me put some light: <br>A confusion matrix is simply a table, which shows how good your model performed, it shows all the points where it predicted the values right and where it got confused! (Hence the name)</p><p>Now let’s see what would happen if we go around playing with the number of nearest neighbors, that is to tune the values of <strong><em>“k” —</em></strong></p><pre>import matplotlib.pyplot as plt<br><br>k_values = list(range(1, 21))<br>accuracies = []<br><br>for k in k_values:<br>    knn = KNeighborsClassifier(n_neighbors=k)<br>    knn.fit(X_train, y_train)<br>    acc = accuracy_score(y_test, knn.predict(X_test))<br>    accuracies.append(acc)<br><br>plt.plot(k_values, accuracies, marker=&#39;o&#39;)<br>plt.title(&quot;Accuracy vs. K Value&quot;)<br>plt.xlabel(&quot;k&quot;)<br>plt.ylabel(&quot;Accuracy&quot;)<br>plt.show()</pre><p>Now, guys I know, I haven’t provided you with the expected outputs, because I think that way you would never try this Iris Dataset on your own which ofcourse would not be a big issue, but since this is the first time you’re doing classification I want you to actually write all these stuffs first before moving on and classifying other data sets. Also this way you could keep my code under check, ping me if there’s any fallacy.</p><p>Also kudos, you’re now a prime time classifier!! You know your flowers!</p><p>Coming to the last section for this blog, that is counting the merits and demerits of k-NN as a classifier algorithm!</p><h4>Section 5: Counting + and -</h4><blockquote>“k-NN is easy to train but hard to trust blindly — distance can be deceiving.”<br> — some guy with a failed LDR *sob sob</blockquote><p><strong><em>Counting all the good first — <br></em></strong>Now i believe after all this reading you are capable enough to spot the goods, but still listing the book lingo for reference (😫)</p><ul><li><strong>Simple &amp; Intuitive — </strong>Easy to understand and implement — just count your neighbors!</li><li><strong>No Training Phase — </strong>It’s a <strong>lazy learner</strong>: it stores the training data and only does the work during prediction.</li><li><strong>Works Well on Small Datasets — </strong>Great for low-dimensional and clean datasets like Iris.</li><li><strong>Flexible — </strong>Can be used for <strong>classification</strong> or <strong>regression</strong> tasks.</li><li><strong>Naturally Multiclass — </strong>No need for complex tweaks to handle multiple classes.</li><li><strong>Non-Parametric — </strong>Makes <strong>no assumptions</strong> about data distribution (unlike logistic regression, etc.)</li></ul><p><strong><em>Coming to the bads/negatives now — <br></em></strong>Book lingo incoming 🚀</p><ul><li><strong>Slow Predictions on Large Datasets — </strong>Has to compute the distance to <strong>every training point(</strong>can be very inefficient with lots of data).</li><li><strong>Sensitive to Irrelevant Features — </strong>Extra noise or unimportant features can mislead the model.</li><li><strong>Needs Feature Scaling — </strong>If features aren’t normalized, those with larger scales dominate the distance calculation.</li><li><strong>Struggles with High-Dimensional Data — </strong>Suffers from the <strong>curse of dimensionality</strong> — distances become less meaningful.</li><li><strong>No Model Insight — </strong>Doesn’t give you feature importance or model coefficients; it’s a “black box” in terms of interpretability.</li><li><strong>Memory Intensive — </strong>Stores the entire training set (can be heavy on RAM for large datasets).</li></ul><p>With this being listed (I’m sure you knew all of this) it’s time to finally <strong>bid goodbye to k-NN</strong>, thanks ninjas for sticking by, I know my blogs are long stuff, but I try to put everything that I can, so that you don’t have to scrape the internet later (<em>but hey, do scrape there’s always some good thing to dig in</em>)</p><h4>Some additional resources —</h4><ul><li><a href="https://scikit-learn.org/stable/modules/neighbors.html#classification">Scikit-learn| k-NN</a></li><li><a href="https://cheatography.com/aggialavura/cheat-sheets/python-k-nearest-neighbors-knn-model/?utm_source=chatgpt.com">Cheatography | k-NN</a></li></ul><h4>Now it’s homework time ⏰</h4><ul><li>Download this real dataset and apply k-NN classification end to end. (don’t forget what you’ve learned beforehand, all strings attached)<br><a href="https://www.kaggle.com/datasets/rakeshrau/social-network-ads/data">https://www.kaggle.com/datasets/rakeshrau/social-network-ads/data</a></li><li>Don’t forget to post and keep the socials engaged, speak everything you want to, I’d listen close. 👂</li></ul><h4>Previous &amp; Next —</h4><ul><li>previous — <a href="https://medium.com/@kunalkashyap2417/openlearn-w1-d6-from-clueless-to-classifier-a-beginners-guide-to-logistic-regression-20c909d83932">W1-D6 : From Clueless to Classifier: A Beginner’s Guide to Logistic Regression</a></li><li>next — <a href="https://medium.com/@kunalkashyap2417/openlearn-cohort-1-0-w1d8-decoding-decisions-your-friendly-guide-to-decision-trees-fe295786abe8">W1D8 : Decoding Decisions: Your Friendly Guide to Decision Trees</a></li></ul><h3>Thankyou for Reading ! Happy Learning.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9191dad1d22e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenLearn | Data Analysis Refresher: NumPy, Pandas, EDA]]></title>
            <link>https://adexxhh.medium.com/openlearn-cohort-1-0-w0-d2-data-analysis-refresher-numpy-pandas-eda-490f47fa3b74?source=rss-c6a87246f735------2</link>
            <guid isPermaLink="false">https://medium.com/p/490f47fa3b74</guid>
            <category><![CDATA[eda]]></category>
            <category><![CDATA[openlearn]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[numpy]]></category>
            <dc:creator><![CDATA[Adesh Anurag]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 08:37:37 GMT</pubDate>
            <atom:updated>2025-08-28T19:09:29.635Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>“In God we trust, all others must bring data.”</strong><br> — <em>W. Edwards Deming</em></blockquote><p><strong>Hello Learning Geeks! 👻<br></strong>Yesterday you all learned about setting up the battleground for the next couple of months + how to tame <em>“the python” </em>+ using powerful tools like kaggle! Let’s dive into what this cohort was originally meant for, some data, some coffee, and a lot more fun!<br>Today we’ll try hover over the real land of data science, spanning all over in a bird’s view, I’d try show you how fascinating it becomes when the mathematical powerhouse — NumPy, and Excel on steroids — Pandas come hand in hand.</p><p><strong><em>What are we going to learn today?<br></em></strong>✅Refresher on NumPy<br>✅Pandas Essentials <br>✅Exploratory Data Analysis<br>✅See what the next few days would look like (hehe 😾)</p><h3><strong>SECTION 1: Refresher on NumPy</strong></h3><blockquote><strong>“NumPy is like giving Python a calculator upgrade.”<br>- </strong><em>some nerd from IT</em></blockquote><p>To begin with, NumPy is the unsung hero behind operations on numbers. Imagine playing with jigsaw puzzles where none of the pieces fit, this is how working with raw python lists when working with large datasets feels like. Here enters NumPy — <strong><em>Numerical Python </em></strong>a library that gives python the edge in scientific computing and data analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*kM5rQZIpBAjbs7UkqUWJdg.webp" /></figure><h4><strong><em>Why NumPy matters?</em></strong></h4><p>Have you ever tried adding two lists in python?</p><pre>a = [1,2,3]<br>b = [4,5,6]<br>print(a+b)</pre><p>Now, you might think that the outcome for this little code snippet here, would be : [5,7,9]</p><p>but, the outcome comes out to be:</p><pre>[1,2,3,4,5,6]</pre><p>This happens because python lists are not made to do mathematical operations, all they do is contain characters. They are the no good containers.</p><p>But don’t cry little ninjas, NumPy hops into the chat*</p><p>NumPy has made working with numbers faster, easier and very efficient. NumPy comes in with a very useful object called the NumPy Array, which is a supercharged version of the normal Python lists, super powerful for numerical operations.</p><pre>import numpy as np<br>a = np.array[1,2,3]<br>b = np.array[4,5,6]<br><br>print(a+b)</pre><p>Now the outcome is what we all were looking forward to. Congratulations ninjas👏</p><pre>[5,7,9]</pre><p>Here you go, this god’s favorite child adds all the numbers directly and does it very fast, even when you work with millions of numbers. This is called <strong><em>vectorization</em></strong>, which is way faster than using python loops. (iykyk)</p><p>Some extra info :<br>Many of the other python libraries that are very important (and in some way indispensable) and are used in data science and machine learning, are primarily built on NumPy or use its arrays underneath.</p><p>Note these pointers ninjas, <br> — <em>If you understand NumPy better, then you could easily get hold of the other libraries.<br></em> — <em>If some anomalies show up in other libraries, knowing NumPy could help you at times.</em></p><p>Now in our mission of understanding NumPy, next up we need to know some of the core concepts.</p><h3>Core Concepts 🚋</h3><h4><strong><em>ndarrays and its properties</em></strong></h4><p>At the heart of NumPy is the ndarrays, short of n-dimensional array. This supercharged version of lists can hold a grid of numbers (1D, 2D, or any random n dimensions)<br>Let’s see how 💡</p><pre>import numpy as np<br>arr = np.array([1, 2, 3])</pre><p>This creates a 1 dimension NumPy array, which unlike normal python arrays, have some special properties-</p><pre>print(arr.ndim)  # Number of dimensions → 1<br>print(arr.shape) # Shape → (3,)<br>print(arr.dtype) # Data type → int64 (or int32)</pre><p>All of these properties can help you look through your data and see the structure of your data in a glance.</p><h4><strong><em>Vectorized Operations vs Python Loops</em></strong></h4><p>Using NumPy arrays can help us bypass long lines of codes for operations like multiplying the elements of the array by a number.<br>For example, if you want to multiply the array by 2, then</p><p>NOOB WAY-</p><p>Here a loop is used, which-<br> — more lines of codes<br> — it is slower for big lists<br> — not very elegant and<em> ‘its not giving’ </em>guys</p><pre>arr = [1,2,3]<br>arr2 = []<br><br>for num in arr:<br>  arr2.append(num*2)<br><br>print(arr2)</pre><p>NINJA WAY-</p><pre>import numpy as np<br>arr = np.array([1,2,3])<br>arr2 = arr*2<br><br>print(arr2)</pre><p><em>Now this is giving</em> 🔥<br>Some more examples, this is how cool vectorized operations are-</p><pre>import numpy as np<br>arr = np.array([1, 2, 3, 4])<br><br># Multiply every number by 3<br>print(arr * 3)     # [3 6 9 12]<br><br># Add 5 to every number<br>print(arr + 5)     # [6 7 8 9]<br><br># Square every number<br>print(arr ** 2)    # [1 4 9 16]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*oNWBZm0m3Zxmv47TlcupSA.gif" /></figure><p><strong><em>Broadcasting</em></strong></p><p><strong>Broadcasting</strong> lets NumPy perform operations on arrays of different shapes as long as they are <em>compatible</em>.</p><pre>arr = np.array([1, 2, 3])<br>print(arr + 10)</pre><p>Even though <strong>10</strong> is just a single number (a scalar), NumPy “broadcasts” it to match the shape of the array, and adds it to every element.</p><h4>Indexing, Slicing, and Reshaping</h4><p>Indexing;<br>Access elements of the list as-</p><pre>arr = np.array([10, 20, 30])<br>print(arr[1])  # Output: 20</pre><p>Slicing;<br>Get a part of the list as-</p><pre>print(arr[0:2])  # Output: [10 20]</pre><p>Reshaping;<br>Turn a 1D array into a 2D array:</p><pre>arr2 = np.array([1, 2, 3, 4, 5, 6])<br>arr2_reshaped = arr2.reshape(2, 3)<br>print(arr2_reshaped)</pre><p>Output-</p><pre>[[1 2 3]<br> [4 5 6]]</pre><p>Reshaping is super useful in machine learning, matrix math and image processing.</p><p><em>Moving on, next up is another important library.. drumrollss..</em></p><h3>SECTION 2: Pandas Essentials</h3><blockquote>“Pandas didn’t just read the CSV — it read my mind.”<br> — on some random tombstone.</blockquote><h4>Introduction to Pandas</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_dPvVzuQMvQyq1SyMdH5w.png" /></figure><p>Imagine working with some messy data in a giant spreadsheet, could be sales numbers, marks scored, survey responses, scientific databases, etc., and you as a data scientist are required to clear, analyze trends, or just find who got the highest marks. Here’s where pandas enters the chat.</p><p>Pandas is a <strong>Python library</strong> that gives you powerful tools to:<br> — Organize the data into tables (aka DataFrames)<br> — Clean it (fixing values, imputing missing values, removing duplicates)<br> — Analyze it (group, sort, filter)<br> — Visualize and export the data</p><p>To understand how does pandas work, we need to understand the different components, i.e. series and DataFrame.</p><h4>Series Vs DataFrame</h4><p>Imagine you’re working with data like a student’s marks.</p><p><strong><em>Series<br> — </em></strong>A <strong>Series</strong> is like <strong>one column</strong> of data, a <strong>single list with labels</strong>.<br> — Think of it like a <strong>vertical list</strong>: marks of one student in different subjects.</p><pre>import pandas as pd<br><br>marks = pd.Series([85, 90, 78], index=[&quot;Math&quot;, &quot;Science&quot;, &quot;English&quot;])<br>print(marks)</pre><p>Output-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*ekOcdGv8pzpVPkrWed2qJA.png" /></figure><p>Series are like dictionaries, with keys(index) and values(data).</p><p><strong><em>DataFrame<br> — </em></strong>A <strong>DataFrame</strong> is like a <strong>full table </strong>with<strong> </strong>multiple columns and rows.<br> — Think of it like a <strong>whole class’s mark sheet</strong>, where each column is a subject and each row is a student.</p><p>Let’s see a sample code-</p><pre>import pandas as pd<br>data = {<br>    &quot;Math&quot;: [85, 70, 90],<br>    &quot;Science&quot;: [90, 75, 88],<br>    &quot;English&quot;: [78, 80, 85]<br>}<br><br>df = pd.DataFrame(data, index=[&quot;Raju&quot;, &quot;Kaju&quot;, &quot;Baju&quot;])<br>print(df)</pre><p>Output-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*i6SmNY5NKs5N81-XLn9dQA.png" /></figure><p>Kudos, now you have a full table in spreadsheet to analyze and manipulate.</p><h4>Reading and Writing Files in Pandas</h4><p>Imagine someone working on a dataset of 1000s of columns, rows and a hell lot of values, reading and working on all that can be one tedious job. But pandas would pull this shit in seconds!! Hail Pandas 🐼!</p><p>Let’s say someone sends you a .<strong><em>csv </em></strong>file (like an Excel sheet) with 1000 rows of data — Pandas can <strong>read it instantly</strong> with just one line.</p><p><strong><em>Reading a csv file:</em></strong></p><pre>import pandas as pd<br>df = pd.read_csv(&quot;students.csv&quot;)</pre><p>This would load the csv file into the DataFrame.<br>You can now read, analyze, change the files.</p><p><strong><em>Writing in a csv file:</em></strong></p><pre>df.to_csv(&quot;new_students.csv&quot;, index=False)</pre><p>This saves your modified DataFrame into a CSV file.<br>index=False avoids writing row numbers to the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*tebYrQhWCES7vL-1TbCMqQ.gif" /><figcaption>(anime butts drive me nuts)</figcaption></figure><h4>DataFrame Operations</h4><p>Let’s say a <strong>DataFrame</strong> is like a supercharged Excel table, with <strong>rows and columns, </strong>but in Python, and way more powerful.<br>After a data frame is made (obviously by loading the data) a hell lot of different operations could be performed on it, some of which are:</p><p><strong><em>Indexing, Selecting, Filtering Rows/Columns</em></strong></p><p>For the time being, let’s understand using this sample dataframe.</p><pre>import pandas as pd<br><br>data = {<br>    &#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;],<br>    &#39;Age&#39;: [25, 30, 35],<br>    &#39;City&#39;: [&#39;Delhi&#39;, &#39;Mumbai&#39;, &#39;Chennai&#39;]<br>}<br><br>df = pd.DataFrame(data)</pre><p>Now various selection operations could be:<br>Selecting a column;</p><pre>df[&#39;Age&#39;]</pre><p>Selecting multiple columns;</p><pre>df[[&#39;Name&#39;, &#39;City&#39;]]</pre><p>Filter rows;</p><pre>df[df[&#39;Age&#39;] &gt; 28]  # Only rows where Age &gt; 28</pre><p>Use of .loc[] and .iloc[]</p><pre>print(df.loc[0, &#39;Age&#39;])  # or<br><br>print(df.iloc[0, 1])  # Age of the first person (Alice)<br><br>#expected outcome<br>#25<br>#25</pre><p>In simple words, these two tools can be used to access specific rows and columns in two different ways, <strong>.loc[] </strong>can be used to “access by location”, i.e., by the use of the labels. <br>While the <strong>.iloc[] </strong>is used to access the rows or columns by the use of the index/positions.</p><h4>Handling Missing Values</h4><p>Sometimes data is incomplete. Pandas makes it easy to handle missing entries, all of these little steps can be incorporated in all the cases of datatypes.</p><pre>df = pd.DataFrame({<br>    &#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, None],<br>    &#39;Age&#39;: [25, None, 35]<br>})</pre><p>Detect missing value;</p><pre>df.isna()</pre><p>Removing missing value;</p><pre>df.dropna()</pre><p>Filling the missing values;</p><pre>df.fillna(&#39;Unknown&#39;)       # For text<br>df.fillna(df[&#39;Age&#39;].mean()) # For numbers</pre><h4>Data Types and Conversions</h4><p>You can check and convert column data types (like int, float, string):</p><pre>df.dtypes           # Check data types<br>df[&#39;Age&#39;] = df[&#39;Age&#39;].astype(int)  # Convert to integerl.</pre><h4>Aggregations and Grouping</h4><p>Great for summarizing and comparing data across categories.</p><p><strong><em>groupby</em></strong></p><pre>df = pd.DataFrame({<br>    &#39;Department&#39;: [&#39;HR&#39;, &#39;IT&#39;, &#39;HR&#39;, &#39;IT&#39;],<br>    &#39;Salary&#39;: [40000, 60000, 45000, 70000]<br>})<br><br>df.groupby(&#39;Department&#39;)[&#39;Salary&#39;].mean()</pre><p><strong><em>Output:</em></strong></p><pre>Department<br>HR    42500<br>IT    65000</pre><p><strong><em>agg for multiple stats:</em></strong></p><pre>df.groupby(&#39;Department&#39;)[&#39;Salary&#39;].agg([&#39;mean&#39;, &#39;max&#39;, &#39;min&#39;])</pre><p><strong><em>pivot_table for summaries:</em></strong></p><pre>pd.pivot_table(df, index=&#39;Department&#39;, values=&#39;Salary&#39;, aggfunc=&#39;mean&#39;)</pre><p>Think of pivot_table like Excel’s Pivot Table, but smarter and in code.</p><h4>Data Transformation</h4><p><strong>Apply Functions: </strong><strong>apply, </strong><strong>map, </strong><strong>lambda</strong></p><p>Apply a custom function to your data:</p><pre>df[&#39;Bonus&#39;] = df[&#39;Salary&#39;].apply(lambda x: x * 0.10)</pre><p>apply: works on rows/columns<br>map: works on single columns (Series)</p><h4>Sorting</h4><p>Sort values in ascending/descending order:</p><pre>df.sort_values(by=&#39;Salary&#39;, ascending=False)</pre><h4>Merging DataFrames: merge, concat, join</h4><p>Imagine combining multiple spreadsheets:</p><p><strong><em>Merge by column:</em></strong></p><pre>pd.merge(df1, df2, on=&#39;EmployeeID&#39;)</pre><p><strong><em>Concatenate vertically:</em></strong></p><pre>pd.concat([df1, df2])</pre><h4>Renaming and Reshaping</h4><p><strong><em>Rename columns:</em></strong></p><pre>df.rename(columns={&#39;Salary&#39;: &#39;Monthly_Salary&#39;})</pre><p><strong><em>Reshape with </em></strong><strong><em>melt (wide → long):</em></strong></p><p>melt() turns multiple columns into one, making your data longer and easier to analyze or visualize.</p><pre>pd.melt(df, id_vars=[&#39;Name&#39;])</pre><p>So, that is all the pandas that you would be required by you to know as you’re starting out with machine learning. <br>But now that you already know enough, let’s do some more pre-building learning !</p><h3>Section 3: Exploratory Data Analysis (EDA)</h3><blockquote><em>“Before you model like a boss, explore like a detective. That’s EDA.”<br> — Fred Datasucker (made up data scientist)</em></blockquote><h4>The name is cool, but what is EDA?</h4><p>Imagine getting a brand-new dataset — rows, columns, numbers, and text. You could just jump into machine learning… but would you build a house without first checking the ground?</p><p>That’s where <strong>Exploratory Data Analysis (EDA)</strong> comes in.</p><p>Picture this: You, the data analyst, are <strong>Sherlock Holmes</strong>, and your dataset is a <strong>crime scene file</strong> full of hidden clues, red herrings, and unexpected twists.</p><p>Your goal? Solve the mystery behind the data before building a case (i.e., your ML model).</p><p><strong><em>Step 1: Examining the Case File (Understanding the Data)</em></strong></p><blockquote>“Watson, how many witnesses do we have? What are their names? Who is missing?”</blockquote><ul><li>Use .shape, .columns, and .info()</li><li>Find out the <strong>structure</strong>, <strong>column names</strong>, and <strong>missing entries</strong></li><li>You’re laying out the crime scene before diving in</li></ul><pre>df.info()<br>df.head()</pre><p><strong><em>Step 2: Looking for Clues (Summary Statistics)</em></strong></p><blockquote>“What’s the average age of the suspects? Any extreme values?”</blockquote><ul><li>Use .describe() to get <strong>mean</strong>, <strong>min</strong>, <strong>max</strong>, <strong>standard deviation</strong></li><li>Catch <strong>outliers</strong> and <strong>strange values</strong> — your “odd suspects”</li></ul><pre>df.describe()</pre><p><strong><em>Step 3: Spotting Anomalies (Data Cleaning)</em></strong></p><blockquote>“Aha! A man listed as 200 years old? Either a vampire or a typo.”</blockquote><ul><li>Look for missing values with .isna(), fix them with fillna() or dropna()</li><li>Check for incorrect data types or inconsistent formatting</li></ul><pre>df[&#39;Age&#39;].isna().sum()<br>df[&#39;Age&#39;].fillna(df[&#39;Age&#39;].median())</pre><p><strong><em>Step 4: Visualizing the Crime Scene (Visual EDA)</em></strong></p><blockquote>“A pattern emerges when you step back and look at the big picture.”</blockquote><p>Use visual tools like:</p><ul><li>Histograms for distributions</li><li>Boxplots for outliers</li><li>Scatter plots for relationships</li><li>Heatmaps for correlation</li></ul><pre>import seaborn as sns<br>sns.boxplot(x=df[&#39;Income&#39;])<br>sns.heatmap(df.corr(), annot=True)</pre><p><strong><em>Step 5: Connecting the Dots (Grouping and Patterns)</em></strong></p><blockquote>“Let’s compare alibis — who earns more, and who spends more?”</blockquote><ul><li>Use .groupby() and .agg() to <strong>summarize by group</strong></li><li>Check how <strong>features relate</strong> to one another</li></ul><pre>df.groupby(&#39;Occupation&#39;)[&#39;Income&#39;].mean()</pre><h4><strong><em>The Conclusion</em></strong></h4><blockquote>“Elementary, my dear Watson. The data always tells a story — if you ask the right questions.”</blockquote><p>EDA is how Sherlock would handle data:</p><ul><li>Observing patterns</li><li>Questioning anomalies</li><li>Digging deeper</li><li>Never assuming</li></ul><p>This was all from the case files of the legendary sleuth, Mr. Sherlock Holmes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*x_1JUlWwFNncQQvnbVdfBQ.gif" /></figure><p>Considering that this particular read was a little too long, and now it’s time to call it a day with some cheat sheets and resources to keep you ninjas engaged in ML forever. HAHAHA 😆</p><h4>Resources &amp; Add ons</h4><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//pandas.pydata.org/Pandas_Cheat_Sheet.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e3cb8678a3b54e0e635a83e31e6065a/href">https://medium.com/media/0e3cb8678a3b54e0e635a83e31e6065a/href</a></iframe><p><a href="https://numpy.org/doc/stable/user/quickstart.html">NumPy quickstart - NumPy v2.3 Manual</a></p><h4>Tasks for today</h4><ul><li>In the given kaggle data set, do the necessary data cleaning and analysis: <a href="https://www.kaggle.com/datasets/ramjidoolla/ipl-data-set">https://www.kaggle.com/datasets/ramjidoolla/ipl-data-set</a></li><li>Share your learnings on social media platforms, tagging OpenLearn.</li></ul><h4>Previous &amp; Next:</h4><ul><li><strong><em>next</em></strong> : <a href="https://medium.com/@thackershubham374/c3ccf534bbe1">W0D3 : From Plots to Predictions: A Beginner’s Guide to Matplotlib, Seaborn &amp; Scikit-learn</a></li><li><strong><em>previous</em></strong> : <a href="https://medium.com/@sharmaachintya49/openlearn-cohort-1-0-w0d1-python-setup-kaggle-basics-and-working-dec42499dae0">W0D1 : Python Setup/Kaggle basics and Working</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=490f47fa3b74" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>