← MAIN
LAB // CURVE FITTING

REGRESSION

Drag points and watch the fit snap into place. Each squared error is drawn as a square.
LOSS — ERROR — POINTS — STATUS —

HOW TO USE

The goal is to see how a line or a curve is fitted to points by least squares. Drag the points on the plane and the best fit follows them, and each squared error is drawn as a square whose area is its share of the loss.

Pick a DATA preset and a DEGREE, then choose a METHOD. The exact methods answer at once, and gradient descent creeps toward the same answer when you press RUN.

Turn on HOLD OUT TEST POINTS to fit only the training points and watch the green test squares. Switch to LOGISTIC to classify the points with a probability map.

THE PLANE
Click empty space to add a point, drag to move it, and double-tap or right-click to delete it.
Squares: area is the squared error. Purple dashed: the exact answer. Green: test points.
Pink and cyan: the two classes, and new points take the class chosen in FIT. Yellow ring: a point on the wrong side.
THE LOSS: AREA OF THE SQUARES
Log10 of the objective per descent step. Dashed: exact optimum (linear models).
OVERFITTING: TRAIN VS TEST
Error by polynomial degree, fitted on the training points only
Cyan: train MSE. Green: test MSE on every fourth point.
MODEL
DATA
seed 7
FIT
DEGREE
METHOD
FEATURE DEGREE
CLASS FOR NEW POINTS
DESCENT
STEP 0
More settings
Normal equations vs QR, largest weight gap: —
RIDGE (L2)
STEP SIZE (log10)
STEPS PER FRAME

HOW IT WORKS

A fit is the set of weights that makes the total squared error of a model as small as possible. A weight is one adjustable number in the model. A line or a polynomial has a closed-form answer, which linear algebra computes directly, by the normal equations or by Householder QR. Gradient descent reaches the same answer by repeated steps downhill. Logistic regression replaces the squared error with the log-loss, which has no closed form, so it is fitted by gradient descent.

Seeded data

The points come from presets. A preset is a rule that draws the same points for the same seed, the integer that starts the random generator. The generator is mulberry32, a 32-bit generator whose output is an integer divided by 232, so every uniform value lies in [0, 1)1

Standard normal values, with mean 0 and standard deviation 1, come from the polar method. It draws a point uniformly in the unit disc, rejects points outside it or at the origin, and keeps one coordinate scaled by a radius term2. The JavaScript port uses the same stream, so the same seed gives the same points in both languages3.

A regression preset draws n points with x uniform on [−1, 1], and sets y to a known curve plus Gaussian noise. The page uses 30 points and a noise level of 0.15. The curves are:

f(x) = \begin{cases} 0.6\,x - 0.2 & \text{line} \\ 0.8\,\sin(2\pi x) & \text{noisy-sine} \\ 1.2\,x^2 - 0.6 & \text{quadratic} \end{cases}
45
x_i = -1 + 2u_i, \qquad y_i = f(x_i) + 0.15\,z_i
6

Here u_i is a uniform draw and z_i a standard normal draw for point i. The x value is drawn first, then the noise, point by point. The noise is always drawn, even at level 0, so the x values stay the same when only the noise changes6.

A classification preset gives two labelled classes, 0 and 1, which alternate in index order so both are balanced. Moons are two interleaved half circles. With t = \pi u, class 0 is (\cos t, \sin t) and class 1 is (1 - \cos t, 0.5 - \sin t). Both are rescaled into the page frame and given noise of 0.1 in each coordinate7. Blobs are two Gaussian clouds, centred at (−0.45, −0.35) for class 0 and (0.45, 0.35) for class 1, with a standard deviation of 0.228.

Least squares and the design matrix

The design matrix X has one row per point. Its columns are the powers x^0, x^1, \ldots, x^d of the input, where d is the degree. Column 0 is all ones, so the first weight is the intercept, the value of the curve at x = 0. A polynomial is linear in its weights, so the same algebra fits a curve9. The page's JavaScript port builds the same columns by repeated multiplication10.

J(w) = \frac{1}{n}\Big(\sum_{i=1}^{n} (y_i - x_i \cdot w)^2 + \lambda \sum_{k=1}^{d} w_k^2\Big)
1112

