Bring the mental model from Dot Product; this page will reuse it instead of restarting from zero.
Machine Learning
Linear Regression & Least Squares
Linear regression fits a line or hyperplane by making residuals as small as possible in squared-error geometry.
Concept Structure
Linear Regression & Least Squares
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learning map
Linear Regression & Least SquaresConceptual Bridge
What should feel connected as you move through this page.
Linear regression fits a line or hyperplane by making residuals as small as possible in squared-error geometry.
The next edge should feel earned: use the demo prediction here before following Logistic Regression.
01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
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 , predict a numeric target 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:
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
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
For training examples with features, collect the inputs in a design matrix and targets in . A linear model uses coefficients and predicts
The residual vector is
Least squares minimizes the residual sum of squares:
The factor only cleans up the derivative. If you instead average over examples, the gradient below is scaled by ; the minimizer is the same, but the step size in gradient descent changes. Expanding the unaveraged gradient gives
At an interior optimum, the gradient is zero:
So the fitted residual vector is orthogonal to every column of :
That is the geometric heart of least squares. The prediction is the closest point to inside the column space of . 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 is invertible, the normal equation has the closed-form solution
If 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 , so and .
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
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
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
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 . If the residuals are mostly above the line, the intercept wants to rise. If residuals grow with , 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.
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.
Start with the picture, metaphor, or geometric mechanism.
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.
Which visible object should carry the first intuition?
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.
Curriculum source for least-squares linear regression and normal-equation geometry.
Open sourceCurriculum source for regression as prediction, residuals, and evaluation.
Open sourceClaim Review
Linear regression fits a line or hyperplane by making residuals as small as possible in squared-error geometry.
Claims without a substantive review badge still need exact source-support review.
cs229-linear-regression, isl-linear-regression
Use equation, code, and demo objects to check whether the source support is operational.
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-28Practice 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.
Before touching the demo, predict one visible change that should happen in Linear Regression & Least Squares.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
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.Open the draft below to save one note and next action in this browser.
Linear Regression & Least Squares
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
This draft stays locally in this browser for concept:machine-learning/linear-regression-least-squares.
- 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
- 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
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.
concept/concept-notebook/machine-learning/linear-regression-least-squares
concept:machine-learning/linear-regression-least-squares