Aug 20, 2026SeminarMachine learning
From least squares to gradient descent
A seminar write-up that builds the first models of machine learning from their mathematics — least squares, likelihood, the logistic loss and the step that minimises it.
By Author
Most of what a first machine-learning course calls "training" is one idea used over and over: write down how wrong a model is as a function of its parameters, then move the parameters downhill. This note builds that idea from the ground up, starting with the oldest model there is — a straight line fitted by least squares — and ending with the update rule that trains networks with billions of weights.
1. The setting
We are given examples. Each example has a feature vector and a target . Stack the features as rows of a design matrix and the targets as a column:
A model is a function with parameters , and a loss measures one mistake. Training means choosing
Everything below is a particular choice of and , and a way of finding the minimum.
2. Linear regression and the normal equations
The linear model predicts with . (A constant column of ones in gives it an intercept.) With the squared loss, the total error is
This function is a quadratic bowl in , so its minimum is where the gradient vanishes. The derivation takes four lines:
- Expand the product: .
- Differentiate term by term, using and for symmetric : .
- Set the gradient to zero. This gives the normal equations: .
- If is invertible — which holds exactly when the columns of are linearly independent — the solution is unique:
The name "normal" is geometric. Rewrite the equations as : the residual is orthogonal, or normal, to every column of . The fitted values are the orthogonal projection of onto the column space of , and is the matrix that performs that projection.
In practice nobody forms . Solving the system with a QR or Cholesky factorisation is faster and far more stable, because inverting squares the condition number of the problem.
3. Why squares? Maximum likelihood
The squared loss can look arbitrary. It is not: it falls out of a probabilistic assumption about the noise. Suppose each target is the model's prediction plus independent Gaussian noise,
Then each has density , and the likelihood of the whole data set is the product over . Taking the logarithm turns the product into a sum:
The first term does not depend on , and is a positive constant, so maximising the likelihood is the same as minimising the sum of squared errors. Least squares is the maximum-likelihood estimate under Gaussian noise. Change the noise model and the loss changes with it: Laplace noise gives the absolute error , which is less sensitive to outliers.
4. Classification: logistic regression
For a binary target a straight line is the wrong output — we want a probability. Logistic regression passes the linear score through the sigmoid
The sigmoid maps to , and it has a derivative that is pleasant to work with:
Treat each label as a Bernoulli draw with probability . The likelihood is , and its negative logarithm, averaged over the data, is the cross-entropy loss
Differentiating with the chain rule and the identity for , almost everything cancels:
This is the same shape as the least-squares gradient, , up to a constant: prediction minus target, weighted by the input. Unlike least squares, though, setting it to zero has no closed-form solution, because depends on through the sigmoid. We need an iterative method.
5. Gradient descent
The gradient points in the direction of steepest increase. Stepping a little way against it lowers the loss:
where is the learning rate. Why does this work, and how large may be? Suppose the gradient is Lipschitz with constant : it cannot change faster than times the distance moved. A first-order Taylor bound then gives, for one step,
As long as , the bracket is positive and every step decreases the loss unless the gradient is already zero. For convex losses such as least squares and logistic regression, that is enough to reach the global minimum; with the error after steps shrinks like , and like a geometric sequence when the loss is strongly convex.
The table summarises what the learning rate does in practice.
| Learning rate | Behaviour | What you see in the loss curve |
|---|---|---|
| Far too small | Safe but slow | A long, almost flat decline |
| About | Steady descent | A smooth curve that levels off |
| Near | Overshoots, zig-zags | A decreasing but jagged curve |
| Above | Diverges | The loss grows without bound |
On large data sets the full gradient is expensive, so we estimate it from a random mini-batch of examples, . That is stochastic gradient descent. The estimate is noisy but unbiased, and with a learning rate that decays over time it still converges.
The whole of logistic regression by gradient descent fits in a few lines:
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def fit_logistic(X, y, lr=0.1, steps=2000, lam=0.0):
n, d = X.shape
w = np.zeros(d)
for _ in range(steps):
p = sigmoid(X @ w)
grad = X.T @ (p - y) / n + lam * w # cross-entropy gradient + L2 term
w -= lr * grad
return w
6. Regularisation: a prior in disguise
When features are many or strongly correlated, is close to singular and the least-squares solution becomes huge and unstable. Ridge regression adds a penalty on the size of the weights:
For any the matrix is positive definite, so the solution always exists and is stable.
The penalty has the same Bayesian reading as the squared loss. Put a Gaussian prior on the weights, , and ask for the most probable weights after seeing the data — the maximum a posteriori (MAP) estimate. By Bayes' rule, the log-posterior is the log-likelihood plus the log-prior:
Maximising this is exactly ridge regression with . A strong belief that the weights are small — a small — means a large penalty. A Laplace prior gives the penalty instead — the lasso — which drives some weights to exactly zero.
7. Bias and variance
Why accept a penalty that makes the fit to the training data worse? Because the training error is not what we care about. Suppose the true relationship is with noise variance , and let be a model trained on a random data set. At a fixed point , the expected squared error over data sets decomposes as
A flexible model with no penalty has low bias but high variance: it chases the noise in each particular sample. Increasing adds a little bias and removes a lot of variance, and somewhere in between the total error is smallest. Finding that point is what a validation set is for.
8. What carries over
Every model in this note followed the same recipe:
- choose a model and a noise assumption;
- turn the assumption into a loss through the negative log-likelihood;
- add a prior as a penalty if the data alone cannot pin the parameters down;
- minimise with gradient descent, taking steps no larger than the curvature allows.
A neural network changes only the first line — becomes a composition of many layers — and backpropagation is nothing more than the chain rule we used for the sigmoid, applied layer by layer. The mathematics of the straight line is the mathematics of the whole field.