What’s one thing you learned? What’s still confusing?
Regularization: L1, L2, and ElasticNet
Prevent overfitting with Ridge, Lasso, and ElasticNet. Geometric intuition for sparsity.
Logistic Regression
Binary classification with the sigmoid function.
Discriminant Analysis & Naive Bayes
Generative classifiers in the Bayes family — Naive Bayes plus LDA and QDA.
Interactive Labs for This Track
Linear Regression
Predict house prices based on square footage — drag points and watch the best-fit line adjust
Gradient Descent Explorer
You're blindfolded on a hilly field trying to find the lowest valley — feel the slope and take steps downhill
Decision Boundary Explorer
You're a bank deciding who gets a loan — draw the line that separates approved from denied
Ask questions, share insights
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.
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!
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:
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,667price ≈ 250 · sqft + 41,667. Reading the coefficients:w = 250 -- each additional square foot adds $250 to the price.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.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.
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.
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.
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.
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?
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.
This is beautiful: one matrix equation, computed in one step, gives you the globally optimal weights. No learning rate, no epochs, no hyperparameter tuning.
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.
When the closed-form is too expensive, we optimize iteratively. The gradient of MSE with respect to weights is:
When you have many features, the model can assign large weights to fit noise. Regularization adds a penalty for large weights:
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?
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.
| 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) |
What does the Normal Equation compute?
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.
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.
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.
| Normal equation is infeasible at this scale |