Machine Learning

Linear Regression & Least Squares

Linear regression fits a line or hyperplane by making residuals as small as possible in squared-error geometry.

status: publishedimportance: criticaldifficulty 2/5math: undergraduateread: 16mlive demo

Concept Structure

Linear Regression & Least Squares

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
1next concepts
3related links

Learning map

Linear Regression & Least Squares
BeforeDot ProductNow4/4 sections readyTryManipulate one control and predict the visible change.NextLogistic Regression

Object flow

4/4 sections readyAsk about thisResearch room
ConceptLinear Regression & Least SquaresMachine Learning
2 sources attachedLocal snapshot ready
concept:machine-learning/linear-regression-least-squares

Conceptual Bridge

What should feel connected as you move through this page.

Carry inDot Product

Bring the mental model from Dot Product; this page will reuse it instead of restarting from zero.

Work hereLinear Regression & Least Squares

Linear regression fits a line or hyperplane by making residuals as small as possible in squared-error geometry.

Carry outLogistic Regression

The next edge should feel earned: use the demo prediction here before following Logistic Regression.

Test the linkManipulate one control and predict the visible change.Then continue to Logistic Regression
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

You are here because many later ideas - regularization, bias and variance, PCA, calibration, neural losses, and even preference modeling - become easier once "fit a simple model to data" is completely clear.

Before this, know dot products and basic derivatives. By the end, you should be able to explain what a residual is, compute a least-squares fit, and predict how a line should move when residuals are mostly positive or negative.

Linear regression asks for the simplest supervised-learning promise: given inputs xx, predict a numeric target yy with a linear rule. In one dimension, the model is a line. In many dimensions, it is a hyperplane.

The learner's first object is not the line. It is the residual:

ri=yiy^i.r_i = y_i - \hat y_i.

A residual is the signed miss for one example. If the residual is positive, the model predicted too low. If it is negative, the model predicted too high. Least squares fits the model by making the vector of residuals short under squared length.

The square matters. Squaring makes large misses costly, removes sign cancellation, and gives a smooth objective with a clean derivative. The price is sensitivity to outliers: one extreme point can pull the line hard.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

For nn training examples with dd features, collect the inputs in a design matrix XRn×dX\in\mathbb R^{n\times d} and targets in yRny\in\mathbb R^n. A linear model uses coefficients wRdw\in\mathbb R^d and predicts

y^=Xw.\hat y = Xw.

The residual vector is

r=yXw.r = y - Xw.

Least squares minimizes the residual sum of squares:

J(w)=12yXw22.J(w)=\frac12\lVert y-Xw\rVert_2^2.

The factor 12\frac12 only cleans up the derivative. If you instead average over examples, the gradient below is scaled by 1n\frac1n; the minimizer is the same, but the step size in gradient descent changes. Expanding the unaveraged gradient gives

wJ(w)=XT(Xwy).\nabla_w J(w)=X^{\mathsf T}(Xw-y).

At an interior optimum, the gradient is zero:

XT(Xwy)=0.X^{\mathsf T}(Xw-y)=0.

So the fitted residual vector is orthogonal to every column of XX:

XTr=0.X^{\mathsf T}r = 0.

That is the geometric heart of least squares. The prediction Xw^X\hat w is the closest point to yy inside the column space of XX. The residual is orthogonal to the feature columns, not magically orthogonal to the target vector, every data point in a scatterplot, or every visual segment you draw.

When XTXX^{\mathsf T}X is invertible, the normal equation has the closed-form solution

w^=(XTX)1XTy.\hat w=(X^{\mathsf T}X)^{-1}X^{\mathsf T}y.

If XTXX^{\mathsf T}X is singular or badly conditioned, the formula may not exist or may be numerically fragile. Rank-deficient systems can have many minimizers; the pseudoinverse gives the minimum-norm solution. Practical code usually uses a least-squares solver, QR decomposition, SVD, or regularization rather than explicitly forming the inverse.

For a model with an intercept in one dimension, use columns [1,xi][1,x_i], so w=[b,m]Tw=[b,m]^{\mathsf T} and y^i=b+mxi\hat y_i=b+mx_i.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

