<?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 Gourav K Nayak on Medium]]></title>
        <description><![CDATA[Stories by Gourav K Nayak on Medium]]></description>
        <link>https://medium.com/@gourav-k-nayak?source=rss-3a9d753cad72------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sYHhoRr_WpfHOmYkvYcxdg.jpeg</url>
            <title>Stories by Gourav K Nayak on Medium</title>
            <link>https://medium.com/@gourav-k-nayak?source=rss-3a9d753cad72------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:16:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gourav-k-nayak/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[Linear Regression: Everything From Math to Program Part-2]]></title>
            <link>https://medium.com/swlh/linear-regression-everything-from-math-to-program-part-2-d5f783740496?source=rss-3a9d753cad72------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5f783740496</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gourav K Nayak]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 23:42:54 GMT</pubDate>
            <atom:updated>2021-02-16T07:25:15.500Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Everyone!!!</p><p>This is the second part of the series <strong>Linear Regression: Everything From Math to Program.</strong></p><p>Part 1: <a href="https://medium.com/swlh/linear-regression-everything-from-math-to-program-ae4c78ddd4b8"><strong>Regression with One Independent Variable</strong></a></p><blockquote>Part 2: <strong>Regression with Two Independent Variable</strong></blockquote><p>Part 3: <a href="https://gourav-k-nayak.medium.com/linear-regression-everything-from-math-to-program-part-3-1b0fa495f42"><strong>Regression with Multiple Independent Variables</strong></a></p><p>Earlier in Part-1, we have learned about how to perform linear regression in the case of one independent variable in python and Excel. We have also derived the general expression for calculating slope and intercept of a one independent variable linear regression problem.</p><p>In this part, we are continuing our learning and <strong>derive a general expression for a multiple linear regression problem</strong>. Later we will use the derived expression to solve one of the linear regression problems with two independent variables. We will represent <strong>each step using excel and also implement the programming version using Python with </strong><a href="https://numpy.org/"><strong>NumPy</strong></a><strong> library</strong>. If you haven’t read Part-1 of this series you might not be able to understand few concepts of residual error. But if you think you are good with those concepts, you can skip them.</p><p>To understand Multiple Linear regression, we need some basic knowledge of Matrices and differential calculus which probably was part of your high school math. I will try to explain each step as much as possible and will give you some resources to understand the derivation part. That should suffice everything you need for this algorithm.</p><p>So, Let’s begin!!!</p><p><strong>Regression with Two Independent Variable</strong></p><p>As the name suggests, there are two independent variables X1 and X2 in the problem, that determines the value of dependent variable Y. Also, the relationship between X1 and X2 with Y should be linear. The objective of the problem is to determine the best <strong>plane</strong> that fits for all the given values of X1 and X2. Note that in regression with one independent variable, the objective was to find the best <strong>line.</strong></p><p>It is possible to plot the graph and visualize the points using some visualization tools like <a href="https://www.fusioncharts.com/"><strong>FusionCharts</strong></a>, <a href="https://www.fusioncharts.com/"><strong>Plotly</strong></a><strong>,</strong> etc. We can also use 3-D plot packages in R and Python to visualize the data. I will show that in the end as well.</p><p>Let’s view the example problem first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*B5T6k_5tWbjbqVDQtnjBBA.png" /><figcaption>Sample data</figcaption></figure><p>General form of a multiple linear regression equation is:</p><p>Y = β₀ + β₁X₁ + β₂X₂ + ….. + βₘXₘ (equ.1)</p><p>where β₀ is a constant and β₁, β₂…βₘ are the regression coefficients.</p><p>In case of a two independent variable regression problem, equ. 1 can be simplified as,</p><p>Y = β₀ + β₁X₁ + β₂X₂</p><p>In case of more than two independent variable regression problem (n variables and m given data), every row can be written as,</p><p>Y₁ = β₀ + β₁X₁₁ + β₂X₁₂+…+ βnX₁n</p><p>Y₂ = β₀ + β₁X₂₁ + β₂X₂₂+…+ βnX₂n</p><p>Y₃ = β₀ + β₁X₃₁ + β₂X₃₂+…+ βnX₃n</p><p>.</p><p>.</p><p>.</p><p>Ym = β₀ + β₁Xm₁ + β₂Xm₂+…+ βnXmn</p><p>This data can be re-written in matrix form as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*mLH0_OfnFv5VpZ7CTAoxwQ.png" /><figcaption>Matrix representation of data</figcaption></figure><p>Since now you understood the general form of the equation, we can safely say that for a set of multiple independent variables a predicted dependent variable can be calculated using the below formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*6neIvCMjNRnNgYIZcvXoBw.png" /><figcaption>General Representation of multiple independent variable linear regression equation for predicted data</figcaption></figure><p>It is clearly evident that to compute Yᵖ, all the biases need to be set. A little knowledge of the matrix here will prove handy.</p><p>From Part-1, We know that error is the difference between the predicted and actual value of y and thus, given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*TiQmLhQJtX5C7xVhxQtkqg.png" /><figcaption>Residual Error</figcaption></figure><p>which in matrix form for all the given data can be written as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*Uq5LcY99q8EHAHbBrOTmEg.png" /><figcaption>Matrix representation of residual Error</figcaption></figure><p>Sum of the squared Error will be,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*N32ie7wo4UGIcmPRFhM2Xw.png" /></figure><p>On simplifying we get,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*rPfYXkq7sIwoPhBH-FQwIw.png" /><figcaption>Simplified RSS</figcaption></figure><p>Our motive is to reduce this error and thus, we will use partial differentiation w.r.t βᵖ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*TY45_3Q600F0XyveYYmGJg.png" /><figcaption>Partial differentiation for RSS</figcaption></figure><p>Putting the value of RSS we obtained above and solving,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*LuBkRTa_Br77uS9yPMMHhw.png" /></figure><p>And this is the formula we are seeking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*PMBfFxeiZj3yeXdkzlSptA.png" /><figcaption>Independent variable Linear regression formula</figcaption></figure><p>If you remember this formula, you would be able to answer all the questions you need to solve for multiple independent variables.</p><p>Let’s start solving the problem we assumed and predict the best-fit plane for our data. I will use excel for displaying the manual calculations and python in the jupyter notebook for the programming part. You are free to refer to this code and implement it in any other language for your own data.</p><p><strong>Step 1: Create or import the data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*5RDuV-axC2t-KNaIUAFGcA.png" /><figcaption>Data representation in Excel</figcaption></figure><p>We are using NumPy to create matrices. We will use two different variables to store our feature data (or independent variables) and labels (or dependent variable).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*6oGniwxoow6E89dJCeuN5g.png" /><figcaption>Matrices in Python</figcaption></figure><p><strong>Step 2: Transform the feature matrix</strong></p><p>We need to append columns of value 1 into the feature matrix to take the bias variable Beta0 into account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*esRsSG22kgITTH1PJCSynA.png" /><figcaption>Feature Matrix in Excel</figcaption></figure><p>In Python, this can be achieved in two steps. First, create a NumPy matrix of values 1 and size equal to rows of given data (N = 5). Then, stack this matrix horizontally on the existing feature matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*SEfV6wQnc71SMBTASfWiJA.png" /><figcaption>Feature Matrix in Python</figcaption></figure><p>Note how the dimension of the feature matrix changed from (5, 2) to (5, 3) because of the additional column of ones.</p><p><strong>Step 3: Find transpose of the feature matrix</strong></p><p>In Excel, we can do this using the <a href="https://support.microsoft.com/en-us/office/transpose-function-ed039415-ed8a-4a81-93e9-4b6dfac76027">TRANSPOSE</a> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*9JpIhk-MK1xcQolzkDNTgA.png" /><figcaption>Transpose of Feature Matrix in Excel</figcaption></figure><p>In Python, it can be easily performed using the <a href="https://www.w3resource.com/numpy/manipulation/transpose.php">transform</a> function provided by Numpy. Look at how the shape of the array reversed here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*E9CYfwKGMi1s5vDq4U3ErA.png" /><figcaption>Transpose of Feature Matrix in Python</figcaption></figure><p><strong>Step 4: Multiply Transpose of Feature Matrix with Original Feature Matrix</strong></p><p>We use the <a href="https://support.microsoft.com/en-us/office/mmult-function-40593ed7-a3cd-4b6b-b9a3-e4ad3c7245eb"><strong>MMULT</strong></a> function in Excel to perform multiplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*dX7qwLgC7JkYKS69SmSvhA.png" /><figcaption>Multiplication of X transpose with X in Excel</figcaption></figure><p>In python, we use the <a href="https://numpy.org/doc/stable/reference/generated/numpy.dot.html"><strong>dot product</strong></a> to multiply 2 matrices of any size, unless one of the matrices is scalar. In that case, we use to multiply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*iNyJZC142m7_XLmE9niL1A.png" /><figcaption>Multiplication of X transpose with X in Python</figcaption></figure><p><strong>Step 5: Inverse of Resultant Matrix</strong></p><p>We use the <a href="https://support.microsoft.com/en-us/office/minverse-function-11f55086-adde-4c9f-8eb9-59da2d72efc6"><strong>MINVERSE</strong></a> function in Excel for finding the inverse of a matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*1IbfPWCBVeEvfGwHcOHAnA.png" /><figcaption>The inverse of the resultant product of matrix in excel</figcaption></figure><p>In python, we can do this using the <a href="https://numpy.org/doc/stable/reference/generated/numpy.linalg.inv.html">multiplicative Inverse</a> function of a matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*KF8AFxdAvMsijB1aPMDj0Q.png" /><figcaption>The inverse of the resultant product of matrix in Python</figcaption></figure><p><strong>Step 6: Product of Transpose of feature matrix and dependent variable</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*1JMyvmeknwu8vtrPXIdKPA.png" /><figcaption>Multiplication of X transpose and Y in Excel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*kenbKLCwbuaCg_JkDtdIxQ.png" /><figcaption>Multiplication of X transpose and Y in Python</figcaption></figure><p><strong>Step 7: Find Regression Coefficient</strong></p><p>Regression coefficient can be calculated using the dot product of matrices obtained in results in step 6 and step 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*iKPdbOLu2VKBpOHHZo2k5w.png" /><figcaption>regression coefficient in Excel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*mHNqKsNaIXiasZDiKwfJAA.png" /><figcaption>regression coefficient in Python</figcaption></figure><p><strong>Step 8: Predict the dependent variable</strong></p><p>We will calculate the predicted value of the label using the predict_label method in python which will accept values of X1 and X2 as an argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*l1mWHM52A9w6Q1yI9xV0Wg.png" /><figcaption>Prediction from the best-fit plane in Excel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WF0Vl-Oh2BwRi8-qjC0Gug.png" /><figcaption>Prediction from the best-fit plane in Python</figcaption></figure><p><strong>Step 9: Plotting</strong></p><p>We have used matplotlib package to plot the points in python. This is definitely not the best way to plot the points in terms of implementation but I didn’t want people to confuse with loops. But that won’t be the case in part 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*fi1F1smCeZDi8WSph1r0IQ.png" /><figcaption>plotting in 3-D space using Python</figcaption></figure><p>Please refer to <a href="https://github.com/GouravNayak/Data-Mining">my GitHub account</a> to get a complete program in Jupyter Notebook as well as the Excel File. Click on the star icon on the top right corner in GitHub to show support to my project.</p><p><strong>Conclusion</strong></p><p>This is all for part 2 of this series. In the final part, we will extend the scope of our problem by importing a dataset with more than two independent variables and build a python program from scratch.</p><blockquote>Let me know your reviews in the comments section. Follow me to get notifications of my articles and connect to me on LinkedIN.</blockquote><p>Stay Safe and healthy.</p><h3>Happy Learning!!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5f783740496" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/linear-regression-everything-from-math-to-program-part-2-d5f783740496">Linear Regression: Everything From Math to Program Part-2</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression: Everything From Math to Program Part-3]]></title>
            <link>https://medium.com/swlh/linear-regression-everything-from-math-to-program-part-3-1b0fa495f42?source=rss-3a9d753cad72------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b0fa495f42</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gourav K Nayak]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 22:49:35 GMT</pubDate>
            <atom:updated>2021-02-16T07:25:23.580Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello All !!!</p><p>This is the third and final part of the series <strong>Linear Regression: Everything From Math to Program.</strong></p><p>Part 1: <a href="https://medium.com/swlh/linear-regression-everything-from-math-to-program-ae4c78ddd4b8"><strong>Regression with One Independent Variable</strong></a></p><p>Part 2: <a href="https://gourav-k-nayak.medium.com/linear-regression-everything-from-math-to-program-part-2-d5f783740496"><strong>Regression with Two Independent Variable</strong></a></p><blockquote>Part 3: <strong>Regression with Multiple Independent Variables</strong></blockquote><p>If you have made it so far then it’s obvious you have understood concepts of Linear regression and how those beautiful libraries on regressions working in the back-end. I don’t want to share anything fancy with you guys at this point and make this blog lengthy and complicated. There are no derivations in this part and we will use the same concept that we have derived in part 2. We are also not performing calculations on Excel since the dataset we are working on will be huge and Excel won’t help us in that. So what we are going to do in this part.</p><p>We will build on what we have learnt so far in the last 2 parts by writing a program in Python to predict a dependent variable Y based on multiple independent variables X1, X2, X3 and so on. We are not using any popular libraries like <a href="https://scikit-learn.org/stable/">Scikit-learn</a> to build linear regression model. There are humongous tutorials for that. We will use numpy for matrices operation and see how we accomplish the task step-by-step so that even a novice can understand it.</p><p>Please refer to Part-2 for all the basic operations. In this tutorial, we are going to build general program which can be implemented on <strong>dataset of any size</strong>.</p><p><strong>Prerequisites: </strong><a href="https://pandas.pydata.org/"><strong>pandas</strong></a></p><p>Please share your thoughts on this series in the comments section or connect to me on LinkedIN. I would be happy to help. Also, don’t forget to follow me on <a href="https://medium.com/">medium.com</a> for more such posts in the future.</p><p>Let’s begin!!!</p><p><strong>Step 1: Understand the dataset</strong></p><p>In this tutorial, we are using an <a href="https://www.kaggle.com/mirichoi0218/insurance">insurance dataset</a> from <a href="https://www.kaggle.com/">Kaggle</a>. There are 7 columns in the dataset: age, sex, bmi, children, smoker, region, insurance charges. Our task is to predict the insurance charges on the basis on age, sex, bmi (body mass index), children (number of children covered by health insurance), smoker (does person smokes) and region (residential area of beneficiary).</p><p><strong>Step 2: Import libraries</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*kjGYgZbyUq1US6JLh0JxTg.png" /><figcaption>importing libraries in python</figcaption></figure><p><strong>Step 3: Read dataset</strong></p><p>We will use pandas library to read the csv file that we have downloaded from <a href="https://www.kaggle.com/mirichoi0218/insurance">here</a> and perform other operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*d-QNaESkl0TLiDoSmoX7Bw.png" /><figcaption>Insurance dataset</figcaption></figure><p>There are 1338 rows and 7 columns.</p><p>Until now we have worked with numerical type independent variables. The other type is categorical or text format. In our dataset, they are sex (male or Female), smoker(yes or no) and region (Southwest, southeast, northwest etc.) We need to convert this columns datatype into integer before regressing.</p><p><strong>Step 4: Convert datatype of columns to integer</strong></p><p>To do so, we will use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.astype.html">astype</a> method by pandas to convert the columns to a category like 1 for yes and 0 for no. And then, assign the encoded variable to a new column using the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html">cat.codes</a> accessor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*f6sdvOfuytQ-Mm0lD2G7rw.png" /><figcaption>convert categorical variables to integer</figcaption></figure><p><strong>Step 5: Convert Pandas dataframe to numpy array</strong></p><p>We could have used pandas for implementation of this program but I wanted to reuse the code we developed in part 2 and thus converting it to numpy array. We will use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html">to_numpy</a> function provided by Pandas to do so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*61qaS_TqDn-ySr8Xn5Q_EA.png" /><figcaption>Convert dataframe to numpy array</figcaption></figure><p><strong>Step 6: Prepare training and testing data</strong></p><p>We are using numpy array <a href="https://numpy.org/doc/stable/reference/arrays.indexing.html">indexing</a> to split the entire dataset into training feature and label as well as testing feature and testing label. We are using first 1334 rows for predicting the values of regression coefficients and use last 4 rows to test the performance of predicted equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*rTW9ClvB1j_ut7MtPzeCVw.png" /><figcaption>Training data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*_umUYB_BgZr7GI3W2JMoXw.png" /><figcaption>Testing data</figcaption></figure><p><strong>Step 7: Calculate Regression coefficent</strong></p><p>From here onwards, all the steps for predictions are same as explained in part 2. Please refer to part 2 in case you are unable to infer any part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*sspPYm5_PXaUlgJvcUdGDA.png" /><figcaption>Transform test feature matrix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*NIuX9QtTE5sFcmfyvtVKFw.png" /><figcaption>Transpose of test feature matrix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*bbQRwTl_bPUwpY6oaV6c0Q.png" /><figcaption>Product of Transpose of test feature matrix and original matrix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*Um7aCxS_4mypW-8aXE0aSA.png" /><figcaption>Inverse of resultant matrix</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*6DKJzsRs56F0ForDRbl2aA.png" /><figcaption>Product of Transpose of feature matrix and dependent variable</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*MH10CmCI3giTinO4KeS9ug.png" /><figcaption>regression coefficents</figcaption></figure><p>Note that the number of column of regression coefficent matrix (=6) is 1 greater than number of dependent variables (= 5)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*yA7CcvSwA-VTGIM2iE13bg.png" /><figcaption>Values of regression coefficent matrix</figcaption></figure><p><strong>Step 8: Prediction</strong></p><p>In this step we will predict the testing data that we have created in step 6 and calculate the value of dependent variable (or insurance charges)</p><p>This may seem pretty daunting to you if you are not familiar with programming in python. Let me break it down for you.</p><p>Firstly we create a numpy matrix of size equal to number of testing data (=4). Then for each testing row we substituted the value of regression coefficents and calculated the predicted value of Y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*gfM6jnA-c4JdizvhHpKrFg.png" /></figure><p>As usual, you can refer to <a href="https://github.com/GouravNayak/Data-Mining">my github account</a> to get complete program in Jupyter Notebook. Click on star icon on top right corner in github to show support to my project.</p><p><strong>Conclusion</strong></p><p>This was all I had to share with you guys on Linear regression. Please drop your reviews on the posts in the comments section. You can connect to me on LinkedIN if you want to discuss anything. I am always happy to help :)</p><p>Till next post… Stay Safe and stay healthy and keep learning.</p><h3>All the best!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b0fa495f42" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/linear-regression-everything-from-math-to-program-part-3-1b0fa495f42">Linear Regression: Everything From Math to Program Part-3</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression: Everything From Math to Program]]></title>
            <link>https://medium.com/swlh/linear-regression-everything-from-math-to-program-ae4c78ddd4b8?source=rss-3a9d753cad72------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae4c78ddd4b8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Gourav K Nayak]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 08:36:27 GMT</pubDate>
            <atom:updated>2021-02-13T23:43:41.425Z</atom:updated>
            <content:encoded><![CDATA[<p>A few days ago I was trying to solve one of the problems given to me in my school. They asked us to impute some missing values in a given dataset. Those of you who are aware of the term ‘imputation’, you know that there are countless algorithms published in various studies for different kinds of data.</p><p>Some of the algorithms for imputing a missing value is:</p><ol><li>3M (Mean, Median, Mode) imputation</li><li>Least Square Imputation</li><li>Hot/Cold Deck Imputation</li><li>Linear Regression Imputation</li><li>Stochastic Regression Imputation</li></ol><p>And many more…</p><p>In our problem, it was clearly mentioned that the given data has <strong>linear relationship</strong> and weneed to impute the values by <strong>regression</strong> method. To my surprise there were so many resources we can use to study and solve the problems and everyone was fantastic with their work. But, I was not able to relate to any of them. The reason behind this was some of the posts were solving a <strong>particular problem</strong> either by hand or a programming library. Few others were talking about math for solving problems with one or two independent variables. And rest were throwing solutions for multiple independent variables. There was no single post that approaches the problem from ground and build it to the end, at least I couldn’t find one. Now, you can definitely refer to these resources to learn but I found it difficult when I am unable to devise some relationships between them because they are eventually coming from different people and every individual has their own style of approaching the problem.</p><p>I will go through the math behind regressions for one, two and multiple independent variables, formulate the equations, and in the end develop the program in python to solve an example of regression problem. Every problem will be discussed at basic level and with appropriate examples. I will use a small dataset and solve it using Excel so that it is easy to view and understand. For the sake of simplicity, I am breaking this post in 3 parts. Each of this will discuss one part of the problem and you can skip forward to learn topic that interests you.</p><blockquote>Part 1: <strong>Regression with One Independent Variable</strong></blockquote><p>Part 2: <a href="https://gourav-k-nayak.medium.com/linear-regression-everything-from-math-to-program-part-2-d5f783740496"><strong>Regression with Two Independent Variable</strong></a></p><p>Part 3: <a href="https://gourav-k-nayak.medium.com/linear-regression-everything-from-math-to-program-part-3-1b0fa495f42"><strong>Regression with Multiple Independent Variables</strong></a></p><p><strong>Prerequisites: </strong>Linear Equations, basic programming in any language python preferably, <a href="https://miro.medium.com/max/1250/1*Yz_b7ZiFky34N4FvWJI5NQ.png">correlation</a> and it’s significance.</p><p>This is my first blog on <a href="https://medium.com/">Medium.com</a> and I am very excited for this. Hope it helps someone.</p><p>So, Let’s begin!!!</p><p><strong>Regression with One Independent Variable</strong></p><p>First let’s understand what do we mean by regression problem with one independent variable.</p><p>When we have only <strong>one</strong> independent variable, say X whose value decides the value of a dependent variable, say Y and the relation between them is linear then it is a linear regression problem with one independent variable. A <strong>linear relationship</strong> between two variables is when one value increases or decreases, the value of other variable also increase or decrease proportionally i.e by multiple of some amount that we call constant which is a scalar value.</p><p>Y = c.X, where c is a constant</p><p>It is possible to plot points for linear data in a graph and then find the best line that fits that data. By fit we mean that best describes the relationship between the data.</p><p>Let’s take an example and work on that to understand the concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*bNTTzCAjSWQYgseFNIbxfw.png" /><figcaption>Sample data</figcaption></figure><p>If we plot these points on a graph, it will look like below figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*8Abz9w0GTkYUpLIDuUEzmA.png" /><figcaption>Scatter Plot</figcaption></figure><p>As we discussed before, we need to find equation of a line that best fits the given data. Linear equation of a line is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*xQTLWKdWqvcTYO-iR3tz_Q.png" /><figcaption>General Equation of straight line</figcaption></figure><p>where m is the slope, C is the intercept of line on y-axis.</p><p>If we have slope and intercept then we can find value of Y for any value of X. In an ideal linear regression problem, all the points on graph will fall in one line but that is rarely the case in real life. Thus, we predict the best fit line for the data. Let’s see how.</p><p>Let’s assume the equation for best fit line predicted for the given data is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*iQtTxDKVL2YrYlpR76OnQA.png" /><figcaption>Equation of Predicted line</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*pdMUCHe88U5IKYvDuYlBwg.png" /><figcaption>Representation for Linear regression</figcaption></figure><p>The important term to understand here is Error, or some call it residual. This is the difference of actual and predicted value of Y given by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*tnBRuBxom3-VDOZO6XX6hg.png" /><figcaption>Residual at i</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*HDUDcz3nzW9cOBvvT23G_Q.png" /><figcaption>Prediction at i</figcaption></figure><p>Hence,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*7aesouFkkUZB_66xfUTZrA.png" /><figcaption>Residual at i</figcaption></figure><p>According to <a href="https://en.wikipedia.org/wiki/Least_squares#:~:text=The%20method%20of%20least%20squares,results%20of%20every%20single%20equation.">Least Square Approximation</a>, the sum of squared error can be written as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*gDQiehNqRpriYSa6Co7a4Q.png" /><figcaption>Sum of Squared Error</figcaption></figure><p>N: total number of data points available.</p><p>The best fit line can be obtained by reducing this error to the least value possible which can be done by setting the <a href="https://en.wikipedia.org/wiki/Gradient">gradient</a> to zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*ZirDBNJrJXHdG0unFzr1SA.png" /></figure><p>Solving (1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*dKrJIlUmiwK9wBbdxVkV-w.png" /></figure><p>where,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*viz_Rr5-DhsfYkuCT_m7Bw.png" /></figure><p>Solving (2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*Uz0mWiSmrDOJ9Ts2AjOQWQ.png" /></figure><p>Solving equation 3 and 4 for slope and intercept of best fit predicted line,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*r7AoTLVFJDGw8FsSsk53mQ.png" /><figcaption>Intercept of predicted line</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*fslGwlK6LCzno9PIMWJ7Bg.png" /><figcaption>Slope of predicted line</figcaption></figure><p>Let’s start solving the problem we assumed and predict the best fit line for our data. I will use excel for displaying the manual calculations and python in the Jupyter notebook for the programming part. You are free to refer to this code and implement in any other language for your own data.</p><p><strong>Step 1: Create or import the data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*IgltEPPy4TjUU5b5tq6ZbQ.png" /><figcaption>Data representation in Excel</figcaption></figure><p>We will use <a href="https://numpy.org/">Numpy</a> for creating the example matrix in python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*Scz-hxGwQh4Kc8XFfhSTKQ.png" /><figcaption>Data representation in Python</figcaption></figure><p><strong>Step 2: Calculate mean of dependent and independent variable</strong></p><p>We have added all the values of X (Sum = 123) and divide it by number of values (Count = 5) to obtain mean of X as 24.6. Similarly, Mean of Y = 51.6</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*Uqq34qJDolyy-PzVAI_K2A.png" /><figcaption>Calculation of Mean in Excel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*MgKvx2PpU-ufIMz7-picjg.png" /><figcaption>Calculation of Mean in Python</figcaption></figure><p><strong>Step 3: Calculate sum of product of dependent and independent variable</strong></p><p>We have multiplied values of X and Y for each row to obtain column XY and then add all of them to obtain a sum = 8486</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*9Zgs0-4K9wPPsqrl-Tbh3Q.png" /><figcaption>Calculation of Sum of Product of X and Y in Excel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*DA8BEczVgYjnnY80qiENJQ.png" /><figcaption>Calculation of Sum of Product of X and Y in Python</figcaption></figure><p><strong>Step 4: Calculate Sum of square of dependent variable</strong></p><p>We have squared values of X for each row to obtain column XX and then add all of them to obtain a sum = 4055</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*T0ucy7AoTTkBdYDYsp7iUg.png" /><figcaption>Calculation of Sum of Square of X in excel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*zl_qxckyf12A24JtjkkPTQ.png" /><figcaption>Calculation of Sum of Square of X in Python</figcaption></figure><p><strong>Step 5: Calculation of Slope of line</strong></p><p>We have used the formulae that we have derived in equ this and this, substituted the calculated values to obtain intercept = 0.4687 and Slope = 2.0785.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*7LYGccxZVmqxz6sqR3HVPQ.png" /><figcaption>Calculation of Slope and Intercept in Excel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*fDngXxE4ebOjjPW04DGiMg.png" /><figcaption>Calculation of Slope and Intercept in Python</figcaption></figure><p><strong>Equation of line</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*bTMYKZBBkXkVzv2Z3XK3dQ.png" /><figcaption>Equation of predicted line</figcaption></figure><p><strong>Step 6: Predict the dependent variable</strong></p><p>The easiest way to check the predicted value is by using the data available and see if you are able to obtain the correct value. We are substituting the value of X = 5 in the best fit line to obtain value of Y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*CB54vx8NS4omZkQ7Apo_0w.png" /></figure><p>which is quite close.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*5UN2g0iaMnYsepAgnpfbog.png" /><figcaption>Prediction from best fit line in Excel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*cmJj4KLMtwma5MZNg_PDwg.png" /><figcaption>Prediction for best fit line in Python</figcaption></figure><p><strong>Plotting the best fit line</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*--RSQb0IeaNlTezKBrGPgA.png" /><figcaption>Plot in python</figcaption></figure><p>Please refer to <a href="https://github.com/GouravNayak/Data-Mining">my github account</a> to get complete program in Jupyter Notebook as well as the Excel File. Click on star icon on top right corner in github to show support to my project.</p><p><strong>Conclusion</strong></p><p>I hope you guys enjoy reading this part 1 of simple linear regression and learnt something today. Let me know your reviews in the comments section and <strong>follow me</strong> to get my next articles on your suggestion lists.</p><h3>Have a good time!!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae4c78ddd4b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/linear-regression-everything-from-math-to-program-ae4c78ddd4b8">Linear Regression: Everything From Math to Program</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>