<?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 Nandhini Muthusamy on Medium]]></title>
        <description><![CDATA[Stories by Nandhini Muthusamy on Medium]]></description>
        <link>https://medium.com/@nandhinimuthusamy1899?source=rss-a6d14c9838ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LqePWjUla85QoBcBkBLJIw.jpeg</url>
            <title>Stories by Nandhini Muthusamy on Medium</title>
            <link>https://medium.com/@nandhinimuthusamy1899?source=rss-a6d14c9838ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:02:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nandhinimuthusamy1899/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[Demystifying Descriptive Analysis: A Beginner’s Guide to Statistics [Part 1]]]></title>
            <link>https://medium.com/@nandhinimuthusamy1899/demystifying-descriptive-analysis-a-beginners-guide-to-statistics-part-1-74a5e23431b0?source=rss-a6d14c9838ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/74a5e23431b0</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[descriptive-statistics]]></category>
            <dc:creator><![CDATA[Nandhini Muthusamy]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 19:22:48 GMT</pubDate>
            <atom:updated>2024-02-05T19:35:32.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BE5oCirMBq_9TA8d" /><figcaption>Photo by <a href="https://unsplash.com/@m_____me?utm_source=medium&amp;utm_medium=referral">m.</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>Table of Contents:</strong></blockquote><ol><li><a href="#3d5e">Introduction</a></li><li><a href="#b654">Why Statistics</a>?</li><li><a href="#5526">Types of Statistics</a></li><li><a href="#0d14">Measures of Central Tendency</a></li><li><a href="#f99b">Measures of Dispersion</a></li><li><a href="#d78f">Percentiles and Quartiles</a></li><li><a href="#8a51">Z-Score</a></li></ol><blockquote><strong>Introduction:</strong></blockquote><p>Welcome to the world of statistics, a powerful tool that enables us to make sense of the vast sea of information surrounding us. At its core, statistics is the science of collecting, analyzing, interpreting, presenting, and organizing data. But then, why do we even need statistics? Why do we need to understand what is underneath the data? Let’s understand.</p><blockquote><strong>Why Statistics?</strong></blockquote><p>Statistics is the art of uncovering the hidden stories and patterns within the overwhelming noise of data. It is like a compass that guides us through the intricate terrain of data, revealing patterns and illuminating the hidden paths of information. It helps us to make better decisions.</p><p>In the real world, statistics find application in diverse areas. Whether it’s predicting stock market trends, understanding consumer behavior, improving medical treatments, or optimizing industrial processes, statistics play a pivotal role. Governments use it to formulate policies, businesses leverage it for market research, and scientists rely on it to draw meaningful conclusions from experiments.</p><blockquote><strong>Types of Statistics:</strong></blockquote><p>There are two main branches of statistics: descriptive and inferential. Descriptive statistics, the focus of our exploration, involve methods for summarizing and organizing data. It provides a snapshot of the main features of a dataset, offering a foundation for further analysis. On the other hand, inferential statistics draw conclusions about a population based on a sample of data, extending the insights gained from the observed sample to the larger group.</p><p>Now let’s dive into the fascinating world of descriptive analysis! Imagine you’ve collected a bunch of data—numbers, figures, or any sort of information. Now, descriptive analysis is like the superhero that swoops in to help you make sense of it all. It is a statistical technique used to summarize and describe the main features of a dataset. It involves organizing and summarizing data in a meaningful way, often through measures of central tendency, variability, and distribution.</p><p>Key aspects under descriptive analysis include:</p><blockquote><strong>Measures of Central Tendency</strong></blockquote><p>Central tendency is a statistical measure to find the middle or average value in a set of data. There are three main measures of central tendency:</p><p><strong>1. Mean</strong></p><p>The mean provides a single value that summarizes the central location of the data. It can be used with both discrete and continuous data but is often used with continuous data. It is calculated by adding up all the values in a dataset and then dividing by the number of values. The three most common types of means are the arithmetic mean, the geometric mean, and the harmonic mean.</p><p><strong>Types of Mean:</strong></p><p><strong>a. Arithmetic Mean:</strong></p><p>The Arithmetic Mean, often simply referred to as the “mean,” is the most common measure of central tendency. It represents the average of a set of values and is calculated by adding up all the values in a dataset and then dividing by the total number of values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*CzYIjXFOyVdy8TllPIJ16w.png" /><figcaption>Arithmetic mean formula</figcaption></figure><p><strong>Example: </strong>In a student dataset, Arithmetic Mean scores are frequently used to represent the average performance of students in exams.</p><pre>import numpy as np<br><br># Exam scores of students<br>exam_scores = [85, 90, 92, 88, 78, 95, 89]<br><br># Calculate arithmetic mean<br>arithmetic_mean_scores = np.mean(exam_scores)<br><br>print(&quot;Arithmetic Mean Exam Score:&quot;, arithmetic_mean_scores)</pre><pre>Arithmetic Mean Exam Score: 88.14285714285714</pre><p><strong>b. Geometric Mean:</strong></p><p>Geometric mean is commonly used in finance for calculating average rates of return, growth rates, or compound annual growth rates. It is calculated by taking the nth root of the product of all values in a dataset, where n is the number of values. Suppose an investment grows by 5% in the first year, 10% in the second year, and -3% in the third year. The geometric mean can be used to calculate the average growth rate over the three years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*oj-jJFL5hlXzrsktgoKJ-w.png" /><figcaption>Geometric mean formula</figcaption></figure><p><strong>Example: </strong>Suppose you have the following dataset of growth rates for an investment over three years: [0.05, 0.10, -0.03]. In this case, to understand the average growth rate over three years, Geometric Mean can be really helpful.</p><pre>import numpy as np<br><br># Annual returns on an investment<br>returns = [0.05, 0.10, -0.03]<br><br># Calculate geometric mean<br>geometric_mean_returns = np.prod(1 + np.array(returns))**(1/len(returns)) - 1<br><br>print(&quot;Geometric Mean Investment Returns:&quot;, geometric_mean_returns)</pre><pre>Geometric Mean Investment Returns: 0.038606986064198656</pre><p><strong>c. Harmonic Mean:</strong></p><p>Harmonic Mean is suitable for situations involving rates or ratios. It is calculated by taking the reciprocal of the arithmetic mean of the reciprocals of the values in a dataset. For example, if a car travels 60 km/h for the first half of the journey and 40 km/h for the second half, the harmonic mean can be used to find the average speed over the entire journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*bpf5HJAzV90SQURIeQW0fQ.png" /><figcaption>Harmonic mean formula</figcaption></figure><p><strong>Example: </strong>Suppose you have the following dataset of speeds in km/h for a journey: [60, 40, 20]. Now, to find the average speed over the entire journey, Harmonic Mean can be used.</p><pre>from scipy.stats import hmean<br><br># Speeds of different legs of a journey (in km/h)<br>speeds = [60, 40, 20]<br><br># Calculate harmonic mean to find average speed<br>harmonic_mean_speed = hmean(speeds)<br><br>print(&quot;Harmonic Mean Average Speed:&quot;, harmonic_mean_speed)</pre><pre>Harmonic Mean Average Speed: 32.72727272727273</pre><p><strong>2. Median</strong></p><p>The Median represents the middle value of a dataset when it is sorted in ascending or descending order. It is useful in various applications, particularly when dealing with datasets that may contain outliers or skewed distributions.</p><p>For example, if we have a total of an odd number of observations, then Median = middle_value of the list of observations. On the other hand, if we have a total of even numbers of observations, then Median = (middle_value_1 + middle_value_2) / 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*GiltbjtGC5ORGK-3Oy4ztQ.png" /><figcaption>Median formula</figcaption></figure><p><strong>Example:</strong></p><pre>import numpy as np<br><br># Example dataset: Ages of individuals in a group<br>ages = [25, 30, 22, 35, 28, 31, 29, 27, 32, 26]<br><br># Calculate the median age using numpy<br>median_age = np.median(ages)<br><br># Print the result<br>print(&quot;Ages of individuals:&quot;, ages)<br>print(&quot;Median Age:&quot;, median_age)</pre><pre>Ages of individuals: [25, 30, 22, 35, 28, 31, 29, 27, 32, 26]<br>Median Age: 28.5</pre><p><strong>3. Mode</strong></p><p>Mode represents the most frequently occurring value in a dataset. In business and marketing, Mode can be used to identify the most popular products, services, or features. This information is valuable for making decisions related to inventory management, product development, and marketing strategies.</p><p>However, there might be some corner cases, like datasets with:</p><ol><li><strong>No Mode</strong>: If all values occur at the same frequency.</li><li><strong>Unimodal</strong>: If there is a single mode (one value that appears most frequently).</li><li><strong>Bimodal</strong>: If there are two modes (two values that appear most frequently).</li><li><strong>Multimodal</strong>: If there are more than two Mode.</li></ol><pre>from collections import Counter<br><br>study_hours = [2, 4, 3, 6, 4, 8, 6, 2, 4, 6, 3, 5, 6, 2, 4, 8, 6, 3, 5]<br><br># Using Counter to count occurrences of each study hour value<br>study_hours_counts = Counter(study_hours)<br><br># Finding the study hour value with the maximum count (mode)<br>most_common_study_hours = max(study_hours_counts, key=study_hours_counts.get)<br><br>print(&quot;Most Common Study Hours:&quot;, most_common_study_hours)</pre><pre>Most Common Study Hours: 6</pre><p>In this example, Mode is used to identify a student&#39;s most common amount of study time for an exam.</p><blockquote><strong>Measures of Dispersion</strong></blockquote><p>Measures of dispersion help to describe the variability in the data. Dispersion is a statistical term that can be used to describe the extent to which data is scattered. Thus, measures of dispersion are certain types of measures that are used to quantify the dispersion of data. There are three main measures of dispersion:</p><h4>1. Range</h4><p>The range is the difference between the maximum and minimum values in<br>the dataset. It is a simple measure of dispersion that is easy to calculate but can be affected by outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*edQq1IJJUgXPhLAdCj0aWQ.png" /><figcaption>Range Formula</figcaption></figure><p>Here, Max represents the maximum value in the dataset and Min represents the minimum value in the dataset. The range is useful for a quick, initial exploration of data to get a sense of how spread out the values are.</p><pre># Example: Finding the range of a dataset<br>data = [14, 7, 10, 23, 18, 5, 13, 25, 9, 16]<br><br># Calculate the range<br>data_range = max(data) - min(data)<br><br>print(&quot;Dataset:&quot;, data)<br>print(&quot;Range:&quot;, data_range)</pre><pre>Dataset: [14, 7, 10, 23, 18, 5, 13, 25, 9, 16]<br>Range: 20</pre><p>When Not to Use Range,</p><ol><li><em>Outlier Presence</em>: In statistics, an <strong>outlier</strong> is a data point that differs significantly from other observations. An outlier may be due to variability in the measurement, an indication of novel data, or maybe the result of experimental error; usually, they are excluded from the data set. If there are outliers in the dataset, the range may not accurately represent the typical variability of the majority of the data.</li><li><em>Skewed Distributions</em>: In datasets with skewed distributions, where most of the values cluster around a certain range but a few are much higher or lower, the range may not be a representative measure of spread.</li></ol><h4>2. Variance</h4><p>The term variance refers to a statistical measurement of the spread between numbers in a data set. More specifically, variance measures how far each number in the set is from the mean (average) and thus from every other number in the set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/0*hFApzHj2-Go85Bn8" /><figcaption>Variance formula</figcaption></figure><p>Variance is calculated by using the following formula. Where,</p><p>Xi = each individual data point</p><p>μ = mean of the data points</p><p>n = total number of data points</p><pre>import numpy as np<br><br># Monthly sales data<br>sales = np.array([4000, 4200, 3800, 4100, 3900, 4050])<br><br># Calculate variance<br>variance_sales = np.var(sales)<br><br># Print result<br>print(f&quot;Monthly Sales Data: {sales}&quot;)<br>print(f&quot;Variance: {variance_sales}&quot;)</pre><pre>Monthly Sales Data: [4000 4200 3800 4100 3900 4050]<br>Variance: 17013.888888888887</pre><h4>3. Standard Deviation</h4><p>Standard deviation is a measure that helps us understand how spread out or dispersed the values in a set of data, from the average (mean). It gives us an idea of how much individual data points deviate or vary from the overall average. A higher standard deviation indicates greater variability, signifying that data points are more spread out from the mean. A lower standard deviation implies less variability and a more clustered dataset. It helps to identify outliers and anomalies that might affect the interpretation of results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*YAGz0tVxxnu9zMgO2gF6AA.png" /><figcaption>Standard Deviation formula</figcaption></figure><p>The standard deviation (<em>σ</em>) is often preferred over the variance, It provides a more comprehensive understanding of the distribution of data than just looking at the mean. It helps researchers and analysts discern the distribution characteristics, identify patterns, and assess the reliability of the dataset.</p><pre>import numpy as np<br><br># Monthly sales data<br>sales = np.array([4000, 4200, 3800, 4100, 3900, 4050])<br><br># Calculate standard deviation<br>std_dev_sales = np.std(sales)<br><br># Print result<br>print(f&quot;Monthly Sales Data: {sales}&quot;)<br>print(f&quot;Standard Deviation: {std_dev_sales}&quot;)</pre><pre>Monthly Sales Data: [4000 4200 3800 4100 3900 4050]<br>Standard Deviation: 130.43729868748773</pre><blockquote><strong>Percentiles and Quartiles</strong></blockquote><p>Percentiles and quartiles are statistical measures that help analyze the distribution of a dataset by dividing it into parts based on the relative position of individual data points.</p><h4>1. Percentile</h4><p>Percentile is a measure that indicates the relative standing of a particular value within a dataset. Percentiles are expressed as a percentage and range from 0 to 100. Percentiles are different from percentages. Percentiles describe the position of a particular value within a dataset, while percentages refer to a proportion of the whole. Percentiles are particularly useful for understanding the distribution of data and identifying the relative position of a specific value.</p><p>Let’s calculate the percentile for a dataset: [40, 15, 10, 55, 20, 35, 50, 45, 30, 25]. And we want to find the 75th percentile in the dataset.</p><ol><li><em>Sort the Data</em>: Arrange the dataset in ascending order, from the smallest to the largest value. The sorted dataset is: [10, 15, 20, 25, 30, 35, 40, 45, 50, and 55].</li><li>I<em>dentify the Position</em>: Determine the position of the target value within the ordered dataset.</li></ol><p>3. <em>Calculate the Percentile</em>: Use the following formula to calculate the percentile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*wzmwUQIz3a8j4FtbMe33ng.png" /><figcaption>Percentile formula</figcaption></figure><p>Alternatively, you can use the nearest-rank method, where you find the position using the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*98fpivIJgfX2wtyz7HLCzg.png" /></figure><p>If the position is an integer, you take the value at that position. If it’s a decimal, you interpolate between the values at the two closest integer positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*IXBLZIJKoeIH0YqBr-f_8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*3BHrjZn3uKTM3xaIqB_lWw.png" /></figure><p>So, the 75th percentile in this dataset is 43.75. This means that 75% of the values in the dataset are below 43.75.</p><pre>import numpy as np<br><br># Exam scores dataset<br>exam_scores = np.array([78, 85, 92, 60, 72, 89, 95, 88, 68, 75, 80, 93, 67, 84, 90])<br><br># Calculate the 80th percentile<br>percentile_80 = np.percentile(exam_scores, 80)<br><br>print(f&quot;The 80th percentile score is: {percentile_80}&quot;)</pre><pre>The 80th percentile score is: 90.4</pre><h4>2. Quartiles</h4><p>Quartiles are useful in analyzing the spread and distribution of a dataset. Quartiles are values that divide a data set into four equal parts. The three quartiles are commonly denoted as Q1, Q2, and Q3. The second quartile (Q2) is also known as the median.<br>Here’s a brief explanation of each quartile:</p><p>a. <em>First Quartile (Q1)</em>: This is the value below which 25% of the data falls. It is the median of the lower half of the dataset.</p><p>→ <em>First Quartile (Q1) = ((n + 1)/4)th Term</em></p><p>b. <em>Second Quartile (Q2)</em>: This is the median of the dataset. It represents the middle point of the data, separating it into two halves. Fifty percent of the data falls below this value and 50% above it.</p><p>→ <em>Second Quartile (Q2) = ((n + 1)/2)th Term</em></p><p>c. <em>Third Quartile (Q3)</em>: This is the value below which 75% of the data falls. It is the median of the upper half of the dataset.</p><p>→ <em>Third Quartile (Q3) = (3(n + 1)/4)th Term</em></p><p><strong>Interquartile range (IQR)</strong></p><p>The interquartile range (IQR) is a measure of statistical dispersion that provides information about the spread of a dataset. It is particularly useful in describing the middle 50% of the data, thereby offering a more robust measure of variability than the range.</p><p>The interquartile range is calculated as the difference between the third quartile (Q3) and the first quartile (Q1) in a dataset. the formula for calculating the interquartile range (IQR) is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*Zt4hgft7FCqDI6Wl_0tclw.png" /><figcaption>IQR formula</figcaption></figure><p>Here, Q1 is the first quartile, representing the value below which 25% of the data falls. Q3 is the third quartile, representing the value below which 75% of the data falls.</p><pre>import numpy as np<br><br># sample dataset<br>data = np.array([12, 18, 11, 15, 20, 22, 16, 14, 13, 19, 21])<br><br># Calculate quartiles using numpy<br>q1 = np.percentile(data, 25)<br>q2 = np.percentile(data, 50)  # Median<br>q3 = np.percentile(data, 75)<br><br># Calculate Interquartile Range (IQR)<br>iqr = q3 - q1<br><br>print(&quot;First Quartile (Q1):&quot;, q1)<br>print(&quot;Second Quartile (Q2 or Median):&quot;, q2)<br>print(&quot;Third Quartile (Q3):&quot;, q3)<br>print(&quot;Interquartile Range (IQR):&quot;, iqr)</pre><pre>First Quartile (Q1): 13.5<br>Second Quartile (Q2 or Median): 16.0<br>Third Quartile (Q3): 19.5<br>Interquartile Range (IQR): 6.0</pre><p>The interquartile range (IQR) is preferred over the range because it is less sensitive to outliers, provides a robust measure of spread, and focuses on the central 50% of the data.</p><blockquote><strong>Z-Score</strong></blockquote><p>In simple words,<strong> </strong>a z-score (also called a <em>standard score</em>) gives you an idea of how far from the mean a data point is<strong>.</strong> But more technically, it’s a measure of how many standard deviations below or above the population mean a raw score is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*4XyOaLKxYR6IxTHp" /><figcaption>Z-Score formula</figcaption></figure><p>For example, let’s say you have a test score of 190. The test has a mean (μ) of 150 and a standard deviation (σ) of 25. Assuming a normal distribution, your z score would be:</p><p>z = (x — μ) / σ</p><p>→ z = (190–150) / 25 = 1.6</p><p>The z-score tells you how many standard deviations from the mean your score is. In this example, your score is 1.6 standard deviations <em>above</em> the mean.</p><pre>import numpy as np<br>from scipy.stats import zscore<br><br># Sample dataset<br>data = np.array([10, 12, 8, 15, 7, 11, 9, 13, 14])<br><br># Calculate Z-scores<br>z_scores = zscore(data)<br><br># Print Z-scores<br>print(f&quot;Z-Scores: {z_scores}&quot;)</pre><pre>Z-Scores: [-0.38729833  0.38729833 -1.161895    1.54919334 -1.54919334  0.<br> -0.77459667  0.77459667  1.161895  ]</pre><p>In conclusion, the journey through descriptive statistics has unveiled the art of transforming raw data into meaningful insights, allowing us to unravel the intricate stories hidden within numbers. By mastering the tools of central tendency, variability, and distribution, we empower ourselves to navigate the vast landscape of data with precision and clarity.</p><p>In the second part of it, we will dive deep into some other important aspects of descriptive statistics. The link to that blog is here.</p><p>Hope this helps. I’m going to share more of my journey, which will be totally beginner-friendly. Check out my other blogs on <a href="https://medium.com/@nandhinimuthusamy1899">Medium</a>, or we can connect on <a href="https://www.linkedin.com/in/nandhini-muthusamy-63709a183/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74a5e23431b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Linear Regression: A Beginner’s Intuitive Guide to the Basics]]></title>
            <link>https://medium.com/@nandhinimuthusamy1899/understanding-linear-regression-a-beginners-intuitive-guide-to-the-basics-c2d858d934ee?source=rss-a6d14c9838ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2d858d934ee</guid>
            <category><![CDATA[linear-regression-math]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[linear-regression-python]]></category>
            <dc:creator><![CDATA[Nandhini Muthusamy]]></dc:creator>
            <pubDate>Mon, 25 Dec 2023 18:04:55 GMT</pubDate>
            <atom:updated>2023-12-25T18:04:55.968Z</atom:updated>
            <content:encoded><![CDATA[<p>Linear regression is a supervised learning algorithm used for predicting a continuous outcome variable (dependent variable) based on one or more predictor variables (independent variables). This assumes a linear relationship between the input features and the target variable. Let’s consider we have a simple scenario where we want to predict a student’s exam score based on the number of hours they studied. In this context, the exam score represents the dependent variable, the metric we aim to predict, while the number of hours dedicated to studying acts as the input feature or independent variable.</p><p>Linear regression with one variable is called single or univariate linear regression. When a linear regression model involves multiple independent variables, it is referred to as multivariate linear regression.</p><p>The linear regression equation,</p><h4>y = mx + c</h4><p>encapsulates the concept of a straight-line relationship between two variables.</p><p>where y is the dependent variable, the output we are trying to predict, x is the independent variable, used to make predictions about the dependent variable (y). Changes in (x) are assumed to cause changes in (y), m is the slope of the line indicating the rate at which the dependent variable (y) changes concerning a change in the independent variable (x). It represents the steepness or incline of the line, and c is the y-intercept, representing the value of (y) In other words, it’s the point where the line intersects the y-axis.</p><h4>Hypothesis Function</h4><p>The linear regression hypothesis function is the mathematical representation of the relationship between the independent variable(s) and the dependent variable in a linear regression model. The hypothesis function is expressed as,</p><h4><strong><em>hθ</em>​(<em>x</em>)=<em>θ</em>0​+<em>θ</em>1​⋅<em>x</em></strong></h4><p>The goal of linear regression is to find the values of <em>θ</em>0​ and <em>θ</em>1​ that minimize the difference between the predicted values (<em>hθ</em>​(<em>x</em>)) and the actual values (<em>y</em>) in the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBAppU6IA2vd1r7rqtX11A.png" /></figure><p><strong>Weights </strong>(w or θ1) denote, how much the feature matters in the model. higher weight of a particular feature means that is more important in deciding the outcome of the model. Generally, weights are initialized randomly. we should try to bring them to optimal values, so they are able to fit the model well and can help in prediction of unseen values.</p><p><strong>Bias</strong> (b or θ0) allows to move the line down or up fitting the prediction with the data better</p><h4>Cost Function</h4><p>It measures the difference between the predicted values and the actual values in the training data. The goal of linear regression is to find the parameters (weights &amp; bias) of the linear model that minimizes the cost function. The most commonly used cost function for linear regression is the Mean Squared Error (MSE).</p><p>The Mean Squared Error (MSE) is calculated as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*nBwBbsTwGDRAkCILGGSb8w.png" /><figcaption>Mean Squared Error</figcaption></figure><p>Where J(<em>θ)</em> is the cost function, m is the number of training examples,<em> </em>hθ​(x(i)) is the predicted value for the <em>i</em>th example, <em>y</em>(<em>i</em>) is the actual value for the <em>i</em>th example. The 1/2​ term is included to simplify the derivative of the cost function during the optimization process. The goal is to minimize the cost function <em>J</em>(<em>θ</em>) by adjusting the parameters <em>θ</em>0​, <em>θ</em>1​, …,<em>θn</em>​.</p><h4>Gradient Descent</h4><p>Gradient descent is an optimization algorithm used to minimize the cost function in various machine learning models, including linear regression. The basic idea behind gradient descent is to iteratively adjust the model parameters (weights &amp; bias) in the direction that reduces the cost function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*UfL08fYv5UV8apg-g1itaw.png" /></figure><h4>Update rule for weights</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*ro_ZTsNEHTZ53L_sAckIvQ.png" /></figure><p><em>α</em> is the learning rate, <em>m</em> is the number of training examples, <em>hθ</em>​(<em>x</em>(<em>i</em>)) is the predicted value for the <em>i</em>th example, <em>y</em>(<em>i</em>) is the actual value for the <em>i</em>th example, <em>xj</em>(<em>i</em>)​​ is the <em>j</em>th feature value for the <em>i</em>th example.</p><h4>Update rule for bias</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*-iJt5r54HWm_XHuZdoPqJQ.png" /></figure><h3><strong>Learning Rate</strong></h3><p>The learning rate is a hyperparameter in the gradient descent algorithm that controls the size of the steps taken during the optimization process. Choosing an appropriate learning rate is crucial. If the learning rate is too small, the algorithm may take a long time to converge or get stuck in a local minimum. On the other hand, if the learning rate is too large, the algorithm may overshoot never reach the minimum, or fail to converge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*5E3dVsvaKyBD6kXK7-N1OA.png" /><figcaption><em>Fig. 4. Importance of Learning Rate — (Image source: </em><a href="https://blog.goodaudience.com/gradient-descent-for-linear-regression-explained-7c60bc414bdd"><em>here</em></a><em>)</em></figcaption></figure><p>A positive slope indicates that the algorithm is increasing the values of the parameters during each iteration of the optimization process and Negative slope is decreasing the values of the parameters during each iteration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*gMVGfdbvFyYk9yOHWMRgRw.png" /><figcaption><em>Fig. 3. Gradient Descent — (Image source: </em><a href="https://blog.goodaudience.com/gradient-descent-for-linear-regression-explained-7c60bc414bdd"><em>here</em></a><em>)</em></figcaption></figure><h3>Implementation</h3><p>Download the <a href="https://github.com/Nandhini-Muthusamy/datasets-linear-regression"><strong>Sales dataset</strong></a> from my repository, As we will be using it for implementing linear regression. I used Google Colab, and the majority of the code will remain the same if transferred to a Jupyter Notebook.</p><h4><strong>Import Necessary Libraries</strong></h4><pre>from google.colab import files<br>import io<br><br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)<br><br># Import the numpy and pandas package<br>import numpy as np<br>import pandas as pd<br><br># Data Visualisation<br>import matplotlib.pyplot as plt <br>import seaborn as sns<br><br># Performing Simple Linear Regression<br>from sklearn.model_selection import train_test_split <br>from sklearn.linear_model import LinearRegression <br>from sklearn import metrics </pre><h4><strong>Read CSV into DataFrame</strong></h4><p>This line prompts the user to upload a file. After running this line, you’ll see a button allowing you to select and upload a file from your local drive. Then we read the uploaded CSV file (assuming it’s named ‘advertising.csv’) from the content uploaded and create a Pandas DataFrame named advertisement_data with the data from the CSV.</p><pre># To upload from your local drive<br>uploaded = files.upload()<br><br>advertisement_data = pd.read_csv(io.BytesIO(uploaded[&#39;advertising.csv&#39;]))<br># Dataset is now stored in a Pandas Dataframe<br><br>advertisement_data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*b51RzmV8YStq9KWnebzAZg.png" /></figure><h4><strong>Understanding Data</strong></h4><p>used to gain insights into the structure and characteristics of the advertisement_data DataFrame, including its shape, descriptive statistics, and general information about the data types and non-null values.</p><pre>advertisement_data.shape<br># (200, 4)<br><br>advertisement_data.describe()<br><br>advertisement_data.info()<br><br># &lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br># RangeIndex: 200 entries, 0 to 199<br># Data columns (total 4 columns):<br>#  #   Column     Non-Null Count  Dtype  <br># ---  ------     --------------  -----  <br>#  0   TV         200 non-null    float64<br>#  1   Radio      200 non-null    float64<br>#  2   Newspaper  200 non-null    float64<br>#  3   Sales      200 non-null    float64<br># dtypes: float64(4)<br># memory usage: 6.4 KB</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*GNmiKS8Q-VNrUfZ1w7_5Ww.png" /><figcaption>advertisement_data.describe()</figcaption></figure><h4>Data cleaning</h4><p>count of missing values in each column</p><pre>advertisement_data.isnull().sum()<br><br># TV           0<br># Radio        0<br># Newspaper    0<br># Sales        0<br># dtype: int64</pre><h4>Visualization</h4><p>scatter plots for the specified columns in the advertisement_data DataFrame, with &#39;Sales&#39; on the y-axis, displays each plot individually. This can help visualize the relationship between different advertising channels (&#39;TV&#39;, &#39;Radio&#39;, &#39;Newspaper&#39;) and sales</p><pre>import matplotlib.pyplot as plt<br><br>def generate_scatter_plot(x_data, y_data, x_label):<br>    # Scatter plot with x_data against y_data<br>    plt.scatter(x_data, y_data)<br>    <br>    # Adding Title to the Plot<br>    plt.title(&quot;Scatter Plot&quot;)<br>    <br>    # Setting the X and Y labels<br>    plt.xlabel(x_label)<br>    plt.ylabel(&#39;Sales&#39;)<br>    <br>    plt.show()<br><br># Assuming advertisement_data is a DataFrame with columns &#39;TV&#39;, &#39;Radio&#39;, &#39;Newspaper&#39;, and &#39;Sales&#39;<br>columns_to_plot = [&#39;TV&#39;, &#39;Radio&#39;, &#39;Newspaper&#39;]<br><br>for column in columns_to_plot:<br>    generate_scatter_plot(advertisement_data[column], advertisement_data[&#39;Sales&#39;], column)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYBXcBerqfPQ9T5CcaLBZg.png" /></figure><h4>Model Building</h4><p>We split the dataset into training and testing sets, which is a common practice in machine learning to evaluate model performance on unseen data.</p><pre>Y = advertisement_data[&#39;Sales&#39;] <br>X = advertisement_data.drop([&#39;Sales&#39;],axis=1) <br><br>X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=42) </pre><p>Using LinearRegression class from scikit-learn, we created an instance. lin_reg_model is now an object that represents a linear regression model. The fit method takes two main parameters<br>X_train, features (independent variables) from the training set and<br>Y_train, target variable (dependent variable) from the training set.<br>The linear regression model will learn the coefficients for each feature during this training process, aiming to create a linear relationship that predicts the target variable (Y_train) based on the features (X_train)</p><pre># loading the linear regression model <br>lin_reg_model = LinearRegression() <br># Now we can fit the model to our dataset <br>lin_reg_model.fit(X_train,Y_train) </pre><p>predicting the target variable (Y_train) based on the features (X_train)</p><pre># prediction on Training data <br>training_data_prediction = lin_reg_model.predict(X_train) </pre><p>The performance of the linear regression model on the training data is calculated by using the R-squared error. A higher R-squared value indicates a better fit of the model to the training data.</p><pre># R squared Error <br>train_error_score = metrics.r2_score(Y_train, training_data_prediction) <br>print(&quot;R squared Error - Training : &quot;, train_error_score) </pre><p>predicting the target variable (Y_test) based on the features (X_test)</p><pre># prediction on Training data <br><br>Y_pred = lin_reg_model.predict(X_test) </pre><p>The performance of the linear regression model on the testing data is calculated by using the R-squared error.</p><pre># R squared Error <br><br>test_error_score = metrics.r2_score(Y_test, Y_pred) <br>print(&quot;R squared Error - Test: &quot;, test_error_score) </pre><p>To plot the best fit line,</p><pre># create scatterplot with regression line<br>sns.regplot(x=Y_test, y=Y_pred, scatter_kws={&quot;color&quot;: &quot;green&quot;}, line_kws={&quot;color&quot;: &quot;blue&quot;})<br><br># Add labels and title<br>plt.xlabel(&quot;Actual Values (Y_test)&quot;)<br>plt.ylabel(&quot;Predicted Values (Y_pred)&quot;)<br>plt.title(&quot;Scatterplot with Regression Line&quot;)<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*Mc5DKEeOCc1Ae1rtj2kj1A.png" /></figure><p>If you encounter any uncertainties during the implementation, please refer to my Colab; I have provided the <a href="https://github.com/Nandhini-Muthusamy/datasets-linear-regression/tree/master/advertising_implementation"><strong>link</strong></a> here for your reference.</p><p>In an upcoming blog post, we will delve into detailed explanations of underfitting and overfitting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2d858d934ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>