Slides · ML foundations

Linear models, loss functions and gradient descent

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:

  1. Derive the gradient (p - y) x and say why log loss pairs with a sigmoid.
  2. Solve linear regression two ways and know when each fits.
  3. Choose a loss by what it penalises.
  4. Tune and debug gradient descent: learning rate, momentum, Adam, scaling.

Compare

Same loop, different pieces

TaskOutputTypical lossWhy
RegressionLinearSquared errorLikelihood under Gaussian noise
Regression with outliersLinearAbsolute or HuberErrors grow linearly
Binary classesSigmoidLog lossBernoulli likelihood
MulticlassSoftmaxCross-entropyCategorical likelihood
Margin classifierRaw scoreHingeOnly boundary points matter
  • Change one piece and you have a different algorithm.

Source1 Dive into Deep Learning, Linear Regression (analytic solution, minibatch SGD, squared loss and Gaussian noise)

Math

Linear regression: the normal equation

J(w)=1n∥Xw−y∥2,∇wJ=2nX⊤(Xw−y)=0J(w)=\tfrac1n\lVert Xw-y\rVert^2,\qquad \nabla_w J=\tfrac2n X^{\top}(Xw-y)=0X⊤X w=X⊤y⇒w=(X⊤X)−1X⊤yX^{\top}X\,w=X^{\top}y\quad\Rightarrow\quad w=(X^{\top}X)^{-1}X^{\top}y
  • The middle form says the residual is orthogonal to every column of XX.
  • 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.

Source1 Dive into Deep Learning, Linear Regression (analytic solution, minibatch SGD, squared loss and Gaussian noise)

Worked example

Worked example: three points, exact

Fit y=b+wxy=b+wx to x=[1,2,3]x=[1,2,3], y=[2,4,5]y=[2,4,5].

QuantityValue
X⊤XX^{\top}X(36614)\begin{pmatrix}3&6\\6&14\end{pmatrix}
X⊤yX^{\top}y(11, 25)(11,\ 25)
Determinant6
b, wb,\ w2/3 and 3/2
Residuals-1/6, 1/3, -1/6
MSE1/18
  • Residuals sum to 0, and ∑xiri=0\sum x_ir_i=0: the orthogonality condition, checked.

Compare

Closed form or gradient descent?

Normal equationGradient descent
CostAbout nd2nd^2 to form, d3d^3 to solveA pass over a batch per step
Learning rateNoneMust be tuned
Collinear columnsNearly singular, unstable coefficientsConverges slowly along the flat direction; ridge helps both
No closed form (logistic, neural nets)Not availableThe general tool
Streaming dataNeeds all dataMini-batches
  • Libraries use a decomposition of XX, not a literal inverse.
  • Unstable coefficients with stable predictions is the signature of collinearity.

Sources2 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×109nd^2 = 4\times10^9 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

Diagram: A linear score is squashed to a probability, the log loss compares it with the label, and the gradient (p minus y) times x is subtracted...

Features x

Score z = w.x + b

Sigmoid: p

Log loss

Gradient (p - y) x

w = w - lr * gradient

Diagram summary: A linear score is squashed to a probability, the log loss compares it with the label, and the gradient (p minus y) times x is subtracted from the weights, scaled by the learning rate.

Source2 Linear Models (ridge regression and lasso)

Math

Deriving (p - y) x

ℓ=−[ylog⁡p+(1−y)log⁡(1−p)],σ′(z)=p(1−p)\ell=-\big[y\log p+(1-y)\log(1-p)\big],\qquad \sigma'(z)=p(1-p)∂ℓ∂z=(−yp+1−y1−p)p(1−p)=−y(1−p)+(1−y)p=p−y\frac{\partial\ell}{\partial z}=\Big(-\frac yp+\frac{1-y}{1-p}\Big)p(1-p)=-y(1-p)+(1-y)p=p-y
  • Then ∇wℓ=(p−y)x\nabla_w\ell=(p-y)x and ∂ℓ/∂b=p−y\partial\ell/\partial b=p-y.
  • The sigmoid’s p(1−p)p(1-p) cancels the denominators of the logs.
  • Softmax with cross-entropy gives (softmax - one-hot) on the logits: the same form.

Source3 Dive into Deep Learning, Softmax Regression (softmax and cross-entropy loss, derivative with respect to the logits)

Worked example

Worked example: one step by hand

One example x=[1,2]x=[1,2], y=1y=1, w=[0,0]w=[0,0], b=0b=0, learning rate 0.1.

QuantityValue
Score and probabilityz=0z=0, p=0.5p=0.5
Error p−yp-y-0.5
Gradient[−0.5,−1][-0.5,-1] and −0.5-0.5 for the bias
New w, bw,\ b[0.05, 0.10][0.05,\ 0.10] and 0.05
New score, probability0.30 and 0.574
Log loss0.693 to 0.554
  • With y=0y=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 zz, label y=1y=1:

zzppCross-entropySquared error
-60.00247-0.99753-0.00246
-20.1192-0.8808-0.09248
00.5-0.5-0.125
20.8808-0.1192-0.01252
  • Squared error keeps the factor p(1−p)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 xjx_j multiplies the odds by ewje^{w_j} (about 2.01 for wj=0.7w_j=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][1,2,3,4,100] that is 22 against 3.
  • A line: x=1..6x=1..6, y=2xy=2x except the last label 12 became 40.
