Linear Regression: Understanding the Intuition from First Principles
Rebuilding Linear Regression from first principles—from astronomical observations and residuals to the Residual Sum of Squares (RSS), normal equations, and closed-form limits.
- Machine Learning
- Linear Regression
- Data Science
- Mathematics
- Statistics
You might be wondering, "Another Linear Regression-based article?" There are so many around the internet, so why another article about the same? You are going in the right direction if this is what came to your mind, and yes, this is another one of those articles about linear regression, but what is different? It is not just about knowing what it is and implementing it using the set of Python libraries; it is more about the intuition that runs the algorithm, the fundamentals of one of the most fundamental algorithms in Machine Learning.
What is Linear Regression?
Linear Regression is a fundamental method in statistical modelling, which assumes a linear relationship between a predictor variable 'X' and a quantitative response 'Y'. The relationship is modelled as a straight line, which is used to predict the response 'Y' from the predictor 'X' such that the model parameters are estimated using the least square method to minimize the sum of squared prediction error.
Mathematically, the linear relationship between the response variable Y and the predictor variable X can be represented as:
Y_n ≈ θ₀ + θ₁ X₁ + θ₂ X₂ + … + θ_n X_nWhere:
- Y: Quantitative response
- X: Predictor Variable
- θ: Parameters
At this stage, we have defined a formal equation, but it is actually the result of a deeper reasoning process, and we need to step back a bit to understand a more fundamental question to understand the concept.
Where does Linear Regression come from?
Let's start with an example from one of our favourite topics that we enjoyed when we were children. You guessed it right! It's Astronomy.
Suppose you are an astronomer who is studying the impact of distance from Earth on the observed brightness of the star, and to prove the hypothesis, you record a dataset in the following form:
(x₁, y₁), (x₂, y₂), …, (x_i, y_i)Where:
- x_i: the distance of the star from Earth
- y_i: the observed brightness of the star
Once you have already plotted the data onto the XY plane, you realise a general trend that shows that the observed brightness decreases as the distance from Earth increases. However, these data points do not lie on a straight line due to noise, measurement error, and astrophysical variability.
Now, you want to derive a simple function that can estimate a dominant relationship by mapping these variables in a meaningful way.
The Linear Assumption
We assume that the observed brightness varies approximately linearly with the distance from Earth, which leads us to propose it in the form of a straight line:
ŷ_i ≈ θ₀ + θ₁ x_iWhere:
- θ_0 is the intercept (baseline brightness)
- θ_1 controls how brightness changes with distance
At the given stage, we don't know what the values of the parameters θ_0 & θ_1 are, but from the coordinate geometry, we know that the different choices of these parameters will provide different lines on the coordinate axis, and thus different predictions.
From where we arrive, to a very fundamental question:
Which values of θ_0 and θ_1 explain the best relationship between the observed data?
Quantifying the Prediction Error
For the given star i, the residual can be defined as the difference between the value of observed brightness and the predicted brightness by our linear model, and can be formalised as:
e_i = y_i - ŷ_i = y_i - (θ₀ + θ₁ x_i)Where:
- e_i: The residual (error) for the i-th observation
- y_i: The actual observed value
- ŷ_i: The predicted value from the model
When visualising it on a geometrical plane, the residual assumes the vertical distance between a data point and the regression line.
Since the data consists of many stars, we will obtain many residuals for the same, and to understand if the regression line we obtained is actually a "good fit", we must combine these residuals into a single measure of error.
Residual Sum of Squares (RSS)
You might be or might not be wondering if we can just assume the single measure as either the sum of residuals or the mean of the same. You are partially correct in that sense, and going for the right path, but that's not it. Simply summing the residuals or considering the average does not work. Why? Because the positive and negative errors cancel out, and to avoid that, we consider the sum of squares of residuals, which is called the Residual Sum of Squares (RSS).
Mathematically, Residual Sum of Squares (RSS) can be represented as:
RSS = e₁² + e₂² + … + e_i² = (y₁ - θ₀ - θ₁ x₁)² + (y₂ - θ₀ - θ₁ x₂)² + … + (y_i - θ₀ - θ₁ x_i)²or,
RSS(θ₀, θ₁) = Σ_{i=1..m} (y_i - (θ₀ + θ₁ x_i))²At this stage, we have already formalised an equation that can help us to interpret a decent choice of parameters; however, there are still some things that need to be considered:
- RSS can scale with the number of observations. Stepping back to our astronomy example, let us assume that we are going to calculate RSS for a dataset of 100 stars and compare it to a dataset of 10,000 stars. The larger data repository will have a massive total error because of the amount of data, which makes it difficult to assume which model is performing better at a glance.
- Suppose we add 1,000 more stars to the dataset; the raw total error would increase by a massive amount. This would build an illusion that the model is getting "worse" just because it is introduced with more information.
- The brightness values of stars can span a massive range from the blindingly bright sun to the dimmest brown dwarfs, and the square of residuals for a huge number of stars could eventually become too large for a standard computer to process.
From RSS to the Cost Function
To avoid issues like exploding values and to make the error measure independent of dataset size, we normalise the RSS by dividing it by the number of data points m.
For mathematical convenience, specifically to simplify the derivatives while calculating gradients for algorithms like gradient descent (introduced in the next article), we introduce a factor of 1/2.
Mathematically, this can be expressed in terms of J(θ_0, θ_1) to assume the normalised cost function:
J(θ₀, θ₁) = (1 / 2m) Σ_{i=1..m} (y_i - (θ₀ + θ₁ x_i))²Where:
- J(θ₀, θ₁): This is the standard notation for the Cost Function (also known as the Squared Error Function).
- 1/2m: The average of the squared errors. The "2" is added to the denominator to make the math cleaner later during the derivative / gradient descent step.
- Σ (Sigma): Summation of all errors from the 1st to the m-th data point.
- (y_i − ŷ_i)²: The square of the difference between the actual value and the prediction.
Now that we have described our learning objective, we assume a linear model to define the values of θ_0 and θ_1 that minimise the cost function for convergence.
Choosing θ₀ and θ₁ for which the cost function converges
Although we assume a linear relationship with x, the cost function is quadratic in parameters due to squaring of the errors and hence, forms a bowl-shaped (convex) surface, which is critical for optimisation as it ensures a single global minimum and no local minima to allow the algorithms like Gradient Descent to converge reliably.
Since a quadratic function is convex, it is smooth and differentiable everywhere, which makes it easy to calculate gradients and efficiently update the parameters using calculus.
Now, to locate the minimum of the cost function, we can compute the partial derivatives with respect to each parameter by setting the derivatives equal to zero:
∂J / ∂θ₀ = 0 and ∂J / ∂θ₁ = 0Where each derivative can be represented as:
∂J / ∂θ₀ = -(1 / m) Σ_{i=1..m} (y_i - θ₀ - θ₁ x_i)
∂J / ∂θ₁ = -(1 / m) Σ_{i=1..m} x_i (y_i - θ₀ - θ₁ x_i)We can further solve these equations to get the normal equations, whose solution yields the optimal values for each parameter:
Σ_{i=1..m} (y_i - θ₀ - θ₁ x_i) = 0 (Normal Equation for θ₀)
Σ_{i=1..m} x_i (y_i - θ₀ - θ₁ x_i) = 0 (Normal Equation for θ₁)Now, at a glance, they might look the same, but there is a very subtle difference, and that is due to weight. The second equation has an extra x_i multiplying the residual.
Assume the same example: the first equation or the intercept condition does not allow the model to overestimate or underestimate the brightness, as the errors cancel uniformly regardless of the distance, and hence, it anchors the line vertically.
Whereas, the second equation or the slope condition, assumes that the error is weighted by the distance, and they must be balanced out, which says that errors from distant stars are more important than the nearby ones.
The algebraic simplification of the following equations gives us a closed-form solution, giving us the optimal parameters as:
θ₁ = Σ_{i=1..m} (x_i - x̄)(y_i - ȳ) / Σ_{i=1..m} (x_i - x̄)² (Equation for the Slope)
θ₀ = ȳ - θ₁ x̄ (Equation for the Intercept)The equation comes through an important observation, that the regression line always passes through the sample mean point (\barx, \bary).
Why Least Squares?
Now, you might be wondering why we need to use the method of least squares, and a part of which we have discussed already:
- 01.The method squares both positive and negative deviations so that they contribute positively to the sum of errors by preventing them from cancelling each other.
- 02.When these errors are squared, it adds more weight to the larger errors, which forces the regression line to stay close to most of the data points.
- 03.Under certain Gaussian noise assumptions, the Gauss-Markov Theorem suggests that the ordinary least squares estimator establishes as the best linear unbiased estimator (BLUE) such that it corresponds to maximum likelihood estimation.
Limitations of closed-form solutions
While the normal equation helps us to determine the exact solutions for the parameters, it comes with certain limitations that are:
- Computational complexity: This solution demands a heavy computation to calculate the inverse of a matrix in higher dimensions, with an asymptotic complexity of approximately O(m³), where m is the number of features.
- Memory footprint: To minimise the cost function, we need to load the entire dataset into memory and perform the matrix multiplication. Assuming our example of brightness of stars and distance, the dataset can be huge, and in those cases, there is a high chance of exceeding the RAM capacity.
- Collinearity & singular matrices: Let us assume that the distance from Earth and observable brightness are perfectly correlated; in such cases, the surface of the cost function will have a "valley" rather than a global minimum at the bottom. This will result in singular matrices, and hence, the closed-form mathematics will fail to converge.
An alternative approach has been introduced to consider these limitations, where instead of solving these parameters analytically, they are iteratively updated by moving in the direction that optimises the cost function.
The approach is known as Gradient Descent.
In the next article, we will understand the intuition behind the gradient descent by visualising these parameters to move down towards the minimum in the cost surface.
References
- 01.James, G., Witten, D., Hastie, T., Tibshirani, R. and Taylor, J., 2023. Linear regression. In An Introduction to Statistical Learning: With Applications in Python (pp. 69–134). Cham: Springer International Publishing.
- 02.Montgomery, D.C., Peck, E.A. and Vining, G.G., 2021. Introduction to Linear Regression Analysis. John Wiley & Sons.
- 03.Wolberg, E.J., 2010. The method of least squares. In Designing Quantitative Experiments: Prediction Analysis (pp. 47–89). Berlin, Heidelberg: Springer Berlin Heidelberg.
- 04.Stanford CS229 Lecture Series: https://www.youtube.com/watch?v=jGwO_UgTS7I&list=PLoROMvodv4rMiGQp3WXShtMGgzqpfVfbU