Master the foundational algorithm of machine learning. Learn to predict continuous values with linear models, optimize using gradient descent, handle multiple features with matrix operations, and prevent overfitting with L1/L2 regularization.
Linear regression is arguably the most important algorithm to understand deeply. Not because it's the most powerful—it's not—but because it introduces nearly every concept you'll need for more complex models: loss functions, optimization, overfitting, regularization, and the bias-variance tradeoff.
The core idea is beautifully simple: model the relationship between inputs and outputs as a weighted sum plus a bias term. The weights tell us how much each feature contributes to the prediction. The challenge is finding the optimal weights—those that minimize the prediction errors.
For simple problems, we can solve for optimal weights analytically using calculus. But this approach doesn't scale. Gradient descent provides an iterative alternative: start with random weights, compute how the loss changes with small weight adjustments (the gradient), then nudge weights in the direction that decreases loss. Repeat until convergence.
Real problems have many features interacting in complex ways. Multiple regression extends the model to handle this, fitting a hyperplane in high-dimensional space. The normal equation gives a closed-form solution, but gradient descent is more practical for large datasets.
Regularization addresses a critical problem: models can fit training data too well, capturing noise rather than signal. By penalizing large weights, L2 (Ridge) regularization shrinks coefficients toward zero, while L1 (Lasso) can eliminate features entirely. This tradeoff between fitting the data and keeping the model simple is fundamental to all of machine learning.
This chapter covers:
Click any topic to jump in
The starting point — fit a line through data by minimizing squared errors with a closed-form solution.
Optimization for large data and extending to multiple features
Iterative optimization when closed-form solutions don't scale — follow the negative gradient to minimize loss.
Extend to many features with matrix notation, the normal equation, and feature scaling for stable training.
Nonlinear patterns and controlling model complexity
Capture nonlinear patterns while staying inside the linear regression framework via feature transformations.
Prevent overfitting by penalizing large weights — L1 for sparsity, L2 for shrinkage, Elastic Net for both.
When linear regression is appropriate and how to verify — residual analysis, influential points, and model checks.
Simple linear regression finds the best-fitting line through data points. The line minimizes the sum of squared distances (residuals) between predicted and actual values.
The Model: where is slope and is intercept.
Predicted value is a linear combination of input feature and learned weights (intercept w₀ and slope w₁). The line minimizes total prediction error.
The model defines an affine mapping from input space to output space . The parameter is the rate of change , meaning each unit increase in shifts the prediction by exactly . The intercept anchors the line at . With data points, we have 2 free parameters and constraints — the system is overdetermined when , which is why we need a loss function to define "best fit" rather than exact interpolation.
Model: ŷ = 50 + 10x. What's the prediction when x=3?
The difference between actual and predicted values. Positive = underpredicted, negative = overpredicted. Sum of residuals equals zero for OLS fit.
The residual measures the signed vertical distance from observation to the fitted line. For the OLS estimator, and — these are the normal equations. The first says residuals balance out on average; the second says residuals are uncorrelated with the predictor. Together, these two conditions uniquely determine and . Violations of these orthogonality conditions indicate the model has not converged or was computed incorrectly.
Actual y=100, predicted ŷ=85. What's the residual? Interpretation?
The average of squared residuals. Squaring penalizes large errors more than small ones. Also called L2 loss.
MSE is a convex, differentiable function of the weights. Squaring amplifies large errors: an error of 4 contributes 16 to the sum, while four errors of 1 contribute only 4. This makes MSE sensitive to outliers — a single point far from the line can dominate the entire loss. Statistically, minimizing MSE is equivalent to maximum likelihood estimation when the noise , connecting the geometric idea of "closest line" to the probabilistic idea of "most likely parameters."
Residuals: [2, -3, 1, -2]. Calculate MSE.
MSE is differentiable (unlike MAE at zero), has a unique minimum, and is equivalent to Maximum Likelihood Estimation under Gaussian noise assumption.
The MSE loss surface is a paraboloid in parameter space — it has exactly one global minimum and no local minima. The Hessian matrix is positive semi-definite, guaranteeing convexity. The absolute error has a corner at zero where the derivative is undefined, making gradient-based optimization problematic. MSE's smoothness everywhere means the gradient exists at every point, providing a well-defined direction toward the optimum.
Why not use |error| (MAE) instead of error²?
For simple linear regression, we can compute optimal weights directly using calculus. w₀ = ȳ - w₁x̄.
Setting yields . This has a clean geometric interpretation: the slope equals the correlation coefficient times the ratio of standard deviations, . When features are perfectly correlated (), the line passes through every point. When , the slope is zero and the best prediction is just . The closed-form solution requires time for simple regression, making it efficient for small feature counts.
Cov(x,y) = 15, Var(x) = 5, x̄ = 10, ȳ = 25. Find the line.
Proportion of variance explained by the model. R²=1 is perfect, R²=0 is baseline (predicting mean). Can be negative if model is worse than mean.
decomposes total variance into explained and unexplained parts: . For simple regression, — the square of the Pearson correlation. Adding features can only increase (or keep it the same), which is why adjusted penalizes model complexity by accounting for the number of parameters . A negative means the model fits worse than a horizontal line at .
SSres = 200, SStot = 1000. Calculate and interpret R².
Given data points (1,2), (2,4), (3,5), (4,4), (5,5), calculate the best-fit line using the closed-form solution.