Slides · ML foundations
Linear models, loss functions and gradient descent
1 / 28
Linear models, loss and gradient descent
A function, a loss and an optimizer: the three pieces behind almost every model, shown on the two simplest ones.
Concept
Why this is worth 40 minutes
- Much debugging time is optimisation time: the loss is flat, NaN, or oscillating.
- The gradient of cross-entropy, prediction minus target, is the first step of backpropagation.
- Logistic and linear regression are the baselines a heavier model has to beat.
Four things you will be able to do:
- Derive the gradient (p - y) x and say why log loss pairs with a sigmoid.
- Solve linear regression two ways and know when each fits.
- Choose a loss by what it penalises.
- Tune and debug gradient descent: learning rate, momentum, Adam, scaling.
Compare
Same loop, different pieces
| Task | Output | Typical loss | Why |
|---|---|---|---|
| Regression | Linear | Squared error | Likelihood under Gaussian noise |
| Regression with outliers | Linear | Absolute or Huber | Errors grow linearly |
| Binary classes | Sigmoid | Log loss | Bernoulli likelihood |
| Multiclass | Softmax | Cross-entropy | Categorical likelihood |
| Margin classifier | Raw score | Hinge | Only boundary points matter |
- Change one piece and you have a different algorithm.
Math
Linear regression: the normal equation
J(w)=n1∥Xw−y∥2,∇wJ=n2X⊤(Xw−y)=0X⊤Xw=X⊤y⇒w=(X⊤X)−1X⊤y- The middle form says the residual is orthogonal to every column of X.
- Squared error is the likelihood-maximising loss if the noise is Gaussian. That is an assumption, and it is why outliers hurt.
- With a column of ones for the intercept, the residuals sum to zero.
Worked example
Worked example: three points, exact
Fit y=b+wx to x=[1,2,3], y=[2,4,5].
| Quantity | Value |
|---|---|
| X⊤X | (36614) |
| X⊤y | (11, 25) |
| Determinant | 6 |
| b, w | 2/3 and 3/2 |
| Residuals | -1/6, 1/3, -1/6 |
| MSE | 1/18 |
- Residuals sum to 0, and ∑xiri=0: the orthogonality condition, checked.
Compare
Closed form or gradient descent?
| Normal equation | Gradient descent | |
|---|---|---|
| Cost | About nd2 to form, d3 to solve | A pass over a batch per step |
| Learning rate | None | Must be tuned |
| Collinear columns | Nearly singular, unstable coefficients | Converges slowly along the flat direction; ridge helps both |
| No closed form (logistic, neural nets) | Not available | The general tool |
| Streaming data | Needs all data | Mini-batches |
- Libraries use a decomposition of X, not a literal inverse.
- Unstable coefficients with stable predictions is the signature of collinearity.
Sources[2] Linear Models (ridge regression and lasso)[1] Dive into Deep Learning, Linear Regression (analytic solution, minibatch SGD, squared loss and Gaussian noise)
Check yourself
Check: which solver?
A model has 200 features and 100,000 rows, and the data fits in memory. Would you reach for gradient descent?
Answer
Probably not. Forming a 200 by 200 matrix costs about nd2=4×109 operations and solving it is cheap, so the closed form (or a library’s decomposition) is simple and exact. Gradient descent earns its place with very many features, streaming data, or models with no closed form.
Diagram
Logistic regression in one picture
Math
Deriving (p - y) x
ℓ=−[ylogp+(1−y)log(1−p)],σ′(z)=p(1−p)∂z∂ℓ=(−py+1−p1−y)p(1−p)=−y(1−p)+(1−y)p=p−y- Then ∇wℓ=(p−y)x and ∂ℓ/∂b=p−y.
- The sigmoid’s p(1−p) cancels the denominators of the logs.
- Softmax with cross-entropy gives (softmax - one-hot) on the logits: the same form.
Worked example
Worked example: one step by hand
One example x=[1,2], y=1, w=[0,0], b=0, learning rate 0.1.
| Quantity | Value |
|---|---|
| Score and probability | z=0, p=0.5 |
| Error p−y | -0.5 |
| Gradient | [−0.5,−1] and −0.5 for the bias |
| New w, b | [0.05, 0.10] and 0.05 |
| New score, probability | 0.30 and 0.574 |
| Log loss | 0.693 to 0.554 |
- With y=0 every sign flips and the loss falls by the same amount.
Worked example
Why not squared error on a sigmoid?
Gradient with respect to the score z, label y=1:
| z | p | Cross-entropy | Squared error |
|---|---|---|---|
| -6 | 0.00247 | -0.99753 | -0.00246 |
| -2 | 0.1192 | -0.8808 | -0.09248 |
| 0 | 0.5 | -0.5 | -0.125 |
| 2 | 0.8808 | -0.1192 | -0.01252 |
- Squared error keeps the factor p(1−p), so it goes quiet when the model is confidently wrong.
- Its curve also bends the wrong way for negative scores, so it is not convex. Log loss is convex (unique when strictly convex, e.g. with an L2 penalty).
Concept
Reading weights, and the separable trap
- Linear in log-odds: a one-unit rise in xj multiplies the odds by ewj (about 2.01 for wj=0.7).
- Compare weights only on comparable scales. Do not read them causally.
- If a line separates the classes, the loss approaches 0 as weights grow and there is no finite minimiser. In the lesson: 3.376 after 100 steps, 10.127 after 100,000.
- An L2 penalty of 0.1 stops it at 1.458.
Check yourself
Check: sign and size
A positive example gets p = 0.99. How big is the gradient on its weights compared with a positive example at p = 0.2, and what does that say about training?
Answer
The error is p - y = -0.01 versus -0.8, so for the same input x the confident, correct example moves the weights 80 times less than the badly wrong one. Log loss concentrates learning on the mistakes.
Worked example
Squared versus absolute error
- A constant: squared error picks the mean, absolute error the median. For [1,2,3,4,100] that is 22 against 3.
- A line: x=1..6, y=2x except the last label 12 became 40.
| Fit | Result | Prediction at x = 1 |
|---|---|---|
| Least squares | y=−9.333+6x | -3.333 |
| Least absolute deviations | y=2x | 2 |
- Huber: quadratic for small errors, linear for large, so outliers get a lesser weight without being ignored. With threshold 1, an error of 10 costs 9.5 instead of 50.
- Look at why the outliers exist before you choose a robust loss.
Compare
Classification losses by margin
| Margin m=yf(x) | Hinge | Log loss | Squared (1−m)2 |
|---|---|---|---|
| -2 | 3 | 2.127 | 9 |
| -1 | 2 | 1.313 | 4 |
| 0 | 1 | 0.693 | 1 |
| 1 | 0 | 0.313 | 0 |
| 2 | 0 | 0.127 | 1 |
- Hinge is exactly 0 past margin 1: well-classified points drop out.
- Log loss keeps pushing and gives probabilities.
- Squared loss on the margin punishes confident correct answers: wrong shape.
Source[4] Stochastic Gradient Descent (scikit-learn user guide)
Diagram
Where each loss stops caring
Check yourself
Check: pick the loss
Sensor data has a few readings that are sensor glitches, thousands of times too large. Which loss, and what do you do besides?
Answer
Huber or absolute error limits the damage, but the glitches are a data problem: filter or flag them and count them, and keep a clean validation set so the loss choice is judged on real readings.
Concept
Gradient descent and the learning rate
w←w−η∇wJ(w)On J(w)=w2 each step multiplies w by 1−2η.
| Learning rate | Behaviour from w=1 |
|---|---|
| 0.1 | 0.8, 0.64, 0.512: converges slowly |
| 0.5 | Lands on 0 in one step |
| 1.0 | -1, 1, -1, 1: oscillates forever |
| 1.1 | -1.2, 1.44, -1.728: diverges |
- Converges only if η<2/h for curvature h. Plot loss against steps.
Concept
Batch size
- Full batch: exact gradient, one pass per step.
- One row (SGD): cheap and noisy.
- Mini-batch: the default; the textbook cites 32 to 256.
- Noisier steps need a smaller or decaying rate. scikit-learn’s SGD estimators default to decaying schedules.
Sources[1] Dive into Deep Learning, Linear Regression (analytic solution, minibatch SGD, squared loss and Gaussian noise)[4] Stochastic Gradient Descent (scikit-learn user guide)
Math
Momentum and Adam
Momentum: v←βv+g,w←w−ηv
Adam, per parameter:
mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,w←w−ηv^t+ϵm^t- Momentum: agreeing gradients add up, zigzags cancel.
- Adam: a step size per parameter; first step is about η whatever the gradient size. Widely used for neural networks (common practice).
- PyTorch defaults: learning rate 0.001, betas 0.9 and 0.999, epsilon 1e-8.
- Libraries differ on where the learning rate enters the momentum update, so settings may not transfer.
Sources[5] Dive into Deep Learning, Momentum (ill-conditioned problems and the leaky average of gradients)[6] torch.optim.Adam[7] torch.optim.SGD[8] Adam: A Method for Stochastic Optimization
Worked example
Honest numbers: a narrow valley
f=0.1w12+2w22 from (5,3). Steps until f<10−6, best setting on a grid:
| Method | Best setting | Steps |
|---|---|---|
| Gradient descent | η=0.45 | 79 |
| Momentum | η=0.5, β=0.5 | 23 |
| Adam | η=0.7 | 114 |
- At η=0.5 plain descent oscillates forever (steep factor 1−0.5⋅4=−1, exactly the limit 2/4); at 0.51 it diverges.
- Momentum with β=0.9, a common choice, took 122 to 290 steps: slower than tuned plain descent. Tune β with η.
- Only Adam’s learning rate was searched (betas fixed at 0.9 and 0.999), so 114 is not tuned Adam. It did not beat tuned descent on this clean problem; its value is robustness to scale and noise.
Source[5] Dive into Deep Learning, Momentum (ill-conditioned problems and the leaky average of gradients)
Worked example
Feature scaling, measured
200 rows; feature 1 in [0, 1], feature 2 in [0, 100]. Best fixed rate, steps to be within 1e-6 of the minimum, median of 20 datasets:
| Features | Condition number | Steps |
|---|---|---|
| Raw | 23,200 | 96,865 |
| Centred | 9,760 | 36,206.5 |
| Standardised | 1.12 | 3 |
- Scale decides the steepest direction, and that decides the usable learning rate.
- Needed for gradient descent and penalties; not for trees. Fit the scaler on training data only.
Sources[4] Stochastic Gradient Descent (scikit-learn user guide)[9] Cross-validation: evaluating estimator performance
Diagram
When the loss will not go down
Check yourself
Check: read the curve
A run’s loss alternates 0.40, 0.90, 0.40, 0.90 with a constant learning rate. What does that suggest and what do you try?
Answer
The step is overshooting the valley and bouncing between two sides, the picture of a rate near the stability limit. Lower the rate (or decay it) and standardise the inputs, then check the curve again.
Code
Logistic regression in a few lines
Python
import math
def sigmoid(z):
if z >= 0:
return 1 / (1 + math.exp(-z))
e = math.exp(z)
return e / (1 + e)
def step(X, y, w, b, lr):
n = len(X)
gw, gb = [0.0] * len(w), 0.0
for xi, yi in zip(X, y):
err = sigmoid(sum(a * c for a, c in zip(w, xi)) + b) - yi
gw = [g + err * c for g, c in zip(gw, xi)]
gb += err
return [a - lr * g / n for a, g in zip(w, gw)], b - lr * gb / n- The stable sigmoid never overflows. The gradient is the mean of (p - y) x.
- The homework adds the loss, the loop and an L2 penalty that skips the bias.
Summary
Recap
- The log-loss gradient is (p - y) x because the sigmoid’s p(1-p) cancels; squared error on a sigmoid stalls when confidently wrong.
- The normal equation is exact and cheap for small d; collinearity makes coefficients unstable; gradient descent scales and generalises.
- Squared error follows the mean, absolute error the median, Huber sits between; hinge ignores points past margin 1; log loss gives probabilities.
- Learning rate too high diverges, too low crawls; momentum and Adam help but need tuning; standardise features first, on training data only.
References
References & Sources (1 of 2)
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_linear-regression/linear-regression.html
Used for The analytic solution w = (X'X)^-1 X'y and its requirement of linearly independent columns; minimising mean squared error is maximum likelihood under additive Gaussian noise; minibatch SGD and typical batch sizes of 32 to 256.
Linear Models (ridge regression and lasso) (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/linear_model.html
Used for Least squares cost O(n_samples n_features^2) via the singular value decomposition; collinear features make the least-squares estimate highly sensitive to random errors in the target (large variance); the logistic regression cost function (cross-entropy plus a penalty); HuberRegressor applies a linear loss to samples treated as outliers and gives them a lesser weight rather than ignoring them.
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_linear-classification/softmax-regression.html
Used for The derivative of the cross-entropy loss with respect to the logits is the softmax output minus the label.
Stochastic Gradient Descent (scikit-learn user guide) (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/sgd.html
Used for Hinge and log-loss definitions (max(0, 1 - y f(x)) and log(1 + exp(-y f(x)))); SGD is sensitive to feature scaling, with advice to scale to [0,1] or [-1,1] or standardise and to fit the scaler on training data only; features with an intrinsic scale may not need scaling; default decaying learning-rate schedules.
Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book
https://d2l.ai/chapter_optimization/momentum.html
Used for Ill-conditioned problems (a small learning rate is safe in the steep direction but slow in the flat one), the momentum update as a leaky average of past gradients, and the effective step scaling of 1/(1 - beta).
References
References & Sources (2 of 2)
torch.optim.Adam (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.optim.Adam.html
Used for The Adam update with bias-corrected first and second moment estimates, and the default values (learning rate 0.001, betas 0.9 and 0.999, epsilon 1e-8).
torch.optim.SGD (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.15/generated/torch.optim.SGD.html
Used for The momentum update v = mu*v + g, p = p - lr*v, and the note that PyTorch's convention differs from the formulation in Sutskever et al. and other frameworks.
Adam: A Method for Stochastic Optimization (opens in a new tab)
Diederik P. Kingma, Jimmy Ba2015ICLR 2015 (arXiv:1412.6980)Paper
https://arxiv.org/abs/1412.6980
Used for Adam is a first-order gradient-based optimizer for stochastic objectives (abstract page only; the update rule and defaults above are taken from the PyTorch documentation, since the paper's PDF could not be read as text).
Cross-validation: evaluating estimator performance (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/cross_validation.html
Used for Preprocessing such as scaling should be learned from the training set only and applied to held-out data (cited by the scaling advice).
Keys: ← → move, Home End first and last, F full screen.