Zero Labs
Industry News / AI

Linear Regression with OLS: Simple & Multiple Regression

Source · Towards AI By Anas Razy

From the publisher’s feed, collected in the ZeroLabs newsroom.

Learn Simple and Multiple Linear Regression through step-by-step OLS derivations with Code.Notes Image by authorIf you’re learning Machine Learning and feeling overwhelmed by scattered explanations across different sources, you’re not alone. In this article, I’ll walk you through the way I understood the concepts while learning them myself. I’ve gathered ideas, explanations, and insights from multiple sources and combined them into one place so you can follow the journey more easily.Linear RegressionLet’s try to understand what really is Linear Regression…? 🤔What is Linear Regression?💭 Imagine you have some information (input data, ex: a student’s CGPA or grade) and want to predict something else (target data, ex: How much package he got?). Linear Regression helps us find a pattern between them so that we can make future predictions.Linear Regression itself is of three types —Simple Linear RegressionMultiple Linear RegressionPolynomial Linear RegressionFor the simplicity of this article, we’ll only cover Simple and Multiple Linear Regression so that we can dive deep into the maths and intuition without burning out.You probably already know that data can be represented on graphs. The number of dimensions depends on how many independent variables (inputs) we have. For example, with one input variable, we can plot the data on a 2D graph. With two input variables, we need a 3D graph, and with even more variables, we move into higher dimensions that are difficult to visualize.In Linear Regression, we’ll focus on data where the relationship between the input and output is approximately linear, meaning the data points tend to follow a straight-line pattern.So the question is: How do we find the best line that represents this data?How does it work?Linear Regression helps us finds the line or plane (or hyperplane) that disappoints the least number of data points.Simple Linear Regression visualization — by authorIn the case of a single independent variable or Simple Linear Regression, our goal is simply to draw a straight line that passes as close as possible to all the data points.But what happens when we have multiple independent variables?We move beyond a simple 2D graph. With two input variables, the model is represented by a plane in 3D space. With even more variables, we enter higher-dimensional spaces that are difficult to visualize. This is Multiple Linear Regression.Multiple Linear Regression with a plane visualization — by authorThe idea remains exactly the same: instead of finding the best-fitting line, we find the best-fitting plane (or hyperplane — for nD space) that minimizes the total prediction error across all data points.Whether it’s a line, a plane, or a hyperplane, Linear Regression is ultimately trying to find the simplest shape that represents the relationship between the inputs and the target variable as accurately as possible.Error Function (E)We were talking a lot about minimizing prediction error. But what is error? Error is nothing but the how much we did mistake in predicting for example let’s say the linear line we made for Package vs. CGPA graph we predicted the student’s package to be about 9 lpa but that student had got 11lpa in reality why so? Because real world data are affected by different factors it is never perfect. Here how much error we made?11–9 = 2 lpawhere, 2 is the error.Errors in Linear Regression visualization — by authorYou can look at the graph above, it clearly shows each errors (d) in a visualised manner that error is the difference between the actual value and the predicted value.We can say,E = d1 + d2 + d3 + … + dnThe individual errors can be negative which will cancel out positive errors and we don’t want that to happen! Therefore, we square each errors.Note: You must be thining why we didn’t take the modulus? If we take the mod, our error function will not be differentiable at zero.so,E = d1² + d2² + d3² + .. + dn²E = ∑di²where, summation is from i = 1 to i = nWhat was d?we defined d as subtraction of predicted value from the actual value.d = yi — ŷiwhere,yi is actual value, ex: 11 lpaŷi is the predicted value, ex: 9 lpaFinally,E = ∑(yi — ŷi)²Now, we only need to minimize the error. But how?There are two common ways to do this:Ordinary Least Squares (OLS) — We solve the equation mathematically and directly arrive at the optimal solution in one shot.Gradient Descent — Instead of solving the equation directly, we start with a random guess and gradually move towards the optimal solution step by step.Both approaches aim to find the values that minimize the error. The difference lies in how they reach the solution.In this article, we’ll focus on the Ordinary Least Squares (OLS) method.Simple Linear RegressionIntuitionFor Simple Linear Regression (when we have only one independent variable), the relationship between the input and output is represented by a straight-line equation:y = mx + bwhere,y is the predicted value (dependent variable, can be represented as ŷ) — for ex: How much package a student got?x is given input — for ex: Student’s CGPA or Gradeb is the intercept (the value of y when x = 0)At this point, our problem boils down to finding two numbers: m and b. Different values of m and b produce different lines, but only one line fits the data best. The best-fit line is the one whose predictions are closest to the actual data points, resulting in the smallest overall error.Mathematical Derivation of Simple Linear RegressionWe know that the equation of a straight line is:y = mx + bOur goal is to find the values of m and b that produce the best-fit line.To measure how good or bad a line is, we define an Error Function (also called a Loss Function):E = Σ(yi − ŷi)²Since our prediction comes from the line equation:ŷi = mxi + bwe can substitute it into the error function:E = Σ(yi − (mxi + b))²Notice something important here.The error function E depends on both m and b. In other words, E is a function of two variables:E(m,b)If you expand the squared term, you’ll notice that E is a quadratic function. A quadratic function has the general form:Ax² + Bx + Cand its graph is bowl-shaped.Quadratic Equation graph via MathBits.comWhy is this important?Because when we want to minimize a function, we are essentially trying to find the lowest point of its graph.A bowl-shaped graph has a very special property: it contains one and only one global minimum and no maxima.To find that minimum, we differentiate the function and equate it to zero.Normally, when we differentiate and set the derivative equal to zero, we obtain a stationary point where the slope becomes zero. This point could be either a maximum or a minimum.However, in our case we don’t need to worry about that.Since the error function is quadratic and bowl-shaped, it has only one global minimum and no maximum. Therefore, we can directly differentiate and set the derivatives equal to zero.Since E depends on both m and b, we need to compute two partial derivatives:∂E/∂b = 0 and ∂E/∂m = 0Step 1: Differentiate with respect to bStarting with:E = Σ(yi − mxi − b)²Differentiating with respect to b:∂E/∂b = -2 Σ(yi − mxi − b)Setting it equal to zero:Σ(yi − mxi − b) = 0Expanding:Σyi − mΣxi − nb = 0Rearranging:b = (Σyi − mΣxi)/nDividing numerator and denominator by n:b = ȳ − m x̄This gives us the value of the intercept.Step 2: Differentiate with respect to mAgain starting with:E = Σ(yi − mxi − b)²Differentiating with respect to m:∂E/∂m = -2 Σ xi(yi − mxi − b)Setting it equal to zero:Σ xi(yi − mxi − b) = 0Substituting:b = ȳ − m x̄and simplifying gives:m = Σ[(xi − x̄)(yi − ȳ)] / Σ[(xi − x̄)²]This is the standard form of the slope equation.Final EquationsWe have successfully derived both parameters:m = Σ[(xi − x̄)(yi − ȳ)] / Σ[(xi − x̄)²]b = ȳ − m x̄Once we compute these values from the data, we can substitute them into:y = mx + band use the resulting line to make predictions.💡 Want to see the full derivation walk-through? I’ve covered it in a 30 mins lecture:https://medium.com/media/ad2e090d3470fbb38f1a4334f3bc44b7/hrefCoding our own Simple Linear Regression classclass MeraLR: # or my LR class # initializer def __init__(self): self.m = None self.b = None # fit data with X_train and y_train or Xi and Yi_cap def fit(self, X_train, y_train): num = 0 den = 0 for i in range(X_train.shape[0]): # just write the formula as it is for both m and b num = num + (X_train[i] - X_train.mean()) * (y_train[i] - y_train.mean()) den = den + (X_train[i] - X_train.mean()) ** 2 self.m = num/den self.b = y_train.mean() - (self.m * X_train.mean()) print(self.m) print(self.b) # our final y prediction will be equal to mx+b def predict(self, X_test): return self.m * X_test + self.bfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2)lr = MeraLR()lr.fit(X_train, y_train)lr.predict(X_test[0])Mathematical Derivation of Multiple Linear RegressionIn Simple Linear Regression, our prediction equation was:y = mx + bSince we had only one independent variable, we only needed one slope (m) and one intercept (b).But what if we have multiple independent variables?For example, a student’s salary package may depend on multiple factors:CGPANumber of ProjectsInternship ExperienceCommunication SkillsIn such cases, a single slope is no longer sufficient. We need one coefficient for each feature.The equation becomes:y = β₀ + β₁x₁ + β₂x₂ + … + βₙxₙwhere:β₀ is the interceptβ₁, β₂, …, βₙ are the coefficients (weights)x₁, x₂, …, xₙ are the input featuresWe can also write this more compactly as:ŷ = β₀ + Σ βᵢxᵢThis is exactly the same equation, just written using summation notation.Writing the Equation in Matrix FormWhen dealing with many features, writing long equations becomes inconvenient.Instead, we represent everything using matrices.Notes image by authorThe prediction vector can be written as:ŷ = XβNotice that the “+” signs from (a) disappeared in (b)It is because matrix multiplication already performs all the multiplications and additions internally.Here:X is the feature matrixβ is the coefficient vectorŷ is the prediction vectorDefining the ErrorJust like Simple Linear Regression, we want our predictions to be as close as possible to the actual values.The residual (error) vector is:e = y — ŷOur goal is to minimize the Sum of Squared Errors:E = Σ(yi — ŷi)²In matrix notation, this becomes:E = eᵀeSubstituting e:E = (y — Xβ)ᵀ(y — Xβ)This is the matrix version of the same squared error function we used in Simple Linear Regression.Before dealing with the matrix you must know how to solve it, please refer to the cheatsheet below:Matrix multiplication cheatsheet via University College LondonExpanding the Error FunctionExpanding:E = (y — Xβ)ᵀ(y — Xβ)Using matrix transpose rules:E = (yᵀ — (Xβ)ᵀ)(y — Xβ)Further expanding:E = yᵀy — yᵀXβ — βᵀXᵀy + βᵀXᵀXβNotice that:yᵀXβ and βᵀXᵀy are scalars and are equal (refer to the cheatsheet).Therefore:E = yᵀy — 2βᵀXᵀy + βᵀXᵀXβNow our entire error function depends only on β.Differentiating with Respect to βCommon Matrix/Vector Derivatives cheatsheet via University College LondonTo find the minimum error, we differentiate E with respect to β and equate it to zero as we did in Simple Linear Regression.Differentiating:∂E/∂β = -2Xᵀy + 2XᵀXβSetting it equal to zero:-2Xᵀy + 2XᵀXβ = 0Dividing by 2:-Xᵀy + XᵀXβ = 0Rearranging:XᵀXβ = XᵀyThis equation is known as the Normal Equation.Solving for βTo isolate β, multiply both sides by:(XᵀX)⁻¹Therefore:β = (XᵀX)⁻¹XᵀyAnd that’s it.We have successfully derived the coefficients for Multiple Linear Regression.Final SolutionThe optimal coefficient vector is:β = (XᵀX)⁻¹XᵀyOnce we compute β, we can plug it back into:ŷ = Xβto generate predictions.This equation is the matrix equivalent of the formulas we derived for m and b in Simple Linear Regression. Instead of solving for one slope and one intercept, we are now solving for all coefficients simultaneously using linear algebra.Coding our own Multiple Linear Regression classclass MeraLR(): # my Linear Regression class def __init__(self): self.coef_ = None self.intercept_ = None def fit(self, X_train, y_train): # using np.insert we can add a column directly to matrix # because we need 1 inseted in the matrix X's first column # as we saw in matrix representation above X_train = np.insert(X_train, 0, 1, axis=1) # to matrix, column number, what value, at what axis # calculate coefficeint # to calculate inverse of a matrix we use np.linalg.inv betas = np.linalg.inv(np.dot(X_train.T,X_train)).dot(X_train.T).dot(y_train) self.intercept_ = betas[0] self.coef_ = betas[1:] print(betas) def predict(self, X_test): y_pred = np.dot(X_test, self.coef_) + self.intercept_ return y_predfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2)lr = MeraLR()lr.fit(X_train, y_train)lr.pred = lr.predict(X_test)r2_score(y_test, y_pred)Key TakeawaysLinear Regression finds the best-fit line (or hyperplane) by minimizing the Sum of Squared Errors — squaring keeps errors positive and makes the function differentiable.For Simple Linear Regression, OLS gives closed-form formulas for slope m and intercept b by setting partial derivatives of the error function to zero.For Multiple Linear Regression, the same idea extends to matrix form — the optimal coefficients are given by the Normal Equation: β = (XᵀX)⁻¹Xᵀy❤️ T️hat’s it for this blog! See you soon…Linear Regression with OLS: Simple & Multiple Regression was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.