Lesson 32 · 100 min · core
Supervised Learning & Gradient Descent
Supervised learning chooses a predictor by minimising the average loss on training data. This lesson formulates empirical-risk minimisation (ERM), proves that the training risk of an ERM solution is optimistically biased and decomposes the expected squared error into noise, bias and variance. It derives the gradients of the mean-squared-error loss of a linear model and of the binary cross-entropy of logistic regression coordinate by coordinate and in matrix form, proves the descent lemma for -smooth functions and the rate of gradient descent with step on convex objectives, shows that the iteration diverges on a quadratic once the step exceeds , and proves that minibatch gradients are unbiased with variance proportional to — the same structure as the shot-noise-limited gradients of variational quantum circuits.
Objectives and key results
Formulate empirical-risk minimisation , define the population risk and the generalisation gap, and prove that .
Derive the bias–variance decomposition with every algebraic step.
Derive and for the MSE loss, and for the binary cross-entropy, including .
Prove the descent lemma and the convergence rate of gradient descent on convex -smooth functions with a full telescoping argument.
Show with the spectral theorem that gradient descent on a positive-definite quadratic converges for every start if and only if .
Prove that a minibatch gradient is an unbiased estimator of the full gradient with covariance , and compute the variance of an -shot Pauli expectation estimate.
Implement a vectorised MSE gradient in TypeScript and check it against finite differences.
- definition · Empirical-risk minimisation
- formula · Gradient of the mean-squared error
- formula · Gradient of the logistic (binary cross-entropy) loss
- theorem · Descent lemma
- theorem · O(1/k) rate of gradient descent
Supervised learning and empirical-risk minimisation#
Quantum machine learning reuses the classical training loop almost unchanged: a model with parameters makes predictions, a loss compares them with labels, and an optimiser moves against the gradient of the average loss. In Stage 4 the model will be a parameterised quantum circuit and the gradient will be estimated from measurement shots; in this lesson every object is classical, so each step of the loop can be derived exactly. We work with real vectors , the Euclidean inner product and norm — the real special case of the Hilbert-space structure of the first lessons.
Definition
Supervised learning problem
An unknown probability distribution on generates labelled examples. A training sample consists of independent draws from . A hypothesis class is a set of functions , and a loss scores a prediction against a label: the squared loss for regression, the cross-entropy for binary classification with . The population risk of is and its empirical risk on is .
Definition
Empirical-risk minimisation and generalisation gap
Empirical-risk minimisation returns a hypothesis with the smallest training loss, The population risk cannot be computed because is unknown; ERM replaces it by its sample average. The generalisation gap of the returned hypothesis is , the amount by which the training loss under-reports the loss on fresh data. When is parameterised, ERM is the finite-dimensional optimisation problem with , which the rest of the lesson solves by gradient descent.
Training risk is unbiased for a fixed model and optimistic for the ERM model
Assume all risks below are finite. (a) For every fixed that does not depend on , . (b) If is an empirical-risk minimiser over , then so the expected generalisation gap is non-negative.
Proof (7 steps)
- Step 1:Linearity of expectation applied to the average of terms.
- Step 2:Each pair has distribution , and is fixed, so every term has the expectation . This proves (a).
- Step 3:Definition of as a minimiser of over .
- Step 4:Expectation preserves inequalities; then apply (a) to the fixed .
- Step 5:The left side does not depend on , so it is a lower bound of the set , hence below its infimum.
- Step 6:for every sample, and the expectation of a quantity bounded below by a constant is bounded below by that constant.
- Step 7:Subtract the two previous inequalities. Part (a) fails for precisely because was chosen by looking at .
∎
For regression with the squared loss, the error on a fresh example can be split further. Fix a test input and write the label as with the regression function and noise satisfying and . The prediction is random through the training sample , which is independent of the test noise . Let be the average prediction over training samples.
Bias–variance decomposition of the expected squared error
Under the assumptions above, for every input , and averaging over gives the same decomposition of the expected test MSE.
Proof (7 steps)
- Step 1:Substitute , then add and subtract . At fixed , is a number and is random only through .
- Step 2:Expand with , , .
- Step 3:is constant at fixed and the noise has conditional mean zero.
- Step 4:The test noise is independent of the training sample, so the expectation of the product factorises; the first factor is .
- Step 5:Linearity of and the definition of : the cross term vanishes because has mean zero.
- Step 6:Take expectations of the expansion, drop the three vanishing cross terms, and use .
- Step 7:Tower property: average the pointwise identity over the test input , which is independent of .
∎
Quick check
A regression model reaches training MSE but test MSE on a large held-out set drawn from the same distribution. Which statement is supported by this lesson?
Linear regression and the gradient of the mean-squared error#
The linear model predicts with weights and bias . Collect the inputs as the rows of the design matrix (so is feature of sample ), the labels as , and write for the all-ones vector. ERM with the squared loss minimises the mean-squared error and the residuals form the vector .
Gradient of the MSE, coordinate by coordinate
- Step 1:Differentiation is linear, so it passes through the constant factor and the finite sum.
- Step 2:Chain rule with the outer function , whose derivative is .
- Step 3:Only the term of the sum depends on ; and are constants with respect to .
- Step 4:Substitute the two previous lines into the first.
- Step 5:Stack the coordinates: the vector with entries , , is .
- Step 6:Same chain rule with , because enters every prediction with coefficient .
Result
Matrix form and a worked example
- Step 1:Definition of the matrix–vector product and of the transpose, .
- Step 2:Compare with the coordinate formula: entry of is the dot product of column of with , and .
- Step 3:The predictions of the example () used as the visible test of the lab.
- Step 4:Residuals are prediction minus label.
- Step 5:Apply with , so the prefactor is .
- Step 6:Apply . All components are negative, so increasing , and lowers the loss: both predictions are too small.
Result
The MSE is convex and L-smooth
- Step 1:Append a constant feature so that the bias becomes an ordinary weight; the previous derivation then covers and at once.
- Step 2:Differentiate with respect to using . The Hessian does not depend on .
- Step 3:. A twice-differentiable function with positive-semidefinite Hessian everywhere is convex.
- Step 4:The gradient is affine in , and a symmetric positive-semidefinite matrix stretches no vector by more than its largest eigenvalue (spectral theorem).
Result
Quick check
Keep , , from the worked example but set . What is ?
The listing below implements the vectorised gradient, checks it against central finite differences , computes by power iteration and runs gradient descent with step on a noiseless problem whose minimiser is , with . Each printed loss is compared with the bound proved in the convergence section, with .
// Linear least squares with two features: yhat = w . x + b, loss = (1/m) sum_i (yhat_i - y_i)^2.
const X = [[1, 2], [2, 0], [3, 1], [0, 1], [-1, 3], [2, 2]];
const y = X.map(([x1, x2]) => 2 * x1 - x2 + 0.5); // noiseless: w* = (2, -1), b* = 0.5, loss* = 0
const m = X.length;
const residuals = (w, b) => X.map((x, i) => x[0] * w[0] + x[1] * w[1] + b - y[i]);
const loss = (w, b) => residuals(w, b).reduce((s, r) => s + r * r, 0) / m;
// Vectorised gradient: grad_w = (2/m) X^T r and dL/db = (2/m) 1^T r with r = Xw + b1 - y.
function gradient(w, b) {
const r = residuals(w, b);
const gw = [0, 1].map((k) => (2 / m) * X.reduce((s, x, i) => s + x[k] * r[i], 0));
const gb = (2 / m) * r.reduce((s, ri) => s + ri, 0);
return { gw, gb };
}
// Check the gradient against central finite differences at an arbitrary point.
const w0 = [0.3, -0.7], b0 = 0.2, h = 1e-6;
const g0 = gradient(w0, b0);
const fd = [
(loss([w0[0] + h, w0[1]], b0) - loss([w0[0] - h, w0[1]], b0)) / (2 * h),
(loss([w0[0], w0[1] + h], b0) - loss([w0[0], w0[1] - h], b0)) / (2 * h),
(loss(w0, b0 + h) - loss(w0, b0 - h)) / (2 * h),
];
const fdErr = Math.max(...[...g0.gw, g0.gb].map((g, j) => Math.abs(g - fd[j])));
console.log('finite-difference check: ' + (fdErr < 1e-6 ? 'ok' : 'FAILED'));
// Smoothness constant L = lambda_max of the Hessian (2/m) A^T A with A = [X 1], by power iteration.
const A = X.map((x) => [x[0], x[1], 1]);
const hess = [0, 1, 2].map((p) => [0, 1, 2].map((q) => (2 / m) * A.reduce((s, a) => s + a[p] * a[q], 0)));
let v = [1, 1, 1];
for (let it = 0; it < 500; it++) {
const hv = hess.map((row) => row.reduce((s, hpq, q) => s + hpq * v[q], 0));
const nrm = Math.hypot(...hv);
v = hv.map((t) => t / nrm);
}
const L = hess.map((row) => row.reduce((s, hpq, q) => s + hpq * v[q], 0)).reduce((s, t, p) => s + t * v[p], 0);
console.log('L = ' + L.toFixed(6));
// Gradient descent with step 1/L from (w, b) = (0, 0, 0); bound L * ||x0 - x*||^2 / (2k).
let w = [0, 0], b = 0;
const dist0 = 2 ** 2 + (-1) ** 2 + 0.5 ** 2;
const report = [1, 2, 5, 10, 20, 50, 100, 200, 400];
console.log('k = 0 loss = ' + loss(w, b).toExponential(4));
for (let k = 1; k <= 400; k++) {
const { gw, gb } = gradient(w, b);
w = [w[0] - gw[0] / L, w[1] - gw[1] / L];
b = b - gb / L;
if (report.includes(k)) {
const bound = (L * dist0) / (2 * k);
console.log('k = ' + k + ' loss = ' + loss(w, b).toExponential(4) + ' bound = ' + bound.toExponential(4) + (loss(w, b) <= bound ? ' ok' : ' VIOLATED'));
}
}
console.log('w = (' + w[0].toFixed(6) + ', ' + w[1].toFixed(6) + ') b = ' + b.toFixed(6));Expected output
finite-difference check: ok L = 10.097998 k = 0 loss = 1.2917e+1 k = 1 loss = 3.1800e+0 bound = 2.6507e+1 ok k = 2 loss = 1.0315e+0 bound = 1.3254e+1 ok k = 5 loss = 4.5253e-2 bound = 5.3014e+0 ok k = 10 loss = 9.4194e-3 bound = 2.6507e+0 ok k = 20 loss = 6.2597e-3 bound = 1.3254e+0 ok k = 50 loss = 1.9073e-3 bound = 5.3014e-1 ok k = 100 loss = 2.6314e-4 bound = 2.6507e-1 ok k = 200 loss = 5.0089e-6 bound = 1.3254e-1 ok k = 400 loss = 1.8148e-9 bound = 6.6268e-2 ok w = (2.000030, -0.999950) b = 0.499878
Logistic regression and the cross-entropy gradient#
For labels , logistic regression models the probability of class as with the logit and the sigmoid . Maximising the likelihood is the same as minimising the average negative log-likelihood, the binary cross-entropy
Derivative of the sigmoid
- Step 1:Definition, written as a power so that the chain rule applies directly.
- Step 2:Chain rule: the derivative of is , and .
- Step 3:Split the square in the denominator into two factors.
- Step 4:Add and subtract in the numerator.
- Step 5:Combine the two previous lines. In particular , the maximum of , since with equality at .
Result
Gradient of the binary cross-entropy
- Step 1:and .
- Step 2:Common denominator ; the numerator simplifies as .
- Step 3:The sigmoid derivative derived above, with .
- Step 4:Chain rule; the factor is non-zero and cancels.
- Step 5:The logit is linear in the parameters, exactly as the prediction of the linear model.
- Step 6:Average the per-sample chain rule over and stack the coordinates.
Result
The cross-entropy is convex and L-smooth
- Step 1:Differentiate with and (rows ), and use .
- Step 2:Each weight lies in and each square is non-negative, so the Hessian is positive semidefinite and is convex.
- Step 3:Bound , then use the Rayleigh quotient bound of the spectral theorem.
Result
Quick check
At a sample with logit and label , what is the per-sample derivative of the binary cross-entropy?
Smoothness and the descent lemma#
Gradient descent (GD) with step size (learning rate) iterates The first-order Taylor model predicts a decrease, but only for small enough ; to control the error of the linear model we need a bound on how fast the gradient can change.
Definition
L-smooth function
A differentiable function is -smooth if its gradient is -Lipschitz: Example: for with symmetric positive semidefinite, and , so . The MSE and the cross-entropy are -smooth with the constants derived above.
Descent lemma
If is -smooth, then for all
Proof (6 steps)
- Step 1:Restrict to the segment from to ; the multivariate chain rule gives . A Lipschitz gradient is continuous, so is continuously differentiable.
- Step 2:Fundamental theorem of calculus for on (the integral form of Taylor's theorem of order one).
- Step 3:Subtract , the integral of a constant over an interval of length .
- Step 4:Cauchy–Schwarz inside the integral; integrals preserve pointwise inequalities.
- Step 5:-smoothness at the points and , whose distance is for .
- Step 6:. Moving to the right-hand side gives the claim.
∎
Sufficient decrease of one gradient step
If is -smooth and , then Every step decreases unless , and the step maximises the guaranteed decrease: .
Proof (5 steps)
- Step 1:Descent lemma with , so .
- Step 2:and .
- Step 3:Factor out . The bracket is positive exactly when .
- Step 4:The guaranteed decrease is a concave parabola in , maximal where its derivative vanishes.
- Step 5:Substitute , so .
∎
Convergence of gradient descent: the O(1/k) rate and the step-size threshold#
First-order characterisation of convexity
If is convex and differentiable, i.e. for all and , then for all : the tangent plane lies below the graph.
Proof (3 steps)
- Step 1:Rewrite and in the definition of convexity.
- Step 2:Subtract and divide by .
- Step 3:The left side is the directional derivative of at in direction ; limits preserve the non-strict inequality.
∎
Gradient descent on convex L-smooth functions converges at rate O(1/k)
Let be convex and -smooth with a minimiser , , and run from any . Then for every and the distance never increases. To reach accuracy it suffices to take steps.
Proof (10 steps)
- Step 1:First-order convexity with , : ; rearrange.
- Step 2:Sufficient decrease with step (corollary of the descent lemma).
- Step 3:Insert the first inequality into the second.
- Step 4:Substitute the update and expand .
- Step 5:Multiply the expansion by and solve for .
- Step 6:Combine the two previous lines; the left inequality holds because is the minimum. In particular .
- Step 7:Sum the per-step bound over ; the right-hand side telescopes, leaving the first and the last term.
- Step 8:Drop the non-negative term .
- Step 9:Monotonicity: by sufficient decrease , so the last iterate has the smallest value; each of the summands is at least .
- Step 10:Chain the two previous inequalities and divide by .
∎
Gradient descent on a quadratic: convergence if and only if 0 < η < 2/λ_max
Let with symmetric positive definite, eigenvalues and orthonormal eigenvectors . Gradient descent with constant step satisfies Hence for every start if and only if , in which case with ; if and , then .
Proof (9 steps)
- Step 1:Gradient of the quadratic form is for symmetric , here with .
- Step 2:Subtract from both sides of the GD update and factor.
- Step 3:Induction on with the one-step recursion.
- Step 4:Spectral theorem for the real symmetric ( orthogonal with columns ); and makes the inner factors cancel in the power.
- Step 5:Multiply the previous identity by ; is diagonal, so the coordinates along the eigenvectors decouple.
- Step 6:, and .
- Step 7:For : iff , and for all iff . Then each factor with .
- Step 8:Keep only the term of the non-negative sum. If the error never drops below a positive constant, so convergence fails for such starts.
- Step 9:, so the -coordinate flips sign and grows geometrically: the iterates oscillate with increasing amplitude.
∎
Example: f(w) = ½(w₁² + 10w₂²) from w₀ = (−1.8, 1.2)
- Step 1:is already diagonal, so and each coordinate evolves with its own factor ; .
- Step 2:Both factors lie in : alternates in sign and halves every step, shrinks slowly. After steps .
- Step 3:: the steep coordinate overshoots further at every step. After steps , although the factor still contracts.
- Step 4:On , decreases while decreases until and then increases; the maximum of the two is smallest where the decreasing and the increasing branch cross. In general gives with .
The first plot uses : the trajectory zig-zags across the narrow valley along while creeping along the flat direction . The second plot raises the step to with everything else unchanged; drag the learning-rate slider across to watch the transition from damped to growing oscillations.
Quick check
Gradient descent minimises . What is the supremum of the constant step sizes for which it converges from every starting point?
Stochastic gradients and the bridge to shot noise#
For a training loss , one exact gradient costs per-sample gradients. Stochastic gradient descent (SGD) replaces it by a cheap random estimate: draw indices independently and uniformly from (sampling with replacement) and use the minibatch gradient with fresh indices at every step. Write for the covariance of one uniformly drawn per-sample gradient.
The minibatch gradient is unbiased with covariance Σ/B
For fixed ,
Proof (6 steps)
- Step 1:Expectation of a function of the discrete uniform index , with ; the last equality is linearity of the gradient.
- Step 2:Linearity of expectation; every index has the same distribution. This is unbiasedness.
- Step 3:Subtract ; the are independent because the indices are, and centred by the first step.
- Step 4:For , independence and zero mean give ; only the diagonal terms remain.
- Step 5:Same uniform average as in the first step, applied to the outer product.
- Step 6:Sum the identical terms; the mean squared error of a vector estimator is the trace of its covariance, since .
∎
Expected progress of one SGD step
If is -smooth, then one SGD step from a fixed satisfies The last term does not vanish at a minimiser: with a constant step, SGD stalls in a noise ball whose size shrinks with smaller or larger .
Proof (5 steps)
- Step 1:Descent lemma with , valid for every realisation of the minibatch.
- Step 2:is fixed, so is a constant vector; then use unbiasedness.
- Step 3:Write and expand the square; the cross term has expectation . Then apply the theorem above.
- Step 4:Take expectations of the first inequality and substitute the two previous lines.
- Step 5:Collect the two terms in .
∎
The plot runs the same quadratic with step and zero-mean noise added to every gradient: the trajectory reaches the valley as fast as GD but then jitters around the minimiser instead of converging, as the noise term of the proposition predicts. Lowering the noise level or the learning rate shrinks the jitter.
The bridge to quantum gradients. A variational quantum circuit prepares and its model output is an expectation value of an observable, here a Pauli string with eigenvalues . Hardware never returns itself, only measurement outcomes, so every quantity entering gradient descent is an estimate — exactly the situation of SGD.
Shot noise: unbiased estimates with variance proportional to 1/N
- Step 1:, so are the projectors onto its eigenspaces; the Born rule gives the outcome probabilities of one shot .
- Step 2:Definition of the expectation of a two-valued random variable.
- Step 3:for both outcomes.
- Step 4:The shots are independent and identically distributed: linearity gives the mean, and variances of independent terms add, each scaled by .
- Step 5:Linearity of expectation; the last equality is the parameter-shift rule, exact for gates with a Pauli generator , which Stage 4 proves. The shot-based gradient is therefore unbiased.
- Step 6:The two shifted circuits are measured with independent shots, so the variances add with the factor ; each .
Result
Quick check
The minibatch size is raised from to (sampling with replacement). What happens to the standard deviation of each coordinate of the gradient estimate ?
References
- T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning: Data Mining, Inference, and Prediction, 2nd ed., Springer (2009), §2.9, §3.2, §4.4, §7.3.doi:10.1007/978-0-387-84858-7
- Y. Nesterov, Introductory Lectures on Convex Optimization: A Basic Course, Kluwer Academic Publishers (2004), §1.2.2 and §2.1.doi:10.1007/978-1-4419-8853-9
- L. Bottou, F. E. Curtis and J. Nocedal, Optimization Methods for Large-Scale Machine Learning, SIAM Review 60(2), 223–311 (2018).doi:10.1137/16M1080173
- S. Shalev-Shwartz and S. Ben-David, Understanding Machine Learning: From Theory to Algorithms, Cambridge University Press (2014), ch. 2 and ch. 14.doi:10.1017/CBO9781107298019
- M. Schuld, V. Bergholm, C. Gogolin, J. Izaac and N. Killoran, Evaluating analytic gradients on quantum hardware, Physical Review A 99, 032331 (2019).doi:10.1103/PhysRevA.99.032331
Hands-on labs
Gradient of the mean-squared error
1 step · auto-gradedOpen labImplement the vectorised gradient of the mean-squared-error loss of a linear model, namely and with residuals . The function is graded on one visible worked example and five hidden random problems with up to samples and features, to absolute tolerance .