Here n is the number of points the fit uses, y_i is the target of point i, x_i is row i of X, and w is the vector of d + 1 weights. The double sum is the sum of squared errors, the total area of the squares drawn on the plane. The term with \lambda is the ridge penalty, explained below. With \lambda = 0, which is the default, this is plain least squares. Dividing by n gives a mean and does not change where the minimum is11.

A fit with no penalty needs at least as many points as weights. With fewer, the page shows NEEDS d + 1 POINTS OR RIDGE instead of a curve13.

The normal equations

A gradient is the vector of partial derivatives of a function, which points in the direction of steepest increase. At a minimum it is zero. Setting the gradient of J to zero gives a linear system for the weights:

(X^{\top} X + \lambda D)\, w = X^{\top} y, \qquad D = \mathrm{diag}(0, 1, \ldots, 1)
1415

Here X^{\top}X is the Gram matrix of the columns, and X^{\top}y holds the inner product of each column with the targets. D is the penalty matrix, with 0 for the intercept and 1 for every other weight, so the intercept is never penalised.

The code solves this system by Gaussian elimination with partial pivoting. Elimination turns the matrix into an upper-triangular one, one column at a time. Partial pivoting swaps in the row with the largest entry in the current column, so each multiplier f = A[r,k]/A[k,k] has size at most 1, which limits the growth of rounding error. Back substitution then solves the triangular system from the last weight up1617.

Forming X^{\top}X squares the condition number of X, the ratio of its largest to its smallest singular value. A large condition number means small rounding errors in the data change the answer a lot. High-degree powers of x are nearly collinear, so the normal equations lose digits first. On all 30 points of the default data, the largest weight difference between the normal equations and QR is about 4 × 10−15 at degree 3, and about 1.7 × 10−8 at degree 10. The HUD's gap readout shows the same difference for the current fit.

1418
function NORMAL-EQUATIONS(X, y, λ):
    A ← Xᵀ X + λ D                      # D = diag(0, 1, …, 1): no penalty on the intercept
    b ← Xᵀ y
    for k from 0 to p − 1:              # forward elimination
        swap rows k and the row with the largest |A[i, k]|, for i ≥ k, and the entries of b
        for r from k + 1 to p − 1:
            f ← A[r, k] / A[k, k]
            A[r, k..p−1] ← A[r, k..p−1] − f · A[k, k..p−1]
            b[r] ← b[r] − f · b[k]
    for r from p − 1 down to 0:         # back substitution
        w[r] ← (b[r] − A[r, r+1..p−1] · w[r+1..p−1]) / A[r, r]
    return w

The simple version is the core idea: form the system, eliminate, and substitute. The full version writes out the penalty on the diagonal, the tie rule for the pivot, and the check for an exact zero pivot. The Python code raises an error there, because the system is singular. The JavaScript port returns NaN weights there instead. The page checks the QR weights first, so a design that QR rejects is reported as SINGULAR: ADD RIDGE19.

Householder QR

QR decomposition factors X = QR, where Q has orthonormal columns and R is upper-triangular. The code builds the factorisation from Householder reflections. A reflection H = I - 2vv^{\top}/(v^{\top}v) mirrors space across the plane perpendicular to v. Let x be the part of the current column on and below the diagonal. Choosing v = x - \alpha e_1 sends x to \alpha e_1, a multiple of the first unit vector. The sign of \alpha is chosen opposite to x_0, so that v_0 = x_0 - \alpha is a sum of like-signed terms and cannot cancel2021.

H = I - \frac{2}{v^{\top} v}\, v\, v^{\top}, \qquad v = x - \alpha e_1, \qquad \alpha = \begin{cases} -\lVert x \rVert & x_0 \ge 0 \\ \lVert x \rVert & x_0 < 0 \end{cases}
222123

Each reflection is applied to the columns to its right and to y. A reflection is orthogonal, so the residual norm does not change. After p reflections, the top p rows of the transformed matrix are R, and the top p entries of the transformed y are c. The weights solve Rw = c by back substitution24. The page never forms X^{\top}X, so the conditioning is that of X itself.

