<?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 ThakkarrShubham on Medium]]></title>
        <description><![CDATA[Stories by ThakkarrShubham on Medium]]></description>
        <link>https://medium.com/@thackershubham374?source=rss-e20e6a066cb1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*sqJZUSpa1lZV1vlt</url>
            <title>Stories by ThakkarrShubham on Medium</title>
            <link>https://medium.com/@thackershubham374?source=rss-e20e6a066cb1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:10:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thackershubham374/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 Cohort 1.0| W2D14: From Chaos to Clarity: Visualizing Data with t-SNE]]></title>
            <link>https://medium.com/@thackershubham374/openlearn-cohort-1-0-w3d1-from-chaos-to-clarity-visualizing-data-with-t-sne-805b821271e8?source=rss-e20e6a066cb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/805b821271e8</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[ThakkarrShubham]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 06:22:23 GMT</pubDate>
            <atom:updated>2025-08-29T04:54:06.350Z</atom:updated>
            <content:encoded><![CDATA[<h3>OpenLearn| W2D14: From Chaos to Clarity: Visualizing Data with t-SNE</h3><blockquote>“Data is messy, life is messier — but hey, at least we can reduce dimensions.”<br> — Dr. Dimen S. Ional</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*P6qSfX7bfkAzupdf.jpeg" /></figure><p><strong>Hola Learners!!</strong></p><p>Good to see you again. In last blog you were introduced to the concept of dimensionality reduction using PCA. PCA is the go-to technique for squashing high-dimensional data into fewer dimensions. It’s fast, interpretable, and mathematically elegant. But it is a linear method (i.e PCA only <strong>rotates, scales, or shifts</strong> the data in straight lines. It doesn’t bend or curve the space.). Hence PCA cannot cannot capture non linear relations between features. So to capture such relations and visualise high dimension data in lower dimensions, t-SNE: t-distributed Stochastic Neighbor Embedding, (Don’t get overwhelmed by this complex name, we will cleary understand what does it means in a while) is used. Let’s look at an example where PCA fucks up and t-SNE comes as a saviour!!</p><p>We will be using swiss roll dataset, which is very commonly for testing dmensionality reduction techniques. Its it basically s an <strong>artificial 3D dataset</strong> that looks like a <strong>rolled-up sheet or spiral ribbon</strong> — much like a Swiss roll cake.</p><p>Each datapoint has 3 features, X-coordinate, Y-Coordinate , Z-coordinate. So out plot will be a 3d plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Oa75Y7QF3o1bk9-Xuu2Tdw.png" /></figure><p>This plot looks very difficult to understand. So let us try to transform features such that most of the information is captured in 2 dimensions.</p><p>Here’s the plot after applying PCA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-z9oD8OgW0Lu0qHp5YtjMA.png" /></figure><p>See it’s totally messed up!! All he clusters in the original data are destroyed. So the information about the similarity between points in a cluster is lost.</p><p>Now to solve this issue, lets try t-SNE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SESwUXHP8B54mm74ZyoyXw.png" /></figure><p>Much better!! The clusters in the original data are preserved.</p><p><strong>Why did this happen?</strong></p><p>This is because PCA focuses on preserving the global structure of the data. It finds directions (principal components) where the data <strong>varies the most </strong>and projects data along those directions to <strong>retain as much information (variance)</strong> as possible.</p><p>While t-SNE focuses on preserving local relationships. t-SNE tries to <strong>keep nearby points close together</strong> in the low-dimensional space. It doesn’t care much about global geometry or variance.</p><p>Hence it is excellent for <strong>finding clusters</strong> and <strong>visualizing embeddings</strong> like word vectors or image features, but it’s <strong>not good for feature reduction</strong> or downstream modeling (using its output as input for the model).</p><h3>Understanding t-SNE</h3><p>Let us start by understanding its name.</p><ul><li><strong>t-distributed</strong> : It uses t-distribution (type of probability distribution similar to normal distribution) for computing similarity between two points in lower dimensional space.</li><li><strong>Stochiatic :</strong> It uses probabilty of two points being in a same cluster instead of distance. Distances are converted to probability first</li><li><strong>Neighbor : </strong>It focuses on preserving local relations.</li><li><strong>Embedding :</strong> It maps higher dimensional data to lower dimension.</li></ul><p><strong>Now lets see step by step what’s going on under the hood( The Maths Magic)</strong></p><h4>Step 1: Compute Pairwise Similarities in High-D (Gaussian Kernel)</h4><p>In this step, selecting one point at a time, we will transform the distance from other points to the conditional probability P i|j that express How likely is it that point Xi​ picks point Xj​ as a neighbor?</p><p>This is based on a <strong>Gaussian centered at Xi</strong>.</p><p>But wait!! why am i transforming distances to probabilities? Can’t I just use distance and run a clustering algorithm to determine clusters?</p><p>As you also know the answer is no, otherwise we wouldn’t be discussing this. Let us find out why?</p><p>This is because distances become meaningless in high dimension.</p><p>Because in high dimensions:</p><ul><li>All distances tend to <strong>converge</strong> — nearest and farthest neighbors become <strong>similarly far</strong>.</li><li>This is part of the <strong>curse of dimensionality</strong>.</li></ul><p>So if we naively try to preserve raw distances, we’ll get <strong>garbage embeddings</strong>.</p><p>Now you would think why is it so? Lets find out!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*aZt1ysFNZu3xdhmiLoBavw.png" /></figure><p>Then the <strong>coefficient of variation</strong> (relative spread) is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*lUb8nng9t9qvuOXJRTzd-A.png" /></figure><p>This means:</p><blockquote><em>As D increases, the </em><strong><em>spread of distances becomes negligible</em></strong><em> compared to their mean — so </em><strong><em>all distances converge around the same value.</em></strong></blockquote><p>This is the <strong>core of distance concentration.</strong></p><p>Therefore,</p><ul><li>Even though the <strong>mean distance increases</strong> with D,</li><li>The <strong>spread of distances increases much more slowly</strong>.</li><li>So: the <strong>difference between nearest and farthest neighbor shrinks in percentage terms</strong>.</li></ul><blockquote><em>In high-D, all distances are ≈ the same. There’s no meaningful “near” or “far”.</em></blockquote><p>Now we know why do we transform raw distance to conditional probability, lets look at how do we do it?</p><h4><strong>1. Define a Similarity Score</strong></h4><p>We begin by defining an <strong>unnormalized similarity</strong> between Xi and Xj​, using a <strong>Gaussian kernel</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*A2_PxNo5aBmYBPqyuLHmQw.png" /></figure><p>This formula comes directly from the <strong>probability density function (PDF)</strong> of a Gaussian:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*YZa_FaYc1DoTTRhV1_XkZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*3KsbS8cYZEcP_ppUQ8VW6g.png" /></figure><h4><strong>2.Normalize Across All Points</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*BOjquLvCeDjDCDRTgdik4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*BmpSbL8ArfDQ3DuGErkLsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*ay4rolLMckn7Z85DpnlL2A.png" /></figure><h3>Why Use a Gaussian?</h3><p>The Gaussian kernel has several desirable properties:</p><ul><li>Assigns <strong>high weight</strong> to nearby points.</li><li>Decays <strong>rapidly</strong> for distant points.</li><li>Is <strong>differentiable</strong>, which helps for optimization.</li></ul><p>Also, in <strong>probabilistic terms</strong>, this is equivalent to assuming:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aREv6IS8mekB93L8W9VGYQ.png" /></figure><p>So you’re modeling each point’s <strong>local neighborhood</strong> as a probability distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*z-4q-xe0Qs1O-gDyqFDhuQ.png" /></figure><p>Different regions of your data may have different densities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZlzxNzGAgfxSjbnS.png" /></figure><p>In region with low density, we need distribution to have more spread i.e. high standard deviation so that even some distant points have significant probability, while high density region needs less spread and hence low standard deviation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4_vdIPIGgBS0Uk65.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*PqkpfZw6y4CYiogWJ-HnGA.png" /></figure><h4>Now how do we determine the standard deviation corresponding to each point?</h4><p>To do this, we pass a parameter called <strong>perplexity</strong>, which can be thought of as the <em>effective number of neighbors</em> each point should consider. Internally, t-SNE uses <strong>binary search</strong> to find a standard deviation (σ) for each point such that the resulting probability distribution over its neighbors has the desired perplexity.</p><p>However, the final 2D embedding is <strong>highly sensitive</strong> to the perplexity value you choose. There’s no exact formula or universal algorithm to determine the “best” perplexity — it depends on the dataset’s structure and density.</p><p>So in practice, we try <strong>different perplexity values</strong> (typically between 5 and 50) and <strong>visually inspect</strong> the resulting embeddings. We adjust the value based on how well the clusters are separated, how much crowding there is, and whether the global and local structures are preserved.</p><p>After doing all these, what do we get??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EEQS87kfBtWjGU1e7pH6ZA.png" /></figure><h3><strong>Step 2: Symmetrizing</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CrAzfD958wcsPiSeA3hvtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*K644kDNaqH9vuTe2c_gbMQ.png" /></figure><h3>Step 3: Initialize Low-D Points</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJxubve5JRq8U1lFno-0fQ.png" /></figure><h3>Step 4: Compute Similarities in Low-D (t-distribution)</h3><p>So far, we’ve seen how t-SNE uses a <strong>Gaussian distribution</strong> in high-dimensional space to convert distances into probabilities — assigning high similarity to nearby points and low similarity to distant ones.</p><p>But when it comes to <strong>low-dimensional space (like 2D)</strong>, t-SNE does something clever.</p><p>It replaces the Gaussian with a <strong>Student’s t-distribution</strong>, specifically with <strong>1 degree of freedom</strong> — also known as the <strong>Cauchy distribution</strong>.</p><p>Now what the hell is t-distribution? And why to use it in lower dimension instead of Gaussian (Normal) distribution?</p><h4>t-distribution:</h4><blockquote><em>The </em><strong><em>t-distribution</em></strong><em> is used when we work with a </em><strong><em>sample drawn from a larger population</em></strong><em> that follows a </em><strong><em>Gaussian distribution</em></strong><em>, but the </em><strong><em>population standard deviation is unknown</em></strong><em> and must be estimated from the sample.</em></blockquote><blockquote><em>Because we’re using a </em><strong><em>noisy estimate of the standard deviation</em></strong><em>, the result is </em><strong><em>extra uncertainty</em></strong><em> — especially in small samples. This makes the </em><strong><em>t-distribution more sensitive to extreme values</em></strong><em> (like outliers), since any outlier in a small sample has a </em><strong><em>larger impact</em></strong><em> than it would in the full population.</em></blockquote><blockquote><em>To reflect this increased uncertainty, the t-distribution has a </em><strong><em>wider spread</em></strong><em> and </em><strong><em>fatter tails</em></strong><em> compared to the normal distribution.<br> In other words, the probability of observing values far from the mean </em><strong><em>decays more slowly</em></strong><em>, because we’re less confident about where the “typical” data should lie.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lTdc01NWWIHmVYD5.png" /></figure><p>First let us see how we will transform the distances in lower dimension to probability with t-distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*bQqHkyEKXVEHLkSTAYGITw.png" /></figure><h4>Now why do we need it here?</h4><p>This is because of the <strong>crowding problem</strong>.</p><p>In high-dimensional space:</p><ul><li>You have <strong>many</strong> “far-away” points for each data point</li><li>But you can <strong>spread them far apart</strong>, because there’s a lot of space</li></ul><p>In low-dimensional space (like 2D):</p><ul><li>There’s <strong>less room</strong></li><li>So it’s <strong>impossible</strong> to spread dissimilar points as far apart as they are in high-D</li></ul><p>The result?</p><blockquote><strong><em>Unrelated points appear closer than they should</em></strong><em> → All clusters get </em><strong><em>squashed into the center</em></strong><em>.</em></blockquote><p>This is the <strong>crowding problem</strong>.</p><h3>Why the t-Distribution Helps?</h3><p>The <strong>t-distribution has heavy tails</strong>. Therefore, it allows larger gaps between dissimilar points. Let&#39;s see how?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npTvdHcbXDEsZmkSWQwHzg.png" /></figure><p>This is because of the loss function we will define KL Divergence, which we will create ourselves from scratch later in the blog. At first glance it might look scary but stay me.</p><p>KL Divergence Is Asymmetric — It Amplifies the Repulsion</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OPB-y-G_jGFDbyQRkTSkQ.png" /></figure><h4>Step 5: Determining a loss function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drRoQFjYQVIohBkbYQZaQw.png" /></figure><h4>2. Expected Surprise if Reality Follows P</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FyEuY-6iQYtH_mCf94m8A.png" /></figure><h4>But What If We Had Used the Right Distribution?</h4><p>If we used P itself to encode events drawn from P, we’d just compute the regular entropy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*_KoUt08_5yzjFHzkIO5DVQ.png" /></figure><h4>3. Difference Between the Two = KL Divergence</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hNQrqDif391M6O9NyBnyzQ.png" /></figure><p>And here we get the formula for KL divergence. Which we would minimize</p><h4>4. Optimizing Yi with Gradient Descent</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8fzC2REOoPAY6VXjcsa_w.png" /></figure><h3>Extra Tricks t-SNE Uses</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNVVDF5vCpjqd3aGriTHDA.png" /></figure><p>You can study about these techniques on your own.</p><h4>Final Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dv7OhDo6YqVUMaYSQ8HGmw.png" /></figure><p>So now we have completely understood the theoretical part of t-sne; how it works under the hood.</p><p>Now we would learn how to use it practically. Let&#39;s dive into the code.</p><p>For the demonstration we will use the popular breast cancer dataset.</p><p>Each sample (tumor) has <strong>30 numerical features</strong>, which are <strong>statistics</strong> computed from a digitized image of a fine-needle aspirate (FNA) of a breast mass.</p><p>These include:</p><ul><li><strong>Mean</strong>, <strong>standard error</strong>, and <strong>worst</strong> (largest) values of the following:</li><li>Radius (mean of distances from center to points on the perimeter)</li><li>Texture (standard deviation of gray-scale values)</li><li>Perimeter</li><li>Area</li><li>Smoothness</li><li>Compactness</li><li>Concavity</li><li>Concave points</li><li>Symmetry</li><li>Fractal dimension</li></ul><p>So, for example:</p><ul><li>mean radius</li><li>mean texture</li><li>worst perimeter</li><li>concavity error<br> ... are some of the feature names.</li></ul><p>In total:</p><ul><li>10 measurements × 3 kinds (mean, error, worst) = 30 features</li></ul><h4>why this dataset?</h4><ul><li>It has <strong>30 features</strong>, making it hard to visualize directly.</li><li>It has <strong>some nonlinear structure</strong> that’s captured better by t-SNE than PCA.</li><li>The samples are <strong>clustered</strong> based on tumor type, so a good dimensionality reduction technique should <strong>separate the two classes clearly</strong> in 2D.</li></ul><p>So this is all we need to know about the dataset so now lets start coding.</p><h4>Step 1: Import Required Libraries</h4><pre>import matplotlib.pyplot as plt<br>from sklearn.datasets import load_breast_cancer<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.manifold import TSNE</pre><h4>Step 2: Load and Preprocess the Data</h4><p>We’ll load the data, standardize the features, and extract the labels.</p><pre># Load the dataset<br>data = load_breast_cancer()<br>X = data.data               # shape: (569, 30)<br>y = data.target             # 0 = malignant, 1 = benign<br>target_names = data.target_names<br><br># Standardize the features (important for t-SNE)<br>scaler = StandardScaler()<br>X_scaled = scaler.fit_transform(X)</pre><h4>Step 3: Run t-SNE</h4><p>We reduce the 30-dimensional data to 2D for visualization.</p><pre># Create t-SNE model<br>tsne = TSNE(n_components=2, perplexity=30, learning_rate=200, n_iter=1000, random_state=42)<br><br># Fit and transform the data<br>X_embedded = tsne.fit_transform(X_scaled)  # shape: (569, 2)</pre><h3>Notes:</h3><ul><li>perplexity=30: reasonable default, can try 5–50.</li><li>n_iter=1000: sufficient for most datasets.</li><li>random_state=42: ensures reproducibility.</li></ul><h4>Step 4: Visualize the 2D Embedding</h4><p>We’ll plot the points in 2D space and color them based on their labels.</p><pre># Plot the 2D t-SNE result<br>plt.figure(figsize=(8, 6))<br><br># Malignant (0) in red, Benign (1) in green<br>plt.scatter(X_embedded[y == 0, 0], X_embedded[y == 0, 1], label=target_names[0], alpha=0.6, c=&#39;r&#39;)<br>plt.scatter(X_embedded[y == 1, 0], X_embedded[y == 1, 1], label=target_names[1], alpha=0.6, c=&#39;g&#39;)<br><br>plt.title(&quot;t-SNE Visualization of Breast Cancer Data&quot;)<br>plt.xlabel(&quot;Component 1&quot;)<br>plt.ylabel(&quot;Component 2&quot;)<br>plt.legend()<br>plt.grid(True)<br>plt.tight_layout()<br>plt.show()</pre><p>This is the output we got after t-sne.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*RYQgiKx8M-NsX-_T0EKGIA.png" /></figure><p>As we can see, t-sne has done a decent job in clustering. Even though it is not perfect, it is pretty decent. We can try some other values of perplexity to improve it.</p><p>Congrats learners!! With that, we’ve covered the complete intuition, mathematics, and implementation of t-SNE — from theory to practical usage.</p><p>Understanding t-SNE not only deepens your grasp of dimensionality reduction but also builds a strong foundation in optimization, probability distributions, and information theory — all essential topics in machine learning.</p><p>Remember: like all tools, t-SNE works best when used with awareness of its assumptions and limitations. Now that you understand its inner workings, you’re ready to apply it more confidently in real-world problems.</p><p>Now that you know <strong>what t-SNE does and how it works</strong>, let’s move on to today’s task and apply it in code.</p><h3>Task 1: Visualize Effect of Perplexity</h3><p>Use the same dataset (Breast Cancer or Digits) and:</p><ul><li>Try different perplexities (5, 20, 50)</li><li>Plot all results side-by-side</li><li>Analyze how cluster shapes and separations change</li></ul><h3>Task 2: Label a Few Points on the t-SNE Plot</h3><p>Pick a few random samples and display their actual data values (mean radius, texture, etc.) on the plot — helps build understanding of feature relationships.</p><h4>Previous &amp; Next:</h4><p>Previous: <a href="https://medium.com/@adeshanurag50/openlearn-cohort-1-0-w2d13-pca-for-dimensionality-reduction-alchemy-edition-b6eaf33bc866">PCA for Dimensionality Reduction (Alchemy Edition)</a></p><p>Next: <a href="https://medium.com/@ratinder4954/openlearn-cohort-1-0-w2d15-spotting-the-odd-ones-out-your-guide-to-anomaly-detection-e4fb039ded8f">Spotting The Odd One’s out : Your guide To Anomaly Detection</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=805b821271e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenLearn | W0D3 : From Plots to Predictions: A Beginner’s Guide to Matplotlib, Seaborn &…]]></title>
            <link>https://medium.com/@thackershubham374/openlearn-w0d3-from-plots-to-predictions-a-beginners-guide-to-matplotlib-seaborn-c3ccf534bbe1?source=rss-e20e6a066cb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3ccf534bbe1</guid>
            <dc:creator><![CDATA[ThakkarrShubham]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 12:20:16 GMT</pubDate>
            <atom:updated>2025-06-15T12:20:16.543Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>OpenLearn Cohort 1.0| W0D3 : </strong>From Plots to Predictions: A Beginner’s Guide to Matplotlib, Seaborn &amp; Scikit-learn</h3><blockquote>“The journey of a thousand miles begins with a single step.”<br> — Lao Tzu</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*N3qyOoVHL9YPjZ_R.jpeg" /></figure><p><strong>Welcome Back, Learner!</strong></p><p>In the last blog you just stepped into this limitless world of data. As now you have learnt about viewing and manipulating data using Pandas and Numpy, now we will learn to get insights from the data. We will learn to visualize it and gain insights from it.</p><p>In today’s age of information, data is the most valuable thing. How are such magical looking things like LLMs possible? Just because of a huge amount of data. Data visualization is a powerful tool which helps us to see patterns in the data and makes its study easier. To do so we need to select appropriate , preprocess the data and train the model with it.</p><p>Now after studying the data and gaining insights from it, its time to use the data to make predictions. To make predictions first we need to select appropriate model based on the results we got from data analysis.</p><h3>What we will learn today?</h3><p>→ Matplotlib : Important terms and some common types of plots.</p><p>→ Seaborn : Some more useful plots that are diffcult to make with Matplotlib.</p><p>→ Scikit Learn : Introduction to the most used machine learning library , its components and their application.</p><h3>So let’s dive into it!!</h3><blockquote><strong>1) Matplotlib</strong></blockquote><p>Matplotlib is a powerful library to create various kind of plots and visualize data.</p><p>It is opensource and gives us complete access to the properties of our plots and figures. Hence it can be used to create highly customized plots as per our need. Therefore it is the most widely used library for data visualization.</p><p>Let’s create our first plot using matplotlib :</p><pre>import matplotlib.pyplot as plt<br><br>x = [1, 2, 3, 4]<br>y = [10, 20, 25, 30]<br><br>plt.plot(x, y)<br>plt.title(&quot;Simple Line Plot&quot;)<br>plt.xlabel(&quot;X Axis&quot;)<br>plt.ylabel(&quot;Y Axis&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*3zxG27j9-OQVGDAt8OwV6g.jpeg" /></figure><p><em>Key Terms in Matplotlib:</em></p><ol><li>Pyplot : A submodule in matplotlib that makes plotting easier — like drawing with simple commands. Think of it as your drawing assistant.</li><li>plot() : The basic function to draw a line plot. You give it X and Y values.</li><li>figure : The entire canvas or window that holds your plot(s). You can have multiple figures in a script.</li><li>axes : The actual plot area where data is drawn — every chart lives inside an axes. A single figure can have multiple axes (subplots).</li><li>xlabel / ylabel : Functions to add labels to the X and Y axis.</li><li>title() : Adds a title to the plot.</li><li>legend : Adds a legend when you have multiple plots or lines.</li><li>grid() : Adds grid lines to the plot for better readability.</li><li>show(): Displays the plot. Without this, your chart might not appear (especially in scripts).</li><li>savefig() : Saves your plot as an image file (PNG, JPG, PDF, etc.).</li><li>subplot(): Lets you draw multiple plots inside a single figure in a grid layout.</li><li>style() : Matplotlib supports different plot styles (&#39;ggplot&#39;, &#39;seaborn&#39;, etc.) to quickly change the look.</li><li>marker : The symbol used for points in a line or scatter plot (like &#39;o&#39;, &#39;*&#39;, &#39;^&#39;).</li><li>linestyle : Controls the line pattern: solid (&#39;-&#39;), dashed (&#39;--&#39;), dotted (&#39;:&#39;), etc.</li><li>color : You can set line/bar colors using names (&#39;red&#39;, &#39;blue&#39;), hex codes (#ff5733), or short codes (&#39;r&#39;, &#39;g&#39;, &#39;b&#39;).</li></ol><h3><strong>Types of Plots</strong></h3><ol><li>Line Plot :</li></ol><p>Best for showing trends over a continuous range (like time).</p><pre>import matplotlib.pyplot as plt<br><br># Data for plotting<br>x = [1, 2, 3, 4, 5]<br>y = [10, 12, 15, 13, 17]<br><br># Create a line plot with markers and style<br>plt.plot(x, y, color=&#39;green&#39;, linestyle=&#39;--&#39;, marker=&#39;o&#39;, label=&#39;Growth&#39;)<br><br># Add title and axis labels<br>plt.title(&#39;Line Plot Example&#39;)<br>plt.xlabel(&#39;Time&#39;)<br>plt.ylabel(&#39;Value&#39;)<br><br># Add legend and grid<br>plt.legend()<br>plt.grid(True)<br><br># Auto-adjust layout to prevent overlap<br>plt.tight_layout()<br><br># Display the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*he3iIlo423IShe64Gxcm7g.png" /></figure><p>2. Bar Plot :</p><p>Used for comparing categories.</p><pre>import matplotlib.pyplot as plt<br><br># Categories and corresponding values<br>categories = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]<br>values = [5, 7, 3]<br><br># Create a vertical bar chart<br>plt.bar(categories, values, color=&#39;skyblue&#39;)<br><br># Add title and axis labels<br>plt.title(&#39;Bar Plot Example&#39;)<br>plt.xlabel(&#39;Category&#39;)<br>plt.ylabel(&#39;Values&#39;)<br><br># Auto-adjust layout to prevent overlap<br>plt.tight_layout()<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*R99i5gUpjZINfhcYi8e3Qw.png" /></figure><p>3. Horizontal Bar Plot Barh :</p><p>When you have long category names or want to emphasize comparison across categories in a horizontal layout.</p><pre>import matplotlib.pyplot as plt<br><br># Categories and corresponding values<br>categories = [&#39;Data Cleaning&#39;, &#39;Visualization&#39;, &#39;Modeling&#39;, &#39;Deployment&#39;]<br>values = [25, 40, 20, 15]<br><br># Create a horizontal bar chart<br>plt.barh(categories, values, color=&#39;mediumseagreen&#39;)<br><br># Add title and axis labels<br>plt.title(&#39;Horizontal Bar Plot Example&#39;)<br>plt.xlabel(&#39;Time Spent (%)&#39;)<br>plt.ylabel(&#39;ML Workflow Stages&#39;)<br><br># Add grid lines for readability<br>plt.grid(axis=&#39;x&#39;)<br><br># Adjust layout<br>plt.tight_layout()<br><br># Display the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*byOSeDlM9-Gus-um0Acpog.png" /></figure><p>4. Scatter Plot:</p><p>Shows relationship between two numerical variables.</p><pre>import matplotlib.pyplot as plt<br><br># Two numeric variables<br>x = [5, 7, 8, 7, 2, 17]<br>y = [99, 86, 87, 88, 100, 86]<br><br># Create a scatter plot<br>plt.scatter(x, y, color=&#39;red&#39;, marker=&#39;x&#39;)<br><br># Add title and axis labels<br>plt.title(&#39;Scatter Plot Example&#39;)<br>plt.xlabel(&#39;X Values&#39;)<br>plt.ylabel(&#39;Y Values&#39;)<br><br># Add grid<br>plt.grid(True)<br><br># Adjust layout<br>plt.tight_layout()<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*OBUCY3AnYkXwg_93CI5zBQ.png" /></figure><p>5. Histogram</p><p>Used to visualize the distribution of a numeric variable.</p><pre>import matplotlib.pyplot as plt<br><br># Numeric dataset<br>data = [1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6]<br><br># Create histogram with bins<br>plt.hist(data, bins=5, color=&#39;orange&#39;, edgecolor=&#39;black&#39;)<br><br># Add title and axis labels<br>plt.title(&#39;Histogram Example&#39;)<br>plt.xlabel(&#39;Bins&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br><br># Add grid<br>plt.grid(True)<br><br># Adjust layout<br>plt.tight_layout()<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*2VWGTYijvbzDRNZSIOhAjg.png" /></figure><p>6. Pie Chart</p><p>Good for showing part-to-whole relationships.</p><pre>import matplotlib.pyplot as plt<br><br># Labels and values<br>labels = [&#39;Apples&#39;, &#39;Bananas&#39;, &#39;Cherries&#39;, &#39;Dates&#39;]<br>sizes = [15, 30, 45, 10]<br><br># Create a pie chart with percentage display<br>plt.pie(sizes, labels=labels, autopct=&#39;%1.1f%%&#39;, startangle=140)<br><br># Add a title<br>plt.title(&#39;Pie Chart Example&#39;)<br><br># Adjust layout to fit the circle properly<br>plt.tight_layout()<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*n63dxoM5spF8olYeQNwsvw.png" /></figure><p>7. Subplots ( Multiple axes in one figure)</p><pre>import matplotlib.pyplot as plt<br><br># Create a 2x2 grid of subplots<br>fig, axs = plt.subplots(2, 2, figsize=(10, 6))  # 2 rows, 2 columns<br><br># Subplot 1: Line Plot<br>x = [1, 2, 3, 4, 5]<br>y = [10, 12, 15, 13, 17]<br>axs[0, 0].plot(x, y, color=&#39;blue&#39;, marker=&#39;o&#39;)<br>axs[0, 0].set_title(&#39;Line Plot&#39;)<br>axs[0, 0].set_xlabel(&#39;X&#39;)<br>axs[0, 0].set_ylabel(&#39;Y&#39;)<br><br># Subplot 2: Bar Chart<br>categories = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]<br>values = [5, 7, 3]<br>axs[0, 1].bar(categories, values, color=&#39;orange&#39;)<br>axs[0, 1].set_title(&#39;Bar Chart&#39;)<br><br># Subplot 3: Scatter Plot<br>x2 = [5, 7, 8, 7, 2, 17]<br>y2 = [99, 86, 87, 88, 100, 86]<br>axs[1, 0].scatter(x2, y2, color=&#39;green&#39;)<br>axs[1, 0].set_title(&#39;Scatter Plot&#39;)<br><br># Subplot 4: Histogram<br>data = [1, 1, 2, 2, 2, 3, 3, 4, 5, 5, 5, 6]<br>axs[1, 1].hist(data, bins=5, color=&#39;purple&#39;, edgecolor=&#39;black&#39;)<br>axs[1, 1].set_title(&#39;Histogram&#39;)<br><br># Automatically adjust layout to prevent overlapping elements<br>plt.tight_layout()<br><br># Display the full plot grid<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*JUnGX-wOwnNRdaEmXOkEnA.png" /></figure><blockquote><strong>2. Seaborn</strong></blockquote><p>While Matplotlib gives you full control over plot elements, <strong>Seaborn</strong> is like its stylish, smart cousin — it makes your plots <strong>prettier</strong>, <strong>simpler</strong>, and <strong>more informative</strong> with <strong>less code</strong>.</p><p>Seaborn is a powerful Python library built on top of Matplotlib that is specifically designed for <strong>statistical data visualization</strong>. It works seamlessly with pandas DataFrames and makes it easy to create plots that not only look great but also reveal patterns in your data.</p><p><strong>Why Use Seaborn?</strong></p><ul><li>Built-in themes and color palettes for <strong>attractive visuals</strong></li><li>Built-in support for <strong>statistical plots</strong> like boxplots, violin plots, and pair plots</li><li>Works smoothly with <strong>pandas DataFrames</strong></li><li>Ideal for <strong>exploratory data analysis (EDA)</strong> in machine learning workflows</li></ul><p><strong>Key Terms in Seaborn :</strong></p><ol><li>Hue : Adds a third variable by grouping data using color</li><li>Style : Differentiates categories using marker style (mostly in scatter/line plots)</li><li>size : Differentiates categories using point sizes (in scatterplots)</li><li>palette : Defines the color scheme (e.g. &#39;deep&#39;, &#39;pastel&#39;, &#39;coolwarm&#39;)</li><li>context : Sets plot size elements for different contexts (&#39;paper&#39;, &#39;talk&#39;, etc.)</li><li>theme / set_theme() : Controls overall styling (background, gridlines, etc.)</li><li>FacetGrid : Grid layout for plotting multiple subplots based on row/column categoriese</li><li>catplot() : A figure-level function for categorical plots like bar, box, etc.</li><li>replot() : A figure-level function for relationship plots (scatter, line).</li><li>distplot() : A figure-level function to show distributions (hist, kde)</li><li>ax : A Matplotlib axes object that Seaborn can draw on.</li><li>kind : Specifies type of plot within multi-purpose functions (e.g., &#39;scatter&#39;, &#39;line&#39;, &#39;bar&#39;)</li></ol><p>Now lets look at some plots frequently used in Machine Learning.</p><ol><li>countplot() – Categorical Frequency:</li></ol><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br># Load a built-in dataset<br>titanic = sns.load_dataset(&quot;titanic&quot;)<br><br># Countplot shows the frequency of each category in a column<br>sns.countplot(data=titanic, x=&#39;class&#39;, palette=&#39;pastel&#39;)<br><br># &#39;palette&#39; sets the color theme<br># &#39;x&#39; is the categorical column being plotted<br><br>plt.title(&quot;Passenger Class Count&quot;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*lC8QZobBxKHrIzYLaLuHGA.png" /></figure><p>2. boxplot() – Distribution with Summary Stats :</p><p>A <strong>boxplot</strong> (also called a <strong>box-and-whisker plot</strong>) is a <strong>statistical graph</strong> that shows the <strong>distribution</strong> of a dataset based on <strong>five summary statistics</strong>:</p><ol><li><strong>Minimum</strong> (excluding outliers)</li><li><strong>First Quartile (Q1)</strong> — 25th percentile</li><li><strong>Median (Q2)</strong> — 50th percentile</li><li><strong>Third Quartile (Q3)</strong> — 75th percentile</li><li><strong>Maximum</strong> (excluding outliers)</li></ol><p>It also highlights <strong>outliers</strong> in the data — values that are significantly different from the rest.</p><h3>Why Use a Boxplot?</h3><ul><li>Great for <strong>comparing distributions</strong> across categories</li><li>Helps <strong>detect outliers</strong> at a glance</li><li>Shows <strong>spread and symmetry</strong> of the data</li><li>Perfect for <strong>machine learning preprocessing and EDA</strong></li></ul><pre># Boxplot shows median, quartiles, and outliers<br>sns.boxplot(data=titanic, x=&#39;class&#39;, y=&#39;age&#39;, palette=&#39;Set2&#39;)<br><br>plt.title(&quot;Age Distribution by Passenger Class&quot;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*-3t0r8MoIxwMSKY0iHvWcw.png" /></figure><p>3. scatterplot() – Relationship with Grouping :</p><pre># Scatterplot showing survival by age and fare<br>sns.scatterplot(<br>    data=titanic,<br>    x=&#39;age&#39;,<br>    y=&#39;fare&#39;,<br>    hue=&#39;sex&#39;,         # Colors for male/female<br>    style=&#39;class&#39;,     # Different markers for class<br>    size=&#39;survived&#39;,   # Point size by survival<br>    palette=&#39;deep&#39;     # Default rich colors<br>)<br><br>plt.title(&quot;Fare vs Age by Gender, Class, and Survival&quot;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*MaAO9AN-RPzPt5_C6UnuyA.png" /></figure><p>….OOPS!! Looks a bit messy right. Lets to somthing about it.</p><pre># Add transparency to reduce overlap<br>sns.scatterplot(<br>    data=titanic,<br>    x=&#39;age&#39;,<br>    y=&#39;fare&#39;,<br>    hue=&#39;sex&#39;,         # Colors for male/female<br>    style=&#39;class&#39;,     # Different markers for class<br>    size=&#39;survived&#39;,   # Point size by survival<br>    palette=&#39;deep&#39;,    # Default rich colors<br>    alpha=0.6          # Increase transperancy<br>)<br><br>plt.title(&quot;Fare vs Age by Gender, Class, and Survival&quot;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*K7_nbFt01xXYWyvt-IHC_A.png" /></figure><p>Better than before but still this looks quite messy right?</p><p>We can probably do something better with our next type of plot.</p><p>4. relplot() – Multi-plot grid with flexibility :</p><h4>Think of it Like:</h4><ul><li>scatterplot() = one precise photo</li><li>relplot() = a photo collage per category</li></ul><pre># relplot = figure-level scatter/line plot with multi-panel capability<br>sns.relplot(<br>    data=titanic,<br>    x=&#39;age&#39;,<br>    y=&#39;fare&#39;,<br>    hue=&#39;sex&#39;,<br>    col=&#39;class&#39;,           # Creates separate plots (columns) for each class<br>    kind=&#39;scatter&#39;,        # Could also be &#39;line&#39;<br>    palette=&#39;coolwarm&#39;,<br>    height=4<br>)<br><br># &#39;col&#39; uses FacetGrid to split plots<br>plt.suptitle(&quot;Fare vs Age split by Class&quot;, y=1.05)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weCU9dyBdbgnJKyYyc4oew.png" /></figure><p><strong>Special Mention: </strong><strong>sns.catplot() – The Categorical Power Tool</strong></p><p>If you’re working with <strong>categorical data</strong> (like gender, class, embark_town), there’s one function in Seaborn that deserves a <strong>special shoutout</strong>:</p><h4><strong>sns.catplot()</strong></h4><p>But here’s the twist —</p><p><em>It’s </em><strong><em>not</em></strong><em> a type of plot itself.<br> It’s a </em><strong><em>smart wrapper</em></strong><em> that helps you create multiple types of categorical plots like:</em></p><ul><li>barplot</li><li>boxplot</li><li>violinplot</li><li>stripplot</li><li>swarmplot</li><li>pointplot</li></ul><h3>Why use catplot()?</h3><ul><li>You can <strong>easily switch between plot types</strong> using the kind= parameter.</li><li>Add <strong>multiple facets</strong> using col=, row=, or hue=.</li><li>It uses Seaborn’s <strong>figure-level API</strong> — great for multi-plot visualizations.</li></ul><p>This is the syntax for Using catplot():</p><pre>sns.catplot(data=..., x=..., y=..., kind=..., col=..., row=..., hue=...)</pre><p>Example:</p><pre># catplot for boxplots, barplots, stripplots in a flexible layout<br>sns.catplot(<br>    data=titanic,<br>    x=&#39;class&#39;,<br>    y=&#39;age&#39;,<br>    kind=&#39;box&#39;,         # Could also be &#39;violin&#39;, &#39;strip&#39;, etc.<br>    hue=&#39;sex&#39;,<br>    palette=&#39;muted&#39;,<br>    height=4,<br>    aspect=1.2<br>)<br><br>plt.suptitle(&quot;Age Distribution by Class and Gender&quot;, y=1.05)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*QfmEGSU6bIGZ0TL8mBg66g.png" /></figure><p>6. heatmap() – Visualizing Correlation or Matrix Data :</p><p><strong>When to use</strong>: To <strong>understand linear relationships</strong> between features — critical before training models like linear regression.</p><h3>What is a Correlation Matrix?</h3><ul><li>It shows the <strong>relationship between numerical variables</strong>.</li><li>Each value in the matrix is a <strong>correlation coefficient</strong> (between -1 and +1).</li><li><strong>Closer to +1</strong> → Strong positive relationship (both increase together).</li><li><strong>Closer to -1</strong> → Strong negative relationship (one increases, the other decreases).</li><li><strong>Around 0</strong> → Little or no linear relationship.</li></ul><pre># Load Titanic dataset and calculate correlation matrix<br>titanic = sns.load_dataset(&quot;titanic&quot;)<br>corr_matrix = titanic.corr(numeric_only=True)<br><br># Create heatmap with annotations<br>sns.heatmap(<br>    corr_matrix,<br>    annot=True,          # Show values inside boxes<br>    cmap=&#39;coolwarm&#39;,     # Color gradient<br>    linewidths=0.5,      # Grid line thickness<br>    fmt=&quot;.2f&quot;            # Format numbers<br>)<br><br>plt.title(&quot;Correlation Heatmap of Titanic Dataset&quot;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*9_ImR6gjaUvgv6t3AV1Vsg.png" /></figure><p>7. pairplot() – Pairwise Relationships Between Features :</p><pre># Pairplot shows scatter plots and distributions for all numeric feature pairs<br>sns.pairplot(<br>    titanic,<br>    hue=&#39;sex&#39;,         # Grouping by color<br>    vars=[&#39;age&#39;, &#39;fare&#39;, &#39;pclass&#39;],  # Columns to include<br>    palette=&#39;Set1&#39;<br>)<br><br>plt.suptitle(&quot;Pairwise Relationships: Age, Fare, and Class&quot;, y=1.02)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*IoH8TF4Rf-4425IIvjvO4Q.png" /></figure><p>So this would be enough for most of your purpose for now. Still you can learn about other types of interesting plots like voilin plot, joint plot , swarm plot, etc.</p><p>Here we have completed data visualization.</p><h3>Scikit-learn</h3><p>Now let us begin with the most important library for machine learning , scikit-learn.</p><p>If you’re stepping into the world of machine learning, Scikit-Learn is your <strong>best friend</strong>. It’s the <strong>most widely used</strong> and beginner-friendly library that makes the magic of ML approachable. From <strong>data preprocessing</strong> to <strong>model training</strong> and <strong>evaluation</strong>, Scikit-Learn wraps everything you need into a clean and consistent API — making it easier to experiment, learn, and build real-world models. Let’s explore how this powerful library works and walk through your very first ML workflow with it!</p><h3>What Can You Do with It?</h3><ol><li><strong>Load and explore datasets</strong><br> → Built-in datasets like Iris, Wine, Digits for practice</li><li><strong>Preprocess data</strong><br> → Scaling, encoding, imputing missing values</li><li><strong>Train models</strong><br> → Classification, regression, clustering, dimensionality reduction</li><li><strong>Evaluate models</strong><br> → Accuracy, confusion matrix, cross-validation</li><li><strong>Build complete ML pipelines</strong><br> → Automate entire workflows from raw data to prediction</li></ol><h3>Scikit-learn has 4 main parts :</h3><h3>1. Estimator</h3><p>In Scikit-Learn, an <strong>estimator</strong> is <strong>any object that learns from data</strong>. It implements the .fit() method, which allows it to learn parameters from the data.</p><p>Estimator could be:</p><ul><li>A <strong>model</strong> (like logistic regression or decision tree)</li><li>A <strong>preprocessing step</strong> (like standard scaler or PCA)</li></ul><p>Let’s use LogisticRegression to classify data from the Iris dataset.</p><pre># Import necessary modules<br>from sklearn.datasets import load_iris<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br><br># 1. Load dataset<br>iris = load_iris()<br>X = iris.data      # Features (flower measurements)<br>y = iris.target    # Target labels (species)<br><br># 2. Split into training and test sets<br>X_train, X_test, y_train, y_test = train_test_split(<br>    X, y, test_size=0.2, random_state=42)<br><br># 3. Create an estimator (Logistic Regression Model)<br>model = LogisticRegression(max_iter=200)  # Create model object (estimator)<br><br># 4. Fit the model on training data<br>model.fit(X_train, y_train)  # Learns patterns from the data<br><br># 5. Make predictions<br>y_pred = model.predict(X_test)<br><br># 6. Evaluate the model<br>accuracy = accuracy_score(y_test, y_pred)<br>print(&quot;Accuracy:&quot;, accuracy)</pre><ul><li>LogisticRegression() is an <strong>estimator</strong> because it uses .fit() to learn.</li><li>Once trained, you can use .predict() — because it&#39;s also a <strong>predictor</strong>.</li><li>Most estimators also have other helpful methods like .score(), .get_params(), etc.</li></ul><h4>Summary:</h4><blockquote><em>Any object in Scikit-Learn with a </em><em>.fit() method is called an </em><strong><em>estimator</em></strong><em>.<br> If it also has </em><em>.predict(), it becomes a </em><strong><em>predictor</em></strong><em> too.</em></blockquote><h3>2. Transformers</h3><p>A <strong>Transformer</strong> is a special type of <strong>Estimator</strong> that not only learns from data using .fit() but also <strong>transforms</strong> the data using .transform() (or .fit_transform() in one go).</p><pre>from sklearn.preprocessing import StandardScaler<br>import numpy as np<br><br># Sample data<br>X = np.array([[1, 2], [3, 4], [5, 6]])<br><br># Create transformer object<br>scaler = StandardScaler()<br><br># Learn mean and std (fit)<br>scaler.fit(X)<br><br># Transform the data (scale to mean 0 and std 1)<br>X_scaled = scaler.transform(X)<br><br>print(&quot;Original:\n&quot;, X)<br>print(&quot;Scaled:\n&quot;, X_scaled)</pre><blockquote>Every <strong>Transformer</strong> is an <strong>Estimator</strong>, but not every <strong>Estimator</strong> is a <strong>Transformer</strong>.</blockquote><p>Common Transformers in Scikit-Learn :</p><ol><li>StandardScaler : Standardizes features (mean 0, std 1)</li><li>MinMaxScaler : Scales to a given range (e.g., 0–1)</li><li>LabelEncoder : Converts labels into numbers</li><li>OneHotEncoder : Converts categories to binary columns</li><li>PCA : Dimensionality reduction</li></ol><h3>Pro Tip:</h3><p>Most transformers support <strong>.fit_transform()</strong>, which does both .fit() and .transform() in one step:</p><pre>X_scaled = scaler.fit_transform(X)</pre><h3>3. Model Evalation</h3><h3>Why Do We Need Model Evaluation?</h3><p>Training a model is <strong>not enough</strong> — you need to know <strong>how well it’s performing</strong>.</p><blockquote><em>You don’t want a model that “looks good” but makes terrible predictions on new, unseen data.</em></blockquote><p>That’s where <strong>model evaluation</strong> comes in.</p><h3>What Is Model Evaluation?</h3><p>Model evaluation is the process of <strong>quantitatively measuring</strong> how good your model is.</p><p>It helps answer:</p><ul><li>Is the model</li><li>accurate?</li><li>Is it underfitting or overfitting?</li><li>Should I tweak the model or the data?</li></ul><h4>Common Evaluation Metrics by Task</h4><p>For Classification:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*Dthre-XWCpH92DIMGzYKOA.jpeg" /></figure><p>For Regression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*LDgqkUCtmDm7lrsHNjKagA.jpeg" /></figure><h3>Code Example for Classification Evaluation</h3><pre>from sklearn.datasets import load_iris<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score, confusion_matrix, classification_report<br><br># Load data<br>X, y = load_iris(return_X_y=True)<br><br># Split data<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Train model<br>model = LogisticRegression(max_iter=200)<br>model.fit(X_train, y_train)<br><br># Predict<br>y_pred = model.predict(X_test)<br><br># Evaluate<br>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))</pre><h3>4. Automatic Parameter Search</h3><h3>What Is Hyperparameter Tuning?</h3><p>It is the process of:</p><ul><li>Trying multiple combinations of hyperparameters</li><li>Evaluating model performance for each combination</li><li>Selecting the one that performs best</li></ul><p>This is often done using <strong>cross-validation</strong> to ensure that the model generalizes well.</p><h3>Why Do We Need Automatic Parameter Search?</h3><p>Every machine learning model has <strong>hyperparameters</strong> — settings that influence how the model learns.<br> Examples:</p><ul><li>Number of neighbors in KNeighborsClassifier</li><li>Regularization strength in LogisticRegression</li><li>Maximum depth in DecisionTreeClassifier</li></ul><p>Choosing the <strong>right combination</strong> of hyperparameters is critical.<br> Manual tuning is time-consuming and error-prone.</p><p>That’s why we use <strong>automatic hyperparameter search techniques</strong> — to <strong>find the best settings</strong> for our model systematically.</p><h4>Tools for Automatic Hyperparameter Search in Scikit-Learn</h4><h4>1. GridSearchCV</h4><p>Tries <strong>all possible combinations</strong> of provided hyperparameters.</p><pre>from sklearn.model_selection import GridSearchCV<br>from sklearn.svm import SVC<br>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br><br># Load sample data<br>X, y = load_iris(return_X_y=True)<br><br># Split into train and test<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Define model<br>model = SVC()<br><br># Define grid of hyperparameters to search<br>param_grid = {<br>    &#39;C&#39;: [0.1, 1, 10],           # Regularization parameter<br>    &#39;kernel&#39;: [&#39;linear&#39;, &#39;rbf&#39;]  # Type of kernel<br>}<br><br># Create GridSearchCV object<br>grid_search = GridSearchCV(<br>    estimator=model,             # The base model<br>    param_grid=param_grid,       # Grid of hyperparameters<br>    cv=5,                        # 5-fold cross-validation<br>    scoring=&#39;accuracy&#39;           # Metric to optimize<br>)<br><br># Fit grid search to training data<br>grid_search.fit(X_train, y_train)<br><br># Print the best found parameters<br>print(&quot;Best Parameters:&quot;, grid_search.best_params_)<br><br># Print test accuracy using the best estimator<br>print(&quot;Test Accuracy:&quot;, grid_search.best_estimator_.score(X_test, y_test))</pre><h4>2. RandomizedSearchCV</h4><p>Randomly selects combinations and is <strong>faster</strong> when the parameter space is large.</p><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.model_selection import RandomizedSearchCV<br>from scipy.stats import randint<br>from sklearn.datasets import load_iris<br>from sklearn.model_selection import train_test_split<br><br># Load sample data<br>X, y = load_iris(return_X_y=True)<br><br># Split into train and test<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Define model<br>model = RandomForestClassifier()<br><br># Define distribution of hyperparameters to sample from<br>param_dist = {<br>    &#39;n_estimators&#39;: randint(50, 200),   # Number of trees<br>    &#39;max_depth&#39;: [None, 10, 20, 30]     # Maximum depth of tree<br>}<br><br># Create RandomizedSearchCV object<br>random_search = RandomizedSearchCV(<br>    estimator=model,                   # The base model<br>    param_distributions=param_dist,    # Distributions to sample from<br>    n_iter=10,                         # Number of parameter settings to try<br>    cv=5,                              # 5-fold cross-validation<br>    random_state=42,                   # For reproducibility<br>    scoring=&#39;accuracy&#39;                 # Metric to optimize<br>)<br><br># Fit randomized search to training data<br>random_search.fit(X_train, y_train)<br><br># Print the best parameters<br>print(&quot;Best Parameters:&quot;, random_search.best_params_)<br><br># Print test accuracy using the best estimator<br>print(&quot;Test Accuracy:&quot;, random_search.best_estimator_.score(X_test,</pre><p>So these are the main components of scikit-learn that we would regularly use. Now you have official entered into the world of data science and machine learning. Obviously it is very vast and hence no one will be able to teach you everything. Our task is to make you familiar with the fundamentals and provide a clear path to walk on. Now it is your responsiibilty to dive deep into the concepts and learn more stuff on your own. Again congratulations on completing today’s blog and learning something new.</p><h4>conclusion :</h4><p>we explored how to <strong>visualize data using Matplotlib and Seaborn</strong>, and took our first steps into the world of <strong>machine learning with Scikit-learn</strong>. From crafting insightful plots to understanding how models learn, transform, and get evaluated, you now have a solid foundation to build on. This is just the beginning — there’s a vast and exciting world ahead, filled with real-world challenges, smarter models, and deeper insights. Keep experimenting, stay curious, and never stop learning. The path to mastering machine learning starts with understanding the basics — and you’ve already taken that step.</p><h4>Coming Up</h4><p>So we have completed our week 0. We are done with the basics. Now from tomorrow we will be starting week 1, in which we will learn about various supervised learning model!! So stay tuned and keep learning!!</p><h3>Today’s task:</h3><h4>Student Performance Dashboard</h4><ul><li><strong>Dataset</strong>: <a href="https://www.kaggle.com/datasets/spscientist/students-performance-in-exams">Student Performance Dataset</a></li><li><strong>Goal</strong>: Analyze how gender, test preparation, and parental education affect scores.</li><li><strong>Visuals</strong>:</li><li>Histograms, KDEs for score distribution</li><li>Boxplots and barplots by gender and education level</li><li>Heatmap of score correlations</li></ul><h3>Previous &amp; Next</h3><ul><li>Previous : <a href="https://medium.com/@adeshanurag50/openlearn-cohort-1-0-w0-d2-data-analysis-refresher-numpy-pandas-eda-490f47fa3b74">Data Analysis Refresher</a></li><li>Next : Coming Soon (Linear Regression)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3ccf534bbe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get intuition of Neural Networks]]></title>
            <link>https://medium.com/@thackershubham374/get-intuition-of-neural-networks-b9511ba1e9b6?source=rss-e20e6a066cb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9511ba1e9b6</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[ThakkarrShubham]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 18:12:06 GMT</pubDate>
            <atom:updated>2024-12-28T18:12:06.689Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone!!</p><p>Do you want to rediscover Neural Networks yourself? You will be amazed by knowing how simple the process of discovering such a complex looking thing is. And We will be doing this intuitively without getting much into maths.</p><p>So Apple has finally launched a calculator on their iPad. And it has a very amazing feature. You can write an expression with apple pencil and the calculator would evaluate it for you.</p><p>As we can see, for evaluating the expression, the calculator has to recognize the numbers and symbols. Think that you are a software engineer at Apple. Tim uncle has given you the task of developing a program that would recognize the numbers written with apple pencil.</p><p>How will we proceed?</p><p>For now let us consider only one-digit numbers. We will try to make a program that would recognize handwritten numbers from 0 to 9.</p><p>User has written the number with an apple pencil. Now the places where apple pencil touched will have pixels with different color than the background. Now let us divide the space around the number into a grid of size 28*28. This is to make the calculations required practically possible(You will understand this as you read further). And we will turn the image black and white. Now we will decrease the resolution of the image. We would consider each grid box as a pixel. And the greyscale value of each pixel will be decided by the percentage of the grid box filled. So after doing this, the image of our number would look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*riZh9o90cpjSkYgHmzcOyg.jpeg" /></figure><p>Now what information do we have? We know the greyscale value of each pixel. Now we need to create a program that would take the greyscale value of each pixel and return us the number written. So we have a total of 784 input values and 10 options for output.</p><p>I know that few types of combinations of input values would correspond to an output value. We need something before the output layer that can contain the information about the combinations which would be connected to the output layer. And based on the values stored in the last layer, the output layer will show us which number was written.</p><p>And this layer contains something we will call neurons. It basically takes any value between 0 to 1 based on the inputs it got from the previous layer. This will help us pass information regarding different patterns to the output layer.</p><p>And the number of neurons in the layer will be decided by hit and trial or using some trivial methods. And to recognize more complex patterns we can add more layers as per requirements.</p><p>Each neuron in a layer is connected with every neuron in the layers before and after it with the help of an imaginary string. And we can think of the strength of the string which will decide the extent of effect of a neuron on the neuron in the next layer connected with this string. We will use the word ‘weight’ for this strength. In this way a neural network with a random configuration is made. And we would also set sensitivity to the neuron by adding something called bias, which is just a number to make sure that a neuron will light up only if the strength of the signal it got is above a certain threshold.</p><p>Now we will adjust the weights and biases so that it can predict the handwritten number. But even for something as basic as recognizing a handwritten digit, the number of weights and biases becomes insanely large. And it is practically impossible to adjust these manually.</p><p>We will try to reduce our problem to an optimization problem. We will try to find the optimum solutions using thousands of labelled images of handwritten numbers. We will define a cost function, which is a function of all the weights and biases. We will take the desired value for each neuron in the output layer. That would be one for the number corresponding to the image and zero for others. Then we will look at the output given by our network. We will take the difference in the values of neurons required and what we got, Square these differences to get rid of the negative values, and add these squares of difference. This will be the value for the cost function for a given example.</p><p>We will try to minimize the average of the cost function for each training example. We can do it using a derivative test to find a minima, but using it for such a complex function with these many parameters is not practically possible. So we will use Gradient descent method. So the gradient vector is a vector that shows the direction in which the value of a function increases at the highest rate. So in the direction opposite of it that is negative of the gradient vector, the value of function decreases at the highest rate. So we will change the weights and biases in the direction opposite to gradient and the change will be proportional to the magnitude of the gradient vector to prevent overfitting. This can be thought of as moving in the direction towards the valley. We will do this until a local minima is found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSbdezImZbxd0Cj8IHLLrw.jpeg" /></figure><p>This will be done by an algorithm known as back-propagation. We will start from the output layer. We will see how much change is needed in the output layer. We cannot do changes directly in the output layer. It would be dependent on weights and the values of the neurons of the previous layer. We will change the bias and weights according to gradient descent. We cannot directly change the values of neurons as they are dependent on the previous layer. So we will continue this process till we reach the first layer of neurons and finally we will make changes in connections between input layer and first layer of neurons. This can be thought of as the neurons in a layer are telling the neurons, weights and biases in the previous layer that “ I want you to change in this way.”. Every neuron, weight and bias in the previous layer will listen to every neuron in the layer next to it. Find the average of all suggestions and tell the previous layer how it wants to get changed. And the previous layer will also do the same thing until it reach the layer which can directly be changed that is the first layer of weights and biases</p><p>In this way we will find a local minima for recognizing handwritten numbers.</p><p>We can summarize all the steps as follows:</p><p>-&gt; Processing the image of the number and making the data of the image manageable.</p><p>-&gt; Making a neural network with a random configuration with the greyscale value of each of 784 pixels as input. And the output layer having 10 numbers from 0 to 9 as options for output.</p><p>-&gt; Now we will calculate the cost function for each training example and find the average for cost functions.</p><p>-&gt; Now we will use Gradient descent for reducing the value of the cost function. We will perform this using back-propagation.</p><p>-&gt; we will repeat these steps until we reach a local minima.</p><p>For more curious readers, who want to dive deeper into the topic including mathematics, I would recommend you this playlist by 3Blue1Brown. You can also find a link to code in the description of the video. You can try your own hand on it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi&amp;image=https%3A%2F%2Fi9.ytimg.com%2Fs_p%2FPLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi%2Flandscape_mqdefault.jpg%3Fsqp%3DCJzdzMoGir7X7AMICNGyiNsFEAE%3D%26rs%3DAOn4CLAjEIHUnFuuz4cU_21wOJD1sGt5Kw%26v%3D1533155665%26days_since_epoch%3D20452&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c232508017ec179f5da7cb09be88fef9/href">https://medium.com/media/c232508017ec179f5da7cb09be88fef9/href</a></iframe><p>Hope you enjoyed it. See you next time!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9511ba1e9b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>