# Fit y_hat = b + m x by least squares.
# Shapes: X is (n, 2), y is (n,), w is (2,).
x = np.array([-2.0, -1.0, 0.0, 1.0, 2.0, 3.0])
y = np.array([-1.6, -0.4, 0.5, 1.4, 2.3, 3.9])

X = np.column_stack([np.ones_like(x), x])
w, *_ = np.linalg.lstsq(X, y, rcond=None)
y_hat = X @ w
residuals = y - y_hat

normal_equation_residual = X.T @ residuals
mse = np.mean(residuals ** 2)

print("intercept b:", round(w[0], 3))
print("slope m:", round(w[1], 3))
print("predictions:", np.round(y_hat, 3))
print("residuals:", np.round(residuals, 3))
print("X^T residuals:", np.round(normal_equation_residual, 10))
print("MSE:", round(mse, 4))

The code mirrors the math: X @ w creates predictions, y - y_hat creates residuals, and X.T @ residuals is approximately zero at the least-squares solution.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Use the sliders to place a candidate line before revealing the least-squares fit. First predict which single move would reduce squared error most: raise the intercept, lower the intercept, increase the slope, or decrease the slope.

The reveal shows residuals as vertical segments, the fitted line, the current loss, and the normal-equation diagnostic XTrX^{\mathsf T}r. If the residuals are mostly above the line, the intercept wants to rise. If residuals grow with xx, the slope wants to increase. The demo's goal is not to memorize a formula; it is to feel residual geometry.

Live Concept Demo

Explore Linear Regression & Least Squares

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 2/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Linear Regression & Least Squares should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

Linear regression fits a line or hyperplane by making residuals as small as possible in squared-error geometry.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Linear Regression & Least Squares should make visible.

Visual Inquiry

Make the image answer a mathematical question

Linear regression fits a line or hyperplane by making residuals as small as possible in squared-error geometry.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Linear Regression & Least Squares easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2023CS229 Lecture Notes: Linear RegressionStanford CS229

Curriculum source for least-squares linear regression and normal-equation geometry.

Open source
bookAn Introduction to Statistical LearningJames, Witten, Hastie, Tibshirani, and Taylor

Curriculum source for regression as prediction, residuals, and evaluation.

Open source

Claim Review

Linear regression fits a line or hyperplane by making residuals as small as possible in squared-error geometry.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources2 references

cs229-linear-regression, isl-linear-regression

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedLeast squares chooses linear coefficients that minimize the sum of squared residuals between observed targets and model predictions.Claim metadata: source checked

CS229 directly supports the central least-squares objective, matrix-gradient derivation, normal equations, and Gaussian-MLE interpretation used on the page.

Sources: CS229 Lecture Notes: Linear RegressionSupports ordinary least-squares mechanics, not robustness, numerical superiority of the inverse formula, or literal visual orthogonality of residual segments in the scatterplot.A bounded review summary is present; still check caveats and exact source scope.

Checked CS229 sections 1.1-1.3: least-squares cost, matrix form, gradient X^T X theta - X^T y, normal equations, and Gaussian-MLE equivalence. Prior GPT Pro blockers were rank, scaling, intercept, and projection scope; the page now states those caveats.

Reviewer: codex+gpt-pro-prior; reviewed 2026-06-28

Practice Loop

Try the idea before it explains itself

Linear regression fits a line or hyperplane by making residuals as small as possible in squared-error geometry.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Linear Regression & Least Squares.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Object research drawerClose
ConceptLinear Regression & Least SquaresMachine Learning

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptMachine Learning

Linear Regression & Least Squares

Anchored question

What is the smallest example that makes Linear Regression & Least Squares click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:machine-learning/linear-regression-least-squares.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: cs229-linear-regression, isl-linear-regression
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Linear Regression & Least Squares Object key: concept:machine-learning/linear-regression-least-squares Context: Machine Learning Anchor id: concept/concept-notebook/machine-learning/linear-regression-least-squares Open question: What is the smallest example that makes Linear Regression & Least Squares click without losing the math? Evidence to inspect: - Source ids to inspect: cs229-linear-regression, isl-linear-regression - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

Open source object
concept/concept-notebook/machine-learning/linear-regression-least-squares concept:machine-learning/linear-regression-least-squares