Ridge enters QR as extra rows. Each extra row \sqrt{\lambda}\, e_k, for k \ge 1, adds \lambda w_k^2 to the squared residual, so minimising the augmented residual is the same as minimising the ridge objective2526:

\min_{w}\ \left\lVert \begin{bmatrix} y \\ 0 \end{bmatrix} - \begin{bmatrix} X \\ \sqrt{\lambda}\, E \end{bmatrix} w \right\rVert^2, \qquad E = \text{the rows } e_1, \ldots, e_d
25

A column that depends on the columns before it leaves a remaining norm that is only rounding noise. Dividing by it would give meaningless weights, so the code refuses it when that norm falls below \mathrm{tol} = \max(m, p)\, \varepsilon\, \max_j \lVert A_{:,j} \rVert, where m is the number of rows, p the number of columns and \varepsilon the machine epsilon. The page then shows SINGULAR: ADD RIDGE2728.

2529
function QR-SOLVE(X, y, λ):
    A ← X;  b ← y
    if λ > 0:                           # ridge: one extra row √λ eₖ for each k ≥ 1
        for k from 1 to p − 1:
            append the row √λ eₖ to A, and 0 to b
    for k from 0 to p − 1:
        x ← A[k.., k]                   # column k, on and below the diagonal
        α ← −‖x‖ if x[0] ≥ 0, else ‖x‖
        v ← x;  v[0] ← v[0] − α
        apply H = I − 2 v vᵀ / (vᵀ v) to A[k.., k..] and to b[k..]
    return BACK-SUBSTITUTE(the top p rows of A, the top p entries of b)

The simple version shows the reflections and the augmented rows. The full version adds the rank tolerance, the skip when a reflector is zero, and the update of each column and of y. The JavaScript port has the same steps, except that it returns NaN weights where the Python code raises an error. The page treats NaN as singular.

Example. A design with columns [1, x] and identical x values in every row has a second column that is a multiple of the first. After the first reflection its remaining norm is zero up to rounding, below the tolerance, so QR refuses the fit. Adding a ridge makes the augmented system full rank, which is why the page suggests a ridge.

Gradient descent

Gradient descent does not solve the system. It starts from zero weights and moves every weight a small step against the gradient. The step size \eta, shown as STEP SIZE (log10) on the page, sets the length of each step. The gradient of the same objective is:

\nabla J(w) = \frac{2}{n}\left(X^{\top}(Xw - y) + \lambda D w\right), \qquad w \leftarrow w - \eta\, \nabla J(w)
303132

Each step records J at the weights it starts from. The recorded list therefore has one entry per step, plus a final entry at the last weights. If J becomes non-finite or exceeds 10^{12}, the run stops and is marked diverged. The limit is a constant in the code3331.

The descent speed depends on the curvature of the loss in each direction. For a quadratic loss with Hessian H = \frac{2}{n}(X^{\top}X + \lambda D), a step size below 2 / \lambda_{\max}(H) shrinks every error direction. On all 30 points of the default data, that threshold is 0.99 at degree 1, 0.86 at degree 3, 0.81 at degree 5 and 0.74 at degree 10. The flattest direction, which lies in the long narrow valley, then moves slowly. That is why a degree-10 fit creeps for hundreds of steps.

On the page, the descent runs STEPS PER FRAME steps in each animation frame, and the weights carry over between frames. They restart from zero only when the model or the degree changes, and they continue when points are moved. Consecutive frames share their boundary loss, so the recorded list holds one entry per step, and the loss chart plots the last 400 of them against their step numbers343536.

3738
function GRADIENT-DESCENT(X, y, η, steps, λ):
    w ← zeros                           # start from zero weights
    repeat steps times:
        g ← (2 / n) (Xᵀ (X w − y) + λ D w)      # gradient of J at w
        w ← w − η g                     # one step downhill
    return w

The simple version is the update rule. The full version keeps the loss list and the divergence test. Both use the old weights for every component of the gradient, so the update is a true simultaneous step. losses[t] is J at the weights that step t starts from, and the last entry is J at the final weights.

Ridge penalty

The ridge penalty \lambda \sum_{k \ge 1} w_k^2, also called L2, shrinks the weights toward zero and smooths the curve. The intercept is not penalised, because lifting the whole curve does not make it wiggle. The penalty changes the normal equations to (X^{\top}X + \lambda D)w = X^{\top}y, the QR system to the augmented one, and the gradient by the term \frac{2}{n}\lambda D w. The RIDGE slider runs from 0 to 2 in steps of 0.01. Zero is plain least squares3940.

Overfitting and the train/test split

With HOLD OUT TEST POINTS on, the fit uses only the training points. Test points are every fourth point, with id 3, 7, 11 and so on. The rule depends only on the point index, so it does not depend on a random draw4142. The error on a set of points is the mean squared error:

\mathrm{MSE}(w) = \frac{1}{N} \sum_{i} (y_i - x_i \cdot w)^2
43

Here N is the number of points in the set. The sum runs over those points only, and the penalty is not included. Overfitting means the fit is much better on the points it was fitted to than on new points. The page sweeps the degree from 1 to 10, fits each degree on the training points, and measures the MSE on both sets44. The default data, with 23 training points and 7 test points, gives:

DegreeTrain MSETest MSE
10.33680.2796
30.28700.2868
50.04720.0852
70.01410.0718
100.01290.0917

Train MSE falls as the degree rises, from 0.3368 at degree 1 to 0.0129 at degree 10. Test MSE is lowest at degree 7, at 0.0718, and climbs to 0.0917 at degree 10, as the curve starts to follow the noise in the training points. The test set has only 7 points, so the exact location of the minimum is uncertain.

Ridge is a second control. At degree 10 on the same split, a small penalty helps and a large one hurts: λ = 0.01 lowers the test MSE from 0.0917 to 0.0837, while λ = 0.05 raises it to 0.1311, and λ = 0.5 gives train 0.2899 and test 0.2531. A penalty that is too large underfits, so the train error rises with it. Choosing λ and the degree on held-out data is how the best model is picked.

Logistic regression and log-loss

For a 0/1 label, the model predicts a probability. The logistic function, also called the sigmoid, maps any real score into the interval (0, 1). The score is the linear combination z = x \cdot w:

p_i = \sigma(x_i \cdot w), \qquad \sigma(z) = \frac{1}{1 + e^{-z}}
4546

Here p_i is the predicted probability that point i has label 1. The code evaluates the sigmoid on the side where e^{-z} cannot overflow. The Python version also clips z to ±500, which changes nothing visible, because beyond that range the sigmoid is 0 or 1 to machine precision.

The log-loss of one point is -[y \log p + (1 - y)\log(1 - p)]. It is small when the model gives high probability to the true label, and it grows without limit when the model is confidently wrong. The code computes it as \operatorname{softplus}(z) - yz, where \operatorname{softplus}(z) = \log(1 + e^{z}). This form never takes the logarithm of a probability that has rounded to 0 or 14748.

J(w) = \frac{1}{n}\Big(\sum_{i=1}^{n} \big(\operatorname{softplus}(x_i \cdot w) - y_i\, x_i \cdot w\big) + \lambda \sum_{k=1}^{d} w_k^2\Big), \qquad \nabla J(w) = \frac{1}{n}\left(X^{\top}(p - y) + 2\lambda D w\right)
474950

Here p is the vector of probabilities and y the vector of labels. The objective averages the log-loss over the n points and adds the same ridge penalty as the regression objective. The gradient has the same shape as the least-squares gradient, with the residual p - y in place of Xw - y. The penalty's derivative is 2\lambda w, which explains the factor 24932.

The decision boundary is where p = 0.5, which is where x \cdot w = 0. For degree 1 it is a straight line, and for higher degrees a curve. The features are the monomials x_1^i x_2^j with i + j \le d, so there are (d + 1)(d + 2)/2 weights. That is 3, 6, 10 and 15 for degrees 1 to 45152. The accuracy readout in the header is the fraction of points whose predicted side of 0.5 matches the label:

\mathrm{acc} = \frac{1}{n} \sum_{i=1}^{n} \mathbf{1}\big[(p_i \ge 0.5) = (y_i > 0.5)\big]
5354

Here \mathbf{1}[\cdot] is 1 when the condition holds and 0 otherwise. Accuracy is a count of correct sides, so it ignores how confident each prediction is. The log-loss does not, which is why the two are read together.

Fitting the classifier

The classifier is fitted by the same descent as the regression, on every point, starting from zero weights. Only the residual and the constants change. The pseudocode below shows the update with the log-loss gradient.

5556
function FIT-LOGISTIC(X, labels, η, steps, λ):
    w ← zeros
    repeat steps times:
        p ← σ(X w)                      # probability of label 1, for each point
        g ← (1 / n) (Xᵀ (p − labels) + 2 λ D w)
        w ← w − η g
    return w

The simple version is the update: a sigmoid, a residual, and a step. The full version adds the log-loss bookkeeping, the divergence test, and the stable form of \operatorname{softplus}. The JavaScript port evaluates the sigmoid on the side where the exponential is small, and the log-loss in the same softplus form57.

Example. On the default moons data, 60 points with seed 7, the page's accuracy is the same, 95.0%, at every feature degree from 1 to 4 when the descent runs 2,000 steps with step size 0.5. The log-loss still falls, from 0.1566 at degree 1 to 0.1092 at degree 4. The blobs preset reaches 100% at every degree, with a log-loss of about 0.015 after the same run. With the page's default step size of 0.1 and 500 steps, degree 1 reaches a log-loss of 0.1747 on the same data5859.

Step size and divergence

The table gives the objective J after 500 steps from zero weights, on the default regression data, with no penalty. The last row is the exact least-squares value, from QR, for comparison.

Step size ηDegree 1Degree 3Degree 5Degree 10
0.10.320850.284130.275140.23878
0.50.320850.283460.199470.12772
17373, still growingdivergeddivergeddiverged
exact0.320850.283460.048980.01979

At step size 0.1 and 0.5 every degree stays finite, but the high degrees are still far from the exact value after 500 steps. At step size 1, degree 1 stays finite but grows, and reaches about 7,400 at step 500. Degrees 3, 5 and 10 blow past the limit and stop early, within 60 steps. The threshold above, 0.74 at degree 10 and 0.86 at degree 3, explains the boundary between the stable and diverging rows60.

Parameters and their defaults

ParameterDefaultRangeWhy this default
Degree (linear / poly)31 to 10Degree 3 bends enough to follow the sine curve. On the default data the test error is lowest at degree 7.
MethodQRQR, normal equations, descentExact and numerically stable. The normal equations give the same answer up to rounding, and lose digits at high degree.
Hold out test pointsoffon / offWith it off, every square counts toward the loss. With it on, the fit uses three quarters of the points, and the green squares are not used for the fit.
Ridge λ00 to 2Zero is plain least squares, so overfitting is visible. A small value, 0.01, lowers the test error at degree 10 on the held-out split.
Step size η (log10)0.10.001 to 1Stable from 0.1 to 0.5 on the default data. At 1, degrees 3, 5 and 10 diverge.
Steps per frame41 to 40At a typical 60 frames a second, 4 steps per frame is about 240 steps a second.
Datanoisy sine, 30 points, noise 0.15line, noisy sine, quadraticPoints on a known curve with noise 0.15. The line gives the simplest fit.
Logistic feature degree11 to 4The default moons data reaches 95% accuracy at degree 1 already. Higher degrees lower the log-loss.
Class for new pointscyan (1)pink (0) or cyan (1)The label given to each point added in logistic mode.

How these were chosen: The page's defaults match the CLI defaults, so python -m regression fit starts from the same data and degree61. The tables above were measured from this code on the default data.

Try this

Set degree 10 and click HOLD OUT TEST POINTS. The curve threads the training points, and the green test squares are the ones to watch. Then set RIDGE to 0.3 and compare. For the descent, choose gradient descent in METHOD, keep the step size at about 0.3, and watch the purple dashed target stay far ahead of the curve. At step size 1 the run diverges.