Linear & Polynomial Regression
Zillow's "Zestimate" looks at a house in your neighborhood and tells you its price within a few percent. Strava predicts your finishing time from your training pace. Your fitness app tells you how many calories you burned from heart rate and weight. All three are doing the same thing under the hood: drawing the best line through past data and using it to predict the future. By the end of this lesson, you'll build a regression model that predicts house prices from square footage, and you'll understand exactly why each coefficient ("each extra square foot adds $147 to the price") is the number it is. No magic. Just one line, two parameters, and a tiny bit of arithmetic.
After this lesson, you will be able to:
- Understand the linear regression formula y = Xw + b — it is just a weighted sum of your inputs plus a starting value
- Explain Mean Squared Error (MSE) — the 'report card' that tells you how wrong your line is — and why we square the errors
- Find the best-fit line using either a direct formula (normal equation) or step-by-step optimization (gradient descent)
- Extend to curvy polynomial regression and understand why too many curves leads to overfitting
- Choose between the Normal Equation and gradient descent based on dataset size and feature count
Before you start
Don't worry if the math notation looks scary — linear regression is literally just drawing the best straight line through your data points. If you can plot points on graph paper and eyeball a line through them, you already get the core idea!
#The Simplest Prediction Machine
#The Model
A linear regression model predicts a continuous output as a weighted sum of input features:
In compact matrix notation for all n training examples at once:
Try it! Open the Python REPL and type these lines yourself. Fit a line in 3 lines of code:import numpy as np; x = np.array([1,2,3,4,5]); y = np.array([2,4,5,4,5]); coeffs = np.polyfit(x, y, 1); print(f"Slope: {coeffs[0]:.2f}, Intercept: {coeffs[1]:.2f}")— you just ran linear regression!
Where:
- X is the n x d data matrix (n samples, d features)
- w is the d-dimensional weight vector
- b is the bias (intercept) term
- y-hat is the vector of predictions
#Worked Example: 3 Houses and a Best-Fit Line
Let's make this concrete. You have 3 houses:
| Square feet (x) | Price (y) |
|---|---|
| 1000 | $300,000 |
| 1500 | $400,000 |
| 2000 | $550,000 |
price = w * sqft + b. Using the 1D closed-form solution w = (n·Σxy − Σx·Σy) / (n·Σx² − (Σx)²):Σx = 4500,Σy = 1,250,000,Σxy = 1000·300K + 1500·400K + 2000·550K = 2,000,000,000,Σx² = 1,000,000 + 2,250,000 + 4,000,000 = 7,250,000,n = 3w = (3 · 2,000,000,000 − 4500 · 1,250,000) / (3 · 7,250,000 − 4500²) = 375,000,000 / 1,500,000 = 250b = (Σy − w · Σx) / n = (1,250,000 − 250 · 4500) / 3 = 125,000 / 3 ≈ 41,667
price ≈ 250 · sqft + 41,667. Reading the coefficients:- Slope
w = 250— each additional square foot adds $250 to the price. - Intercept
b = 41,667— a "0 sqft house" would (in theory) cost $41.7K. This is the value of the lot/permits/foundation independent of size. The intercept rarely has a real-world meaning — it's just the y-axis crossing point.
250 · 1800 + 41,667 = $491,667. That single number is the entire output of your trained model. This is all linear regression is.#Step 1: Input Data (Scatter Plot)
You start with a collection of data points — each has input features (x) and a target value (y). Plotted on a graph, these form a scatter plot. The goal is to find the line that best describes the relationship between x and y.
#Step 2: Initialize a Random Line
The algorithm begins with a random guess for the weights (slope) and bias (intercept). This initial line usually fits the data poorly — it is just a starting point. In gradient descent, this randomness is necessary; with the normal equation, we skip directly to the solution.
#Step 3: Calculate the Error (MSE)
For every data point, measure the vertical distance between the actual value and the line's prediction. Square each distance, then average them all. This is the Mean Squared Error — a single number that tells you how wrong the current line is. Lower MSE means a better fit.
#Step 4: Compute the Gradient
The gradient tells you which direction to adjust the weights to reduce the error. It is the derivative of the MSE with respect to each weight. A large gradient means a steep slope on the loss surface — you need a big adjustment. A small gradient means you are close to the bottom of the bowl.
#Step 5: Update the Weights
Move the weights in the opposite direction of the gradient, scaled by a learning rate. The line tilts and shifts slightly toward a better fit. Each update is a small step downhill on the loss surface. With the normal equation, this step computes the exact optimal weights in one shot.
#Step 6: Repeat Until Convergence
Compute the gradient again at the new position and take another step. The MSE decreases with each iteration. Eventually, the gradient becomes tiny — the line has settled into the bottom of the loss bowl. For linear regression, this bowl is convex, so there is exactly one global minimum.
#Step 7: Final Fitted Line
The converged line is the best linear approximation of the data. Each weight tells you exactly how much that feature contributes to the prediction. The bias shifts the entire line up or down. This fitted model can now predict y for any new x value it has never seen before.
#Explore: Fitting a Line
Before you fit any line, look at the data. A quick tour of a small house price table shows which columns move together, which ones are skewed, and where the odd values sit.
Do: Open the Scatter tab with Sq Ft on X and Price on Y, and read the dashed trend line and the r value. Then open the Correlation tab and find the row for Price. Last, open the Stats tab and look for amber outliers.Notice: Price rises with square footage along a fairly straight band, so a straight line is a sensible first model. Age moves the other way, with older houses tending to cost less. The table is a small sample with 20 houses and simulated correlations, so treat the numbers as a demonstration.Why: A strong straight-line pattern is exactly what linear regression can use, and a correlation only describes how two columns move together, not why. Checking this first tells you whether a line is worth fitting at all.
Interactive Lab
Add your own data points, adjust the fit by hand or watch the closed-form solution snap to optimal, and see residuals shrink in real time.
LinearRegression, and check how well the model recovered the truth using R-squared.A regression model has R-squared = 0.0 on the test set. What does that mean?
#The Loss Function: Mean Squared Error
Why do we square the errors instead of just averaging the absolute errors?
Squaring serves two purposes: (1) it makes all errors positive without the non-differentiable absolute value, and (2) it penalizes large errors quadratically, making the model focus on reducing big mistakes. A prediction off by 10 contributes 100 to the loss, while a prediction off by 1 contributes only 1. Both reasons matter, so "both" is the correct answer.
#The Closed-Form Solution: Normal Equation
This is beautiful: one matrix equation, computed in one step, gives you the globally optimal weights. No learning rate, no epochs, no hyperparameter tuning.
In the formulas that follow, the bias is folded into the weights: add a column of ones to X, and the last weight is b. Then the model is simply y-hat = Xw. The gradient of the squared error for one feature is derived in Linear Regression: Your First Model, so the derivation below does the same job in matrix form, using the matrix-calculus rules from Vector & Matrix Calculus: Jacobian, Hessian & Backprop Rules.
#The Geometric View: Projection onto the Column Space
The same answer has a picture. The prediction Xw can only be a mix of the columns of X, so the best prediction is the point in that flat sheet nearest to y, and the nearest point is found by dropping a perpendicular. With one column a, the sheet is a line, and the shadow picture below is the whole story: read a as the column of X and b as the target y.
Drag the tip of b and watch the leftover segment stay at a right angle to a exactly when the shadow is the closest point. The derivation below does this for any number of columns and gives the hat matrix H, which turns y into the fitted values.
#How Uncertain Are the Weights?
Fitting the weights is half the story: if the prices had been drawn again with fresh noise, the weights would change. The Gauss-Markov theorem says how good least squares is at this. It is stated here, not proved: if the errors have mean 0, the same variance sigma squared, and are uncorrelated with each other, then among all unbiased estimators of the weights that are linear in y, least squares has the smallest variance. That is why it is called BLUE, the best linear unbiased estimator. Ridge below is biased, so it steps outside the theorem on purpose. The size of the variance is derived next.
#When Does the Closed-Form Break Down?
The normal equation requires inverting the d x d matrix X^T X. This is O(d^3) in computation and O(d^2) in memory. For d = 100 features, this is instant. For d = 1,000,000 features (common in NLP), it is computationally infeasible. In those cases, we fall back to gradient descent, which scales much better with dimensionality.
#Gradient Descent for Linear Regression
When the closed-form is too expensive, we optimize iteratively. The gradient of MSE with respect to weights is:
This gradient is the one derived in the normal-equation derivation above. For a single feature it is also derived in Linear Regression: Your First Model.
- There is exactly one global minimum (no local minima)
- Gradient descent is guaranteed to find it (with appropriate learning rate)
- The loss landscape is the friendliest possible terrain for optimization
#Regularization: Taming Overfitting
When you have many features, the model can assign large weights to fit noise. Regularization adds a penalty for large weights:
#Ridge Regression (L2 Regularization)
Setting the gradient to zero works for ridge too, and the answer is the normal equation with one extra term. The lesson's loss averages over n points, so the closed form carries n times lambda. Libraries such as scikit-learn write the loss without the 1 over n and call the strength alpha, which is the same thing with alpha = n lambda.
Ridge has another virtue that plain least squares lacks: the matrix it inverts always can be inverted.
The price of that stability is a small, deliberate error: ridge pulls the weights toward zero, so on average it misses the true weights.
#Lasso Regression (L1 Regularization)
#Polynomial Regression: Fitting Curves
What if the relationship is not linear? You can fit curves by creating polynomial features:
What happens if you fit a degree-20 polynomial to 25 data points?
A degree-20 polynomial has 21 free parameters for 25 data points. It will almost certainly overfit, producing a wildly oscillating curve that hits most training points but generalizes terribly. This is the bias-variance tradeoff in action: too much flexibility lets the model chase noise.
After fitting linear regression, you plot residuals (y - y_hat) against x and see a clear U-shape. What does that tell you?
#Try It Yourself
Tests: Verify that w converges to approximately 2.0 and b to approximately 3.0. Test with n=1000 for high accuracy. Modify the true function to y=5x-2 and verify the model recovers those coefficients.
#When to Use Linear Regression vs. Alternatives
| Situation | Reach for | Why |
|---|---|---|
| Relationship between features and target looks roughly linear | Linear / Ridge regression | Fast, interpretable, hard to beat |
| Many features, you suspect most are irrelevant | Lasso regression | Drives unhelpful coefficients to exactly zero |
| Strong non-linear patterns visible in residual plot | Polynomial regression or gradient boosting | Linear model will systematically miss the curve |
| Outliers dragging the fit around | Huber / quantile regression | MSE squares errors and gets bullied by outliers |
| You need calibrated probability outputs, not numbers | Logistic regression (next lesson) | Wrong tool here — y must be continuous |
| Hundreds of millions of rows, billions of features | SGD-based linear models (Vowpal Wabbit) | Normal equation is infeasible at this scale |
#Key Takeaways
- Linear regression is the foundation of ML. It predicts a continuous output as a weighted sum of features, and understanding it deeply gives you 80% of what makes all ML work
- MSE penalizes large errors quadratically. Squaring errors makes them all positive, differentiable everywhere, and disproportionately punishes big mistakes over small ones
- The Normal Equation gives exact weights in one step. Unlike iterative methods, it solves for the global optimum directly, but becomes infeasible for datasets with millions of features
- Regularization prevents overfitting. Ridge (L2) shrinks all weights toward zero while Lasso (L1) can push weights to exactly zero, performing automatic feature selection
- Polynomial regression is still linear in the parameters. Creating features like x-squared and x-cubed lets a linear model fit curves, but high-degree polynomials risk severe overfitting
#Quick Check
What does the Normal Equation compute?