FitResultPrediction at x = 1
Least squaresy=−9.333+6xy=-9.333+6x-3.333
Least absolute deviationsy=2xy=2x2
  • 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.

Source2 Linear Models (ridge regression and lasso)

Compare

Classification losses by margin

Margin m=yf(x)m=yf(x)HingeLog lossSquared (1−m)2(1-m)^2
-232.1279
-121.3134
010.6931
100.3130
200.1271
  • 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.

Source4 Stochastic Gradient Descent (scikit-learn user guide)

Diagram

Where each loss stops caring

Diagram: Below a margin of 1 both the hinge and the log loss charge a roughly linear penalty.

yes

no

Margin m = y * f(x)

m below 1?

Hinge and log loss both penalise,
roughly linearly as m falls

Hinge: exactly 0
Log loss: small, never 0

Diagram summary: Below a margin of 1 both the hinge and the log loss charge a roughly linear penalty. Past it the hinge is exactly zero and ignores the point, while the log loss keeps a shrinking penalty.

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)w \leftarrow w - \eta\,\nabla_w J(w)

On J(w)=w2J(w)=w^2 each step multiplies ww by 1−2η1-2\eta.

Learning rateBehaviour from w=1w=1
0.10.8, 0.64, 0.512: converges slowly
0.5Lands 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\eta \lt 2/h for curvature hh. 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.

Sources1 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−ηvv\leftarrow\beta v+g,\quad w\leftarrow w-\eta v

Adam, per parameter:

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,w←w−ηm^tv^t+ϵm_t=\beta_1m_{t-1}+(1-\beta_1)g_t,\quad v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^2,\quad w\leftarrow w-\eta\frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon}
  • Momentum: agreeing gradients add up, zigzags cancel.
  • Adam: a step size per parameter; first step is about η\eta 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.

Sources5 Dive into Deep Learning, Momentum (ill-conditioned problems and the leaky average of gradients)6 torch.optim.Adam7 torch.optim.SGD8 Adam: A Method for Stochastic Optimization

Worked example

Honest numbers: a narrow valley

f=0.1w12+2w22f=0.1w_1^2+2w_2^2 from (5,3)(5,3). Steps until f<10−6f\lt10^{-6}, best setting on a grid:

MethodBest settingSteps
Gradient descentη=0.45\eta=0.4579
Momentumη=0.5, β=0.5\eta=0.5,\ \beta=0.523
Adamη=0.7\eta=0.7114
  • At η=0.5\eta=0.5 plain descent oscillates forever (steep factor 1−0.5⋅4=−11-0.5\cdot4=-1, exactly the limit 2/42/4); at 0.51 it diverges.
  • Momentum with β=0.9\beta=0.9, a common choice, took 122 to 290 steps: slower than tuned plain descent. Tune β\beta with η\eta.
  • 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.

Source5 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:

FeaturesCondition numberSteps
Raw23,20096,865
Centred9,76036,206.5
Standardised1.123
  • 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.

Sources4 Stochastic Gradient Descent (scikit-learn user guide)9 Cross-validation: evaluating estimator performance

Diagram

When the loss will not go down

Diagram: Exploding or NaN points to a too-high rate, unscaled inputs or a numerical bug.

yes

no

yes

no

Loss is not going down

NaN or exploding?

Lower rate, scale inputs,
check log(0) and division by zero

Flat from step one?

Rate too low, loss or label bug,
unscaled features

Falls then plateaus:
decay the rate, add features

Diagram summary: Exploding or NaN points to a too-high rate, unscaled inputs or a numerical bug. Flat from the start points to a too-low rate or a bug in the loss or labels. Falling then levelling off points to the schedule or the model. A sanity check: overfit ten rows to near-zero loss.

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)

  1. Dive into Deep Learning, Linear Regression (analytic solution, minibatch SGD, squared loss and Gaussian noise) (opens in a new tab)

    Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book

    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.

  2. Linear Models (ridge regression and lasso) (opens in a new tab)

    scikit-learn2026Documentation

    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.

  3. Dive into Deep Learning, Softmax Regression (softmax and cross-entropy loss, derivative with respect to the logits) (opens in a new tab)

    Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book

    Used for The derivative of the cross-entropy loss with respect to the logits is the softmax output minus the label.

  4. Stochastic Gradient Descent (scikit-learn user guide) (opens in a new tab)

    scikit-learn2026Documentation

    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.

  5. Dive into Deep Learning, Momentum (ill-conditioned problems and the leaky average of gradients) (opens in a new tab)

    Aston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola2026Book

    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)

  1. torch.optim.Adam (opens in a new tab)

    PyTorch2026Documentation

    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).

  2. torch.optim.SGD (opens in a new tab)

    PyTorch2026Documentation

    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.

  3. Adam: A Method for Stochastic Optimization (opens in a new tab)

    Diederik P. Kingma, Jimmy Ba2015ICLR 2015 (arXiv:1412.6980)Paper

    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).

  4. Cross-validation: evaluating estimator performance (opens in a new tab)

    scikit-learn2026Documentation

    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).