← capítulo

Linear regression

Fit a line — a plane, really — through the data and read predictions off it.

The workhorse baseline for regression: readable coefficients, exact solution, the model everything fancier has to beat.

Two ways to the same line

The idea

Least squares: pick the line where the squared vertical gaps add up to the smallest total.

Watch it fit

Every frame is one gradient step. The line rotates into place; the MSE falls off a cliff, then flattens.

After 60 steps, gradient descent matches the closed form: slope 3.00, intercept 5.10.

The math

The model, per row and stacked:

y^i=wxi+b,y^=Xw+b\hat{y}_i = w^{\top} x_i + b, \qquad \hat{y} = Xw + b

The thing we minimize — mean squared error:

L(w,b)=1ni(y^iyi)2L(w, b) = \frac{1}{n} \sum_{i} \left( \hat{y}_i - y_i \right)^2

A convex bowl. Solve it directly, or descend it. Same bottom.

Scratch vs. library

Normal equation, gradient descent, and sklearn on California housing — identical.

Test R² 0.585, MSE 0.528 — the same for all three. There's only one least-squares line.

The residuals tell the truth

The fan shape is heteroscedasticity; the diagonal streak is the $500k price cap.

Takeaways