SStatistics, Built

Stage III · Master's

Part 21 of 65

Optimization for Statistics

Master'sstarts at this level55 min of film13 chaptersprerequisites: Part 4, Part 9, Part 19

How are estimators actually computed, and what does the shape of the problem say about them?

In 1939 George Dantzig arrives late to Neyman's class, copies two problems from the board as homework and solves them; one becomes, with Wald, the generalized Neyman-Pearson lemma, whose mathematics is linear-programming duality, and in 1947 he invents the simplex method. The World's bakery, a two-variable linear program, is walked from corner to corner and priced by its dual. The part then treats almost every estimator of the course as an optimization problem. Convexity says when a local answer is the global one, and the condition number says how slowly gradient descent gets there. Lagrange multipliers, KKT and duality turn constraints into prices and give the lasso a stopping certificate. Then the algorithms, each on a statistical problem: linear programming for least absolute deviations and quantile regression, Newton and Fisher scoring for a logistic likelihood, MM, coordinate descent, ISTA and FISTA, ADMM, and stochastic gradient with Polyak-Ruppert averaging. It ends where optimization meets inference: the curvature at the optimum is the observed information, and an optimizer should be run until its error is small beside the standard error.

What you need. Multivariable calculus (gradients, Hessians) and the matrix language of Part 4; the lasso and logistic regression as met in Stage II.

Hook
Dantzig's "homework", 1939
Mathematics
convexity, duality and KKT, Newton and scoring, MM and EM, coordinate descent, proximal methods, LP, ADMM, SGD
Built
statkit.optim

What you will be able to do

Bachelor's

  • Solve a two-variable linear program by walking its corners, and read the shadow prices as the worth of one more unit of each resource.
  • Tell a convex objective from one with several peaks, and say why that matters to an optimizer.

Master's

  • Write the KKT conditions of a constrained likelihood or of the lasso and check them at a proposed solution.
  • Implement Newton or Fisher scoring, coordinate descent and proximal gradient for a statistical objective, and state the rate each one has.
  • Compute a duality gap and use it as a stopping certificate.

PhD

  • Prove the descent property of an MM algorithm and the 1/k bound of proximal gradient, and state the class of problems for which Nesterov's 1/k^2 order cannot be improved.
  • State the conditions under which the Polyak-Ruppert average is asymptotically efficient, and which step exponents they exclude.

Practice

  • Decide when to stop an optimizer by comparing its error with a tenth of the standard error, and read non-convergence warnings from the shape of the likelihood.
  • Report standard errors from the curvature at the optimum only after checking that the optimum was reached.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 11 min · Master's 51 min · PhD 55 min · Practice 16 min.

  1. 0Dantzig's homework, 1939Bachelor's4 min
  2. 1Convex sets and functionsBachelor's5 min
  3. 2Lagrange and KKTMaster's4 min
  4. 3DualityMaster's4 min
  5. 4Linear programmingMaster's5 min
  6. 5Newton and Fisher scoringMaster's5 min
  7. 6MM algorithmsMaster's4 min
  8. 7Coordinate descentMaster's4 min
  9. 8Proximal methodsPhD4 min
  10. 9ADMMMaster's4 min
  11. 10Stochastic gradientMaster's5 min
  12. 11Optimization and inferencePractice5 min
  13. Recap, problems, and the road aheadAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

Dantzig's homework, 1939Bachelor's4 min

The master's stage begins with a story statisticians like to tell. In 1939 George Dantzig, a graduate student at Berkeley, arrived late to a class of Jerzy Neyman's. Two problems were on the board, and he copied them down as homework. A few days later he handed in solutions, apologizing that they had taken longer than usual. They were two famous unsolved problems in statistics. The two solutions formed the basis of his 1946 doctoral thesis. The other, published with Abraham Wald in 1951, generalized the Neyman–Pearson lemma, and its mathematics turned out to be the duality of linear programming. By then Dantzig had invented the simplex method, in 1947, to plan the logistics of the United States Air Force.

A linear program in two dimensions shows the idea. The World's bakery bakes trays of loaves and trays of cakes, and makes three on a tray of loaves and four on a tray of cakes. But flour is limited: a tray of cakes takes two sacks, a tray of loaves one, and there are fourteen sacks. The oven has twenty-four hours, and loaves take longer. And there are nine shifts of staff. Each constraint is a half-plane; together they leave a polygon of feasible plans. The question: which plan makes the most money?

The profit is a straight line's worth of plans at each level, so at least one optimal plan is at a corner of this bounded feasible polygon. Dantzig's simplex method moves between basic feasible solutions without decreasing profit; degenerate pivots can leave it unchanged. Start at the empty plan, profit zero. The cakes earn more, so bake cakes until flour runs out: seven trays, profit twenty-eight. Then trade cakes for loaves along the flour line until the staff run out: four trays of loaves and five of cakes, thirty-two. No neighbouring corner is higher, so this is the optimum. The method also gives shadow prices: for sufficiently small resource changes within the same optimal regime, an extra sack of flour is worth one, a staff shift two, and an oven hour nothing because the oven is slack. Those prices solve a second linear program, the dual, which is where Dantzig's homework comes back.

The first big test of the method was a famous puzzle. In 1945 the economist George Stigler asked for the cheapest diet that meets nine nutritional requirements, choosing among seventy-seven foods at 1939 prices. By clever trial and error he found one costing thirty-nine dollars and ninety-three cents a year. In 1947 Jack Laderman solved it exactly with Dantzig's new simplex method: nine constraints, seventy-seven unknowns, and about a hundred and twenty person-days of work on desk calculators. The true optimum was thirty-nine sixty-nine: Stigler had been within twenty-four cents. Modern solvers handle much larger sparse programs, though runtime depends on structure, conditioning and hardware.

Why does a statistician need this? Because almost every estimator is the solution of an optimization problem. The mean minimizes squared distances, in closed form. The median minimizes absolute distances, a linear program. Maximum likelihood maximizes a log likelihood, usually with no formula at all. The lasso minimizes a penalized loss that isn't even differentiable. This part is about how those optima are found, how fast, and what the shape of the problem tells us about the estimator.

Numbers: bakery 0 → 28 → 32, shadow prices 1 / 0 / 2; Stigler $39.93, optimum $39.69

1Convex sets and functionsBachelor's5 min

A set is convex if the segment between any two of its points stays inside it: a disc, a polygon, a half-plane; not a crescent. A function is convex if its chord between any two points lies above its graph. Equivalently, for a smooth function, every tangent lies below the graph. Or, with two derivatives, the Hessian, the matrix of second derivatives, is positive semidefinite everywhere: the curvature is never negative in any direction. Strong convexity asks for curvature bounded away from zero, which gives at most one minimizer. Existence and algorithmic rates require further conditions, such as smoothness and a suitable step size.

Here's a convex function, a smoothed hinge plus a little curvature, the kind of thing a logistic loss looks like. Any chord lies above it. Any tangent lies below it. And the tangent fact has the consequence that matters most for us: if the gradient is zero somewhere, the tangent there is flat, and the whole function lies above it. A stationary point of a convex function is its global minimum. No local traps.

The chord inequality with many points, weighted by probabilities, is Jensen's inequality: f of the mean is at most the mean of f. With x squared it says a variance is never negative. With minus log it says the average of logs is at most the log of the average. And applied to a likelihood ratio, it says the expected log likelihood is highest at the true distribution: the Kullback–Leibler divergence is never negative. That population comparison motivates maximum likelihood; consistency also needs identification and regularity, as Part 22 develops.

Statistics meets both kinds. On the left, the log likelihood of a logistic regression slope for the World's vote, eight hundred adults: concave, the negative of convex, with a single peak. On the right, the log likelihood for the centre of a Cauchy distribution, from seven observations in two clusters. It has two peaks, one near each cluster, with a valley between. An algorithm that only looks locally can climb the wrong one.

Why are exponential families safe? Write the density as h of x times the exponential of theta times T of x, minus a normalizing function A of theta, the log-partition function. Differentiating the normalization shows that A's first derivative is the mean of T and its second derivative is the variance of T, which can't be negative: A is convex. The log likelihood is theta times the sum of the T's, which is linear, minus n times A, which is convex, so it's concave. If a finite interior maximum exists, its score matches the model mean of T to the sample mean. Minimality can make it unique. Boundary data can instead lead to an unattained supremum.

Convexity makes local minima global. Whether an algorithm converges, and its speed, still depend on its assumptions and step choices. If the curvature is everywhere between m and L, their ratio kappa is the condition number: one for a round bowl, huge for a long thin valley. Gradient descent with step one over L then has an objective-gap upper bound decreasing by a factor of one minus one over kappa per step. With kappa ten, that's a tenfold reduction of this objective-gap bound in about twenty-two steps; with kappa ten thousand, every twenty-three thousand. In statistics a large kappa usually comes from predictors on very different scales, or strongly correlated. Centring and scaling them rounds the bowl, and Newton uses curvature and is invariant to invertible linear reparameterizations in exact arithmetic, but ill-conditioned linear solves and poor starting points can still cause difficulty. Chapter five shows both.

Which statistical problems are convex? Exponential families, written in their natural parameter, have concave log likelihoods, because the log-partition function is convex. So canonical logistic and Poisson regressions have concave log likelihoods. Concavity does not ensure that a finite MLE exists: separation is one counterexample. So are ridge, the lasso and quantile regression. Mixtures, heavy-tailed location models, factor models and neural networks are not. For those we use several starting points, and some humility about whether we found the best answer.

Numbers: Cauchy peaks −1.28, 4.0; κ = 10: 22 steps per digit

2Lagrange and KKTMaster's4 min

Lagrange multipliers, and the Karush–Kuhn–Tucker conditions. The simplest constrained estimator: the probabilities of K categories, from counts n k. The log likelihood is the sum of n k log p k, but the p's must add to one. Lagrange's idea: add the constraint with a price lambda, and optimize freely. With positive counts, the optimum is interior: setting each derivative to zero makes n k over p k the same multiplier. Zero counts require the corresponding boundary conditions. The constraint fixes lambda at n, and the estimates are the sample proportions, as everyone guessed, now derived.

Inequality constraints are subtler. Suppose theory says a probability can't exceed a half. On the left, thirty successes in fifty trials: the unconstrained estimate, point six, is outside the allowed region, so the constrained maximum sits on the boundary, at a half. There the likelihood is still rising, with slope twenty: that slope is the multiplier, the price the constraint is charging. On the right, twenty in fifty: the estimate, point four, is inside the region. The constraint doesn't bind, and its multiplier is zero. A slack constraint must have multiplier zero, and a positive multiplier requires a binding constraint. A binding constraint can also have multiplier zero. That is complementary slackness.

In general, to minimize f subject to constraints g i of x at most zero, Karush in 1939 and Kuhn and Tucker in 1951 gave four conditions. Stationarity: the gradient of f is balanced by the constraints' gradients, weighted by multipliers mu. The constraints hold. The multipliers are non-negative. And complementary slackness: each multiplier is zero unless its constraint is binding. At an optimum, necessity requires an appropriate constraint qualification. For differentiable convex objectives and constraints, satisfying the KKT conditions is sufficient for global optimality.

The lasso's KKT conditions explain its zeros. The absolute value has no derivative at zero, but it has a subgradient, any number between minus one and one. Stationarity says each predictor's correlation with the residual equals lambda times s j. If the coefficient is non-zero, s j is its sign, so the correlation is exactly plus or minus lambda. If it's zero, s j can be anything in between. A zero coefficient requires absolute residual inner product divided by n at most lambda. Strictly below lambda forces a zero; at equality, the coefficient can be zero or non-zero: Part 19's diamond corners, as an equation.

A constraint that's common in practice: a relationship known to go one way. In the World, support for Blue rises with income. Here are fifteen hundred adults in twenty-five income bins, and the share voting Blue in each. Sampling noise makes the raw shares dip eight times. Isotonic regression finds the closest non-decreasing fit, least squares subject to the order constraints. Its KKT conditions lead to a simple algorithm: pool adjacent violators. Whenever two neighbours are in the wrong order, replace both by their weighted average, and repeat. The result is a staircase, close to the World's truth, with no assumption about its shape except that it never falls.

Constraints are everywhere in statistics: probabilities that add to one, means known to be ordered, which isotonic regression handles. Sometimes the best estimate sits on a boundary: a variance component of zero, a probability of one. There the usual chi-squared theory of tests breaks down, a subject for Parts 46 and 47. Under suitable sensitivity regularity, a multiplier gives the local derivative of the optimal value when the constraint is relaxed, the shadow price of the bakery.

Numbers: multipliers 20 and 0; PAVA: 8 dips, 12 blocks

3DualityMaster's4 min

Every constrained problem, the primal, has a partner. Put prices mu on the constraints and minimize without them: the result, as a function of the prices, is the dual function. For any non-negative prices it's a lower bound on the true minimum, since at a feasible point the penalty terms can only help. For convex problems, under a mild condition, the best lower bound is exact: maximizing the dual gives the same value as minimizing the primal. That's strong duality.

The bakery's dual is a story about prices. Suppose a buyer wants to rent the bakery's flour, oven and staff. She must offer prices high enough that each kind of tray is worth no more than its ingredients, or the baker would rather bake it, and she wants to pay as little as possible in total. Her best prices are one for flour, nothing for the oven, two for staff, and the total, fourteen plus eighteen, is thirty-two: exactly the best profit. The oven, which wasn't fully used, gets a price of zero: complementary slackness again.

Now Dantzig's homework. A test, on a finite set of possible outcomes, is a function phi: the probability of rejecting when x is observed. Its power is the sum of phi times the alternative's probabilities. Its size, the sum of phi times the null's probabilities, must be at most alpha, and each phi is between zero and one. Everything is linear in phi: the most powerful test is the solution of a linear program. And the KKT conditions solve it. Each outcome is a good buy if its power per unit of size, the likelihood ratio, beats the price of size, k: reject where the ratio exceeds k, never where it falls short. That's the Neyman–Pearson lemma, with the critical value revealed as a Lagrange multiplier.

Here's the linear program solved numerically. Twenty trials; the null says the success rate is a half, in grey, the alternative point seven, in blue. Size five percent. The solver rejects for fifteen or more successes, and at exactly fourteen rejects with probability point seven nine, a randomized test, to use up the size exactly. Its power is fifty-seven percent, the best any level-five-percent test can do. And the solver's multiplier on the size constraint is five point one eight, which is precisely the likelihood ratio at fourteen. The lemma's k is a shadow price: the power you'd gain per unit of extra size.

Duality has a practical payoff: a certificate of how close we are. The lasso has a dual problem, and from any current estimate we can build a feasible dual point, the residual, scaled to satisfy the dual's constraint. The gap between the primal and dual values bounds how far the current objective is from the optimum, even though we don't know the optimum. Here it is falling as coordinate descent runs on two correlated predictors: a factor of ten every dozen or so updates, ten orders of magnitude in a hundred and twenty. A small feasible duality gap certifies objective accuracy. Software can also use other stopping rules; glmnet uses coordinate-update and KKT checks. No guessing about convergence.

Duality also changes how we compute. Ridge regression's solution involves a p by p matrix. Its dual form gives the same answer through an n by n matrix: the coefficient vector is X transposed times a vector alpha, one dual weight per observation. When there are more predictors than observations, the dual is the cheap one. And in the dual, a prediction depends on the data only through inner products between observations. Replace those inner products by a positive-semidefinite kernel and you have kernel ridge regression, a flexible nonlinear method fitted by a linear solve, which Parts 29 and 54 develop.

Numbers: 14 + 18 = 32; NP: power 0.568, φ(14) = 0.79, k = 5.18; gap 10⁻¹⁰ after 120 updates

4Linear programmingMaster's5 min

An early statistical optimization problem predates least squares. In 1757 Roger Boscovich, a Jesuit astronomer in Rome, wanted to know whether the Earth is flattened at the poles, as Newton predicted. If it is, a degree of latitude is longer near the poles. He had five measurements, from Quito to Lapland. His method minimized absolute errors with an additional balancing condition that their signed sum be zero. We will fit a modern unconstrained LAD line to these historical measurements, a different optimization problem. That was nearly fifty years before Legendre published least squares. Least absolute deviations resists outliers, but has no formula. Its solution is a linear program.

Here are Boscovich's five arcs, in toises per degree, against the squared sine of the latitude, which makes the theory a straight line. The least-squares line, in blue, has slope seven hundred and twenty-five. The least-absolute-deviations line, in red, has slope eight hundred, and it passes exactly through two of the five points, Quito and Lapland. That's no accident: with full column rank, a basic optimal LAD solution can interpolate two independent design rows. Not every optimum must do so when solutions are nonunique. Here its total absolute error, three hundred and twenty-seven, beats least squares' three hundred and forty-nine. Either way, the degrees lengthen toward the poles. Newton was right.

Why a linear program? The sum of absolute residuals has a kink at every data point, so ordinary differentiability fails, though subgradients still characterize an optimum. But split each residual into a positive part u and a negative part v: the problem becomes minimizing the sum of u plus v, subject to linear equalities and signs, which is linear. The vertices of this LP are fits passing through p of the data points, which explains why our modern LAD line hits two observations. Boscovich's original method also imposed a zero-sum residual constraint. Laplace found an algorithm for the two-parameter case in 1793, Edgeworth generalized it, and Barrodale and Roberts built a fast simplex method for it in 1973; modern solvers use both simplex and interior-point methods. Our SciPy HiGHS call can select dual simplex.

A curious fact about the simplex method: it's fast on almost every problem anyone meets, yet it can be exponentially slow. Victor Klee and George Minty built a squashed cube in 1972 on which Dantzig's rule visits every one of its two to the n corners. In 1984 Narendra Karmarkar found a method guaranteed to take polynomial time, which travels through the interior of the polytope instead of along its edges. For large quantile regressions, Stephen Portnoy and Roger Koenker showed in 1997 that interior-point methods beat the simplex handily, and interior-point algorithms are important in modern quantile software, alongside simplex and specialized methods.

Tilt the absolute value and you get every quantile. The check function charges tau times a positive residual and one minus tau times a negative one. At tau one half it's half the absolute value, and its minimizer is the median. At tau point nine, under-predicting costs nine times as much as over-predicting, so the minimizer moves up toward the ninetieth percentile. With finite samples or ties, the fraction strictly below need not be exactly ninety percent. Minimizing the check loss gives the tau quantile, and minimizing it over regression lines gives Roger Koenker and Gilbert Bassett's quantile regression, from 1978, still a linear program.

The classic example: Ernst Engel's two hundred and thirty-five Belgian working-class households of 1857, their income and what they spent on food. Five quantile regression lines, each a linear program: the tenth, twenty-fifth, fiftieth, seventy-fifth and ninetieth percentiles of food spending at each income. Their slopes rise from point four zero to point six nine: the lines fan out, because spending varies more among richer households, something a single least-squares line hides. These fitted lines have positive intercepts. Dividing a plus b times income by income gives a over income plus b, which decreases with income when a is positive. That is the food-share pattern associated with Engel's law; a slope below one alone would not imply it. The least-squares line, dashed, is pulled toward the few richest households.

So least absolute deviations and quantile regression are linear programs, for which a basic optimum can interpolate p independent rows under full-rank regular conditions; nonunique optimal fits can behave differently. They resist outliers in the response, though not in the predictors, which is Part 30's subject. Together, quantile regressions describe the whole conditional distribution, not just its mean. Their standard errors involve the density at the quantile, which Part 47's asymptotics will explain.

Numbers: Boscovich: LAD slope 800 vs 725, errors 327 vs 349; Engel slopes 0.40–0.69

5Newton and Fisher scoringMaster's5 min

Newton's idea: near the current guess, approximate the log likelihood by a quadratic, using its gradient g and its Hessian H, the matrix of second derivatives. Then jump straight to the quadratic's peak: theta minus H inverse g. Fisher's scoring method, from 1925, replaces the Hessian by minus the expected information, which is negative semidefinite. With nonsingular information it gives an ascent direction, but a full step can still overshoot; a line search or trust region safeguards the update. For logistic regression and any canonical link the two are identical, and each step is a weighted least squares fit: iteratively reweighted least squares, from Part 14.

Here's the log likelihood of a logistic regression of the World's vote on log income, two thousand adults, as contours over the intercept and slope. The peak sits at the end of a long, narrow ridge, because with an uncentred predictor the intercept and slope can trade off against each other. Gradient ascent, in red, always steps straight uphill. On a narrow ridge, uphill points mostly across the ridge rather than along it, so it creeps: after sixty steps it has covered about a quarter of the distance. Newton, in blue, knows the curvature, so it steps along the ridge. Five steps, and it's there.

Count the error after each step, the distance to the maximum. Newton starts four units away; then point four five; then point zero one two; then nine millionths; then five trillionths; then nothing a computer can measure. Near a regular optimum with a nonsingular Hessian, Newton has local quadratic convergence; this example roughly doubles its correct digits as it approaches the solution. Gradient ascent shrinks the error by a constant factor each step, and on this ridge the factor is close to one: after four hundred steps it's still point five eight away. The price of Newton is a linear system with the Hessian at each step, which for a few dozen parameters is nothing.

Newton can fail. Back to chapter one's Cauchy likelihood, with its two peaks, and start in the valley between them, at one point two. In the valley the curvature is positive, so the quadratic approximation is a bowl, and Newton jumps to the bottom of the bowl: it converges, quadratically, to point seven six, the lowest point of the valley. Newton looks for a zero of the gradient, and a minimum has one too. With a line search, which refuses any step that lowers the likelihood and falls back on the gradient when the curvature points the wrong way, it climbs instead, to three point nine nine. Here that's the higher peak. In general nothing local can promise the global one.

A close relative handles nonlinear least squares, fitting a curve like a growth model or a dose-response curve. The Hessian has two parts: J transposed J, built from first derivatives only, and a term weighted by the residuals, which is small near a good fit. Gauss–Newton drops the second. Each step is then an ordinary least-squares regression of the residuals on the Jacobian, exactly as Fisher scoring is a weighted least-squares fit. Levenberg and Marquardt add a multiple of the identity, which shortens the step when the linearization can't be trusted: large mu gives a cautious gradient step, small mu a bold Gauss–Newton step.

The standard repairs: a line search, which shrinks each step until the objective improves; a trust region, which trusts the quadratic only within a radius it adjusts as it goes, the Levenberg–Marquardt idea; quasi-Newton methods like BFGS, which build up the curvature from successive gradients without ever computing a Hessian; and several starting points for problems that aren't concave. Newton's real limit is cost: solving with a p by p matrix takes of order p cubed operations. With millions of parameters we need the cheaper methods of the coming chapters.

Numbers: errors 4.1 → 0.45 → 0.012 → 8.7e−6 → 4.5e−12; gradient 0.58 after 400; Cauchy 0.76 vs 3.99

6MM algorithmsMaster's4 min

MM stands for majorize, then minimize, a principle Kenneth Lange and others built into a general method. At the current point, build a surrogate function g that lies above f everywhere, and touches it at the current point. Minimize the surrogate, which is chosen to be easy, often a quadratic. Then f at the new point is at most the surrogate there, which is at most the surrogate at the old point, which equals f there. With an exact touching majorizer and a surrogate-reducing update, the objective cannot increase. Constructing the surrogate and solving the subproblem still require care.

The simplest example: the median of seven numbers, which minimizes the sum of absolute deviations, the blue curve with a kink at every data point. Each absolute value lies below a parabola that touches it at the current residual. Add them up and you have a smooth majorizer, in gold, touching the blue curve at the current guess, nine. Its minimum is a weighted mean, with weight one over each point's current distance, and that is the next guess. Nine, then seven point oh nine, then six point eight six, then six point seven six: each step downhill, on its way to the median, four.

Many famous algorithms turn out to be MM in disguise. The EM algorithm, the next part's main tool, is MM for maximization: the expected complete-data log likelihood plus the entropy of the current conditional latent distribution is a touching lower bound. The entropy term is constant in the new parameter and is essential to that bound. Hunter and Lange's algorithm for quantile regression uses the parabola trick we just saw. Weiszfeld's 1937 algorithm for the spatial median is the same weighted mean in two dimensions. And so is de Leeuw's SMACOF for multidimensional scaling, in Part 31.

Here's MM doing median regression on Engel's households, each step a weighted least squares fit. The linear program gives the exact optimum. MM's objective falls toward it, decreasing in this example, though not with Newton's local doubling of digits. The implementation uses a tiny smoothing epsilon, so its exact monotonicity theorem concerns a smoothed check loss; the original objective is shown here. That's the usual bargain: reliable, simple, and sometimes slow.

Another MM classic ranks competitors from their head-to-head results. Here's a toy season among four of the World's town teams, each pair meeting ten times. The Bradley–Terry model gives each team a strength g, and says team i beats team j with probability g i over g i plus g j. The update has a lovely form: a team's new strength is its total wins divided by a sum over its opponents. The log likelihood rises at every step. At the end, Harbour is the strongest, and would beat Quarry eighty-seven percent of the time. Ernst Zermelo proposed exactly this iteration for chess tournaments in 1929; David Hunter showed in 2004 that it's an MM algorithm, which explains likelihood ascent. A finite positive strength MLE also needs an adequately connected win network; the overall strength scale is unidentified and normalized here.

So MM algorithms are stable and monotone, with no step size to choose. Each step is something simple, a weighted mean or a least-squares fit. The cost is speed: convergence is often locally linear under suitable regularity, and can be painfully slow when the surrogate is much more curved than the function. The standard fixes are extrapolation schemes like SQUAREM, or switching to Newton once close.

Numbers: median 9 → 7.09 → 6.86 → 6.76; Bradley–Terry 2.92 / 1.10 / 0.71 / 0.44

7Coordinate descentMaster's4 min

Coordinate descent is the simplest idea of all: hold every variable fixed but one, minimize over that one exactly, and cycle. For the lasso each one-variable problem has a closed form: compute the correlation of predictor j with the residual that leaves it out, and soft-threshold it: shrink toward zero by lambda, and set it to zero if it doesn't get past. That's chapter two's KKT condition, solved one coordinate at a time. Paul Tseng proved in 2001 that this converges under regularity on the objective and coordinate minimizations, including separable penalties; the standard convex lasso with nonzero design columns and an attained optimum fits that framework.

Here's a lasso with just two predictors, correlated point eight four, so its contours are tilted ellipses with corners where they cross the axes. Coordinate descent, in gold, moves only horizontally or vertically: minimize over beta one, then beta two, then beta one again. The path is a staircase down the valley. Because the predictors are correlated, the valley runs diagonally, and the steps are short; there are many of them. The proximal gradient method of the next chapter, in red, takes diagonal steps instead. Both reach the same answer: beta two is shrunk almost to zero, beta one carries the signal.

How much does correlation slow it down? Here are the sweeps needed to reach a duality gap of ten to the minus eight, for two predictors with increasing correlation. Uncorrelated, five sweeps. At a correlation of point nine nine, six hundred and thirty-five. When predictors move together, each one-coordinate step undoes part of the other's progress, and the staircase steps shrink. The count grows roughly like one over one minus the correlation.

Coordinate descent became the standard way to fit the lasso for reasons that compound. Each update costs one inner product. Warm starts: you want the whole path of solutions as lambda decreases, and each solution is an excellent starting point for the next. Active sets: most coefficients are zero, so cycle over the few that aren't until they settle, then check the rest. Screening rules can rule out predictors in advance. Jerome Friedman, Trevor Hastie and Rob Tibshirani built these into glmnet in 2010, and it computes an entire regularization path in a small multiple of the cost of an individual fit in favorable problems. The speed depends on sparsity, correlations, tolerances and the lambda path.

But the separability condition matters. Here's a penalty on the difference between two coefficients, the kind the fused lasso uses, plus a pull toward the point one, one. Start at minus one, minus one, on the diagonal. Moving either coordinate alone opens a gap between them and pays the penalty, which outweighs the gain: every single-coordinate move goes uphill. Coordinate descent is stuck, though the minimum is at one, one, straight along the diagonal. The penalty couples the coordinates, so the theory doesn't apply. For the fused lasso we need a method that can split the problem differently: ADMM, in chapter nine.

Numbers: correlation 0.84; final (1.25, 0.10); sweeps 5 → 635

8Proximal methodsPhD4 min

Many penalties are simple even when they're not smooth. The proximal operator of a function g, at a point v, finds the point that keeps g small without straying far from v. For the lasso penalty it's soft thresholding, coordinate by coordinate. For the extended-valued indicator of a nonempty closed convex set, it is its unique Euclidean projection. And with no penalty, it does nothing.

Here's the lasso's proximal operator as a picture. Soft thresholding sets anything within one threshold of zero to zero, and moves everything else toward zero by the threshold. Compare hard thresholding, which keeps a value untouched if it's big enough and kills it otherwise. Soft thresholding is continuous: the soft-threshold map itself changes continuously with its input. Continuity of an entire fitted coefficient vector also needs suitable uniqueness and design conditions. For a penalty lambda times the count of nonzero coefficients, hard thresholding occurs at the square root of two t lambda. At the threshold, both zero and the original value minimize the proximal objective; this drawing chooses zero. That penalty isn't convex, which is why best-subset selection is computationally hard and the lasso is its convex stand-in, a story Part 32 continues.

Most penalized estimators are a smooth loss f plus a simple penalty g. The proximal gradient method takes a gradient step on the smooth part, with step one over L, where L bounds its curvature, then applies the penalty's proximal operator. For the lasso that's a gradient step on the least-squares loss followed by soft thresholding: ISTA, the iterative shrinkage-thresholding algorithm. For convex f with an L-Lipschitz gradient, closed proper convex g and an attained minimum, its objective gap has a worst-case one-over-k upper bound. A particular problem may converge faster.

Here's ISTA on a hard lasso: forty predictors, all strongly correlated, so the problem is badly conditioned. The objective error on a log scale against the iteration on a log scale: ISTA, in red, crawls, staying under its one-over-k bound. In green, FISTA: the same steps with momentum, from Amir Beck and Marc Teboulle in 2009. Its bound falls like one over k squared, and after four hundred steps it's three orders of magnitude closer than ISTA. It's not monotone: the momentum sometimes overshoots, and the error ripples, but the trend is what the theorem promises.

How does momentum help? Instead of stepping from the current point, FISTA first extrapolates along the direction it was already moving. Then it takes the usual proximal step from there. The extrapolation weight follows a specific sequence, rising toward one. Yurii Nesterov showed in 1983 that one over k squared is an optimal worst-case order for the general smooth convex first-order oracle class with bounded initial distance, as dimension is allowed to grow. Extra structure, including strong convexity, can permit faster rates.

The same recipe covers a zoo of penalties. The group lasso shrinks whole blocks of coefficients together. The nuclear norm of a matrix, for low-rank problems like filling in a matrix of ratings, has a proximal operator that soft-thresholds the singular values. Constraints become projections. And when the curvature bound L isn't known, a backtracking search finds a safe step.

Numbers: κ = 4,745; ISTA 0.0196, FISTA 1.5e−5 after 400

9ADMMMaster's4 min

The alternating direction method of multipliers. Some problems are hard only because two easy pieces are tangled together. ADMM untangles them: give each piece its own variable, x and z, and tie them with a linear constraint. Then alternate. Minimize over x, handling f alone, with a quadratic penalty pulling it toward agreement with z. Minimize over z, handling g alone. And update u, a scaled Lagrange multiplier that accumulates whatever disagreement remains, the price that drives the two toward agreement. The idea dates from the 1970s; Stephen Boyd and colleagues' 2011 survey made it a standard tool.

Chapter seven's stuck example was a fused lasso: fit a sequence b to data y, penalizing the absolute jumps between neighbours, so the fit is piecewise constant. Coordinate descent fails because the penalty couples neighbours. ADMM splits it: let z be the vector of differences. In terms of z the penalty is separable. The b-step is a linear system whose matrix is tridiagonal, solvable in linear time. The z-step is soft thresholding. Two easy steps, repeated.

Here's a signal with four levels and noise, a hundred and twenty points, simulated. With a small lambda the fused lasso follows the noise, with many small jumps. With lambda three it recovers the broad level pattern, with shrinkage and some remaining small jumps, the lasso's usual bias. With lambda twenty almost every jump costs too much, and the fit is nearly flat. Choosing lambda is Part 19's job, by cross-validation.

How quickly does it settle? Track the primal residual, the disagreement between z and the differences of b. It falls fast at first, then declines steadily. That's ADMM's character: a few digits of accuracy come quickly, many digits slowly. The blue curve is the dual residual, rho times the norm of D transposed applied to the change in z. A small primal residual alone does not certify optimality. Check both residuals against appropriately scaled tolerances, and relate numerical accuracy to the statistical task.

Here's the form that made ADMM famous for large data. Spread the data across M machines, give each its own copy of the coefficients, x m, and require every copy to equal a shared z. Each machine updates its own copy, using only its own data, all at the same time. The coordinator averages the copies and applies the penalty's proximal operator. And each machine updates its disagreement. Only coefficient and multiplier vectors are exchanged in this scheme. Those messages can still leak information; distributed computation alone is not a privacy guarantee.

ADMM's strength is that it turns one hard problem into a sequence of easy ones. The pieces can even live on different computers: each fits its own share of the data, and a consensus step averages them. It handles the generalized lasso, the graphical lasso for networks of variables, robust principal components and trend filtering. For the standard two-block convex formulation, closed proper objectives, an attained saddle point and adequately solved subproblems give convergence guarantees for fixed positive rho. Arbitrary nonconvex or multi-block extensions need separate analysis.

Numbers: λ = 0.5, 3, 20; residual 10⁻²·⁸ after 400

10Stochastic gradientMaster's5 min

In 1951 Herbert Robbins and Sutton Monro asked how to find the root of a function you can only measure with noise: the expected value of some H of theta and X. Their answer: after each new observation, nudge theta against its noisy reading, with a step a k. Classical step conditions require a divergent sum but a finite sum of squared steps. Stability, an appropriate root and controlled unbiased noise are also needed; the step conditions alone do not guarantee convergence. To find a median, for instance, move down by a step whenever the new observation is below the current guess, and up when it's above.

Here's the median of a stream of observations, centred on ten, starting from a guess of zero, with steps ten over k. The early steps are big, and the guess races up and overshoots. Then the steps shrink and it settles on ten. And it never stores the data: one number, updated as each observation arrives. That's why the idea now trains models on data sets too big to hold in memory.

Stochastic gradient ascent applies the same idea to a likelihood: after each observation, step in the direction of that one observation's gradient, here for logistic regression. Each step costs almost nothing. We use steps of k to the minus point six, larger than one over k, so the estimate gets to the right region quickly. The price is that the latest estimate is noisy: it's always reacting to the most recent observation.

Here's one pass over twenty thousand of the World's adults, estimating the slope of the vote on log income. The gold band is the maximum likelihood estimate from all the data, with its ninety-five percent interval. In red, SGD's latest estimate, wandering. In green, the plain average of every estimate so far. It's smoother, and it settles inside the band. Boris Polyak and Anatoli Juditsky, and independently David Ruppert, proved something remarkable about this average: under stability, smoothness and nonsingular curvature, with independent observations and step exponents strictly between one half and one, averaging can match the asymptotic variance of the corresponding estimating-equation solution. Under a correctly specified likelihood that is MLE efficiency; under misspecification it involves a sandwich variance. A finite stream is not itself an asymptotic guarantee.

The step sizes matter. Thirty streams of five thousand adults, one pass each, measuring how far the final answer is from the exact maximum likelihood estimate, for step exponents from a half to one. The last iterate, in red, does best around point eight, and even then is about half a standard error away. The average, in green, does best with the biggest steps, exponents near a half, where it lands within a third of a standard error of the MLE. The half-exponent endpoint is a finite-sample comparison, outside the classic square-summable-step condition. In these streams, with this step constant and starting point, one over k is too timid for both: the steps shrink too fast to get there in one pass. Averaging lets you take bold steps and then smooths away their noise.

Modern practice adds refinements. Minibatches average the gradient over a handful of observations, cutting its variance and using hardware well. Momentum accumulates a running direction. Adam, introduced by Diederik Kingma and Jimmy Ba, also uses first and second gradient moments to adapt parameter-wise steps. SVRG uses periodic full gradients, while SAGA maintains a table of past component gradients. Under suitable smooth strongly convex finite-sum conditions, such variance reduction can yield linear convergence; it is not a blanket guarantee for deep networks. Training usually makes several passes over the data, called epochs. These are the workhorses of deep learning, which Part 64 takes up.

The Board checks the claim. Five hundred streams of two thousand adults; after one pass, a Wald interval of plus or minus one point nine six standard errors, computed at the estimate. Using the last iterate: eighty-two percent coverage, broken, because the last iterate carries optimization noise the standard error doesn't know about. Using the Polyak–Ruppert average: ninety-three percent, within this Board's tolerance. The target is the exact finite-World logistic projection, not a sampled reference. Five hundred replicates assess this one procedure and setting; they do not prove nominal coverage or the general efficiency theorem.

Numbers: Robbins–Monro 9.98; MLE 0.579 (SE 0.016); Board 81.6% / 93.0%

11Optimization and inferencePractice5 min

The optimizer doesn't just find the estimate; it measures its uncertainty. At the maximum, the negative Hessian of the log likelihood is the observed information, and under a correctly specified regular likelihood with nonsingular information, its inverse estimates the estimator's covariance: a sharply curved peak means a precise estimate, a flat one an uncertain estimate, as Part 9 showed in one dimension. For the World's vote, the slope's standard error from the curvature is point one eight three; a bootstrap gives point one nine six. And A final Hessian is already closely related to Newton's calculation, though constructing or inverting it still has a cost and its inferential interpretation requires the model assumptions.

Here's what that means in a picture: a profile logistic log likelihood for the slope, reoptimizing the nuisance intercept at each slope. A fixed-intercept slice would understate uncertainty. In gold, the quadratic Newton fits at the top. Its curvature gives the standard error. The ninety-five percent Wald interval is where the quadratic has fallen by one point nine two, half of three point eight four, the chi-squared critical value. Using the real curve instead of its quadratic gives the likelihood-ratio interval, which can capture asymmetry under regular likelihood assumptions. Disagreement alone does not guarantee that its finite-sample coverage is better. Part 22 goes deeper.

That gives a natural place to stop. Here's gradient ascent's distance from the exact maximum, falling as it runs. In gold, the estimate's standard error: the size of its statistical uncertainty. Once the optimization error is a tenth of that, after about a thousand iterations here, its magnitude is small on the statistical scale in this example. Numerical error need not be independent or mean-zero, so there is no general rule that it adds in quadrature or raises the standard error by half a percent. Going further computes more digits of a number we only know to plus or minus point one eight. Léon Bottou and Olivier Bousquet made this trade-off precise for large data in 2008: under an appropriate error-budget analysis, allocating computation to more data can be preferable to solving a smaller problem far more accurately than inference needs. In practice, the exact optimum is unknown: gradient, decrement or dual-gap criteria supply computable accuracy checks.

One warning before the next part. The curvature, A, gives the variance only if the model is right. In general we also need B, the spread of each observation's score, its pull on the estimate. For independent observations and regular estimating equations, the sandwich A inverse B A inverse estimates asymptotic covariance under misspecification. The information identity holds in expectation under correct specification, not as an exact equality of finite-sample score sums. For the World's vote, modelled on income alone though age and region matter too, the curvature-based standard error is point zero five zero eight, the sandwich point zero five one three, and the actual spread over four hundred samples point zero four nine seven: here they agree. Part 22 shows a model wrong enough that they don't.

The shape of the problem also warns us. A weakly curved regular direction can give a large standard error. An exactly flat, nonidentified direction instead invalidates the usual inverse-information approximation. A long ridge, like chapter five's, means strongly correlated estimates, which appropriate centring and scaling can reduce. In logistic regression, information uses fitted-probability weights; ordinary mean centring need not remove the correlation completely. Failure to converge can indicate nonidentification or a boundary, but poor scaling, initialization or an unsuitable algorithm can also cause it. In logistic regression, if a predictor separates the outcomes perfectly, the maximum is at infinity, and the iterations march off forever. The optimizer's struggles are diagnostics.

So: the estimate is the optimum; curvature supports uncertainty calculations under regular likelihood assumptions, with sandwich corrections when needed; the accuracy worth having is a fraction of that uncertainty; and the landscape's shape tells us when something is wrong.

Numbers: SE 0.183 vs bootstrap 0.196; 1,013 iterations to SE/10; sandwich 0.0513

Recap, problems, and the road aheadAll tracks3 min

Part twenty-one in fourteen lines. Dantzig's homework led to linear programming and the simplex method. Convex problems have no local traps, and Jensen's inequality shows why likelihood works. Lagrange multipliers and the KKT conditions handle constraints, with complementary slackness; duality turns constraints into prices, and the Neyman–Pearson lemma into a linear program whose multiplier is the critical value. Least absolute deviations and quantile regression are linear programs. Near a regular optimum, Newton can have quadratic convergence; MM algorithms never go uphill; coordinate descent powers the lasso; FISTA's momentum turns one over k into one over k squared; ADMM splits hard problems into easy ones. Averaged stochastic gradient has strong asymptotic guarantees under explicit regularity and step assumptions; the Board illustrates one finite-sample setting. Curvature supports regular likelihood inference, while misspecification requires more than the Hessian alone.

Where it comes back. Part 22 makes the EM algorithm the centre of likelihood computation. Part 24 uses iteratively reweighted least squares for every generalized linear model. Part 25 optimizes over variance components. Part 27's Bayesian computation is optimization's cousin. Part 32 proves when the lasso finds the truth. Part 54 studies empirical risk minimization. Part 61's optimal transport is a linear program between distributions. And Part 64 trains neural networks with stochastic gradient.

Six problems, with full solutions in the README. The concavity of the logistic likelihood; maximum entropy, which produces an exponential family; the bakery's dual; Newton's quadratic convergence for an exponential rate, and when it fails; the soft-threshold operator; and the step size Robbins–Monro needs. Pause here if you want to try them.

The books this part follows: Boyd and Vandenberghe's Convex Optimization, Kenneth Lange's books on optimization and MM, Nocedal and Wright's Numerical Optimization, and Koenker's Quantile Regression; with the papers from Dantzig and Wald to Polyak and Juditsky.

Twenty-one parts of sixty-five, the first of the master's. We have a collection of algorithms for many estimators, and know that interpreting their curvature requires statistical assumptions. Next, the likelihood itself. In 1894 Karl Pearson tried to split a thousand crabs from Naples into two species by solving a ninth-degree polynomial. Maximum likelihood and the EM algorithm do it better, and a wrong model gets a sandwich. Part 22: likelihood in depth.

Where it goes next. EM, the likelihood's curvature and the sandwich are taken up in Part 22; IRLS becomes the engine of every GLM in Part 24; optimizing over variance components is Part 25; the lasso's theory is Part 32, empirical risk minimization Part 54 and optimal transport as a linear program Part 61.

Key results

The part's results in one place, for revision.

KKT conditions\(\displaystyle \nabla f(x^*)+\sum_i\lambda_i\nabla g_i(x^*)=0,\quad\allowbreak g_i(x^*)\le 0,\quad\allowbreak \lambda_i\ge 0,\quad\allowbreak \lambda_i\,g_i(x^*)=0\)
Weak duality\(\displaystyle \max_{\lambda\ge 0}\,\min_x L(x,\lambda)\;\le\;\min_x\,\max_{\lambda\ge 0}L(x,\lambda),\qquad\allowbreak L(x,\lambda)=f(x)+\sum_i\lambda_i g_i(x)\)
Fisher scoring for logistic regression\(\displaystyle \beta^{+}=\beta+(X^\top WX)^{-1}X^\top(y-p),\qquad\allowbreak W=\operatorname{diag}\bigl(p_i(1-p_i)\bigr)\)
The MM descent property\(\displaystyle f(x_{k+1})\le g(x_{k+1}\mid x_k)\le g(x_k\mid x_k)=f(x_k)\)
Soft thresholding\(\displaystyle \operatorname{prox}_{\lambda|\cdot|}(v)=\arg\min_x\Bigl\{\lambda|x|+\tfrac12(x-v)^2\Bigr\}=\operatorname{sign}(v)\,(|v|-\lambda)_+\)
ISTA and FISTA\(\displaystyle F(b_k)-F^*\le\frac{L\,\|b_0-b^*\|^2}{2k}\ \text{(ISTA)},\qquad\allowbreak F(b_k)-F^*\le\frac{2L\,\|b_0-b^*\|^2}{(k+1)^2}\ \text{(FISTA)}\)

Try it

Lab 21 · ISTA against FISTA, with a certificate

Fit a 40-predictor lasso with correlated columns by proximal gradient with and without Nesterov's momentum, check both against their 1/k and 1/k^2 bounds, and verify the optimum by its KKT conditions and duality gap.

Figure produced by Lab 21: ISTA against FISTA, with a certificate
Produced by the lab below, seed 0, in 0.7 s.
python -m videos.stats.labs 21 needs numpy, scipy, matplotlib · download lab21.py · source on GitHub
condition number of X'X/n                    1291
non-zero coefficients at the optimum         8 of 40
KKT on the support: max | |x_j'r/n| - lam |  9.6e-16   (theory 0)
KKT off the support: max |x_j'r/n|           0.0985   (must be <= lam = 0.1)
duality gap at the optimum                   1.6e-15
ISTA after 50 steps: error, gap              1.00e-01, 2.61e-01   (the gap bounds the error)
error after 400 steps: ISTA                  1.78e-03   (bound 9.77e-02)
error after 400 steps: FISTA                 1.08e-06   (bound 9.72e-04)

Both methods stay under their worst-case bounds, momentum buys orders of magnitude at the same cost per step, and the duality gap certifies an answer without knowing the optimum.
The code (81 lines; it asserts its own result)
"""Lab 21: solve one lasso by ISTA and by FISTA, and certify the answer with KKT and the duality gap."""

import numpy as np

from videos.coursekit import labs
from explainer.stats.kit import optim

TITLE = "ISTA against FISTA, with a certificate"
GOAL = ("Fit a 40-predictor lasso with correlated columns by proximal gradient with and without Nesterov's momentum, "
        "check both against their 1/k and 1/k^2 bounds, and verify the optimum by its KKT conditions and duality gap.")
TASKS = [
    "Raise the correlation rho from 0.9 to 0.99. How do the condition number and the two error curves change?",
    "Replace ISTA by coordinate descent (optim.cd_lasso) and plot its error per sweep on the same axes.",
    "Set lam = 0, where the problem is least squares. Which of the KKT rows changes, and what happens to the gap?",
]


def run(seed=0):
    rng = np.random.default_rng(seed)
    n, p, rho, lam, iters = 100, 40, 0.9, 0.1, 400
    z = rng.standard_normal((n, p))
    X = np.empty((n, p))
    X[:, 0] = z[:, 0]
    for j in range(1, p):  # AR(1) columns: neighbours correlate at rho
        X[:, j] = rho * X[:, j - 1] + np.sqrt(1 - rho ** 2) * z[:, j]
    X = (X - X.mean(0)) / X.std(0)
    beta = np.zeros(p)
    beta[[2, 11, 25]] = (2.0, -1.5, 1.0)
    y = X @ beta + rng.standard_normal(n)
    y = y - y.mean()

    ref = optim.cd_lasso(X, y, lam, sweeps=1500)  # the reference optimum, certified below
    b_star, f_star = ref["b"], ref["objective"][-1]
    gap = optim.lasso_dual_gap(X, y, b_star, lam)["gap"]
    grad = X.T @ (y - X @ b_star) / n
    on = b_star != 0
    ista = optim.ista(X, y, lam, iters=iters)
    fista = optim.ista(X, y, lam, iters=iters, accelerate=True)
    L = ista["L"]
    eig = np.linalg.eigvalsh(X.T @ X / n)
    k = np.arange(1, iters + 1)
    d2 = float(b_star @ b_star)  # ||b_0 - b*||^2 from the start b_0 = 0
    err_i, err_f = ista["objective"][1:] - f_star, fista["objective"][1:] - f_star
    bound_i, bound_f = L * d2 / (2 * k), 2 * L * d2 / (k + 1) ** 2
    mid = optim.lasso_dual_gap(X, y, ista["path"][50], lam)["gap"]

    lab = labs.Lab()
    lab.row("condition number of X'X/n", f"{eig[-1] / eig[0]:.0f}")
    lab.row("non-zero coefficients at the optimum", f"{on.sum()} of {p}")
    lab.row("KKT on the support: max | |x_j'r/n| - lam |", f"{np.abs(np.abs(grad[on]) - lam).max():.1e}   (theory 0)")
    lab.row("KKT off the support: max |x_j'r/n|", f"{np.abs(grad[~on]).max():.4f}   (must be <= lam = {lam})")
    lab.row("duality gap at the optimum", f"{gap:.1e}")
    lab.row("ISTA after 50 steps: error, gap", f"{err_i[49]:.2e}, {mid:.2e}   (the gap bounds the error)")
    lab.row(f"error after {iters} steps: ISTA", f"{err_i[-1]:.2e}   (bound {bound_i[-1]:.2e})")
    lab.row(f"error after {iters} steps: FISTA", f"{err_f[-1]:.2e}   (bound {bound_f[-1]:.2e})")
    lab.note = ("Both methods stay under their worst-case bounds, momentum buys orders of magnitude at the same cost "
                "per step, and the duality gap certifies an answer without knowing the optimum.")
    assert 0 <= gap < 1e-9, "the reference is optimal to nine digits"
    assert np.all(np.sign(grad[on]) == np.sign(b_star[on])) and np.abs(np.abs(grad[on]) - lam).max() < 1e-6, "KKT on"
    assert np.abs(grad[~on]).max() <= lam + 1e-9, "KKT off the support"
    assert np.all(err_i <= bound_i + 1e-12) and np.all(err_f <= bound_f + 1e-12), "the 1/k and 1/k^2 bounds hold"
    assert np.all(np.diff(ista["objective"]) <= 1e-12), "ISTA is a descent method"
    assert err_f[-1] < err_i[-1] / 20, "momentum wins"
    assert mid >= err_i[49] - 1e-12, "the duality gap bounds the suboptimality"

    fig, ax = labs.figure(2, size=(11, 4.2))
    floor = 1e-14
    ax[0].loglog(k, np.maximum(err_i, floor), color=labs.BLUE, label="ISTA")
    ax[0].loglog(k, np.maximum(err_f, floor), color=labs.GOLD, label="FISTA")
    ax[0].loglog(k, bound_i, color=labs.BLUE, ls="--", lw=1, label="bound L d² / 2k")
    ax[0].loglog(k, bound_f, color=labs.GOLD, ls="--", lw=1, label="bound 2 L d² / (k+1)²")
    ax[0].set(title="Objective error against its bound", xlabel="step k", ylabel="F(b_k) − F*")
    ax[0].legend()
    idx = np.arange(p)
    ax[1].bar(idx - 0.2, beta, width=0.4, color=labs.MUTED, label="truth")
    ax[1].bar(idx + 0.2, b_star, width=0.4, color=labs.GREEN, label="lasso optimum")
    ax[1].set(title=f"The optimum: {on.sum()} of {p} coefficients are non-zero", xlabel="predictor j",
              ylabel="coefficient")
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Raise the correlation rho from 0.9 to 0.99. How do the condition number and the two error curves change?
  2. Replace ISTA by coordinate descent (optim.cd_lasso) and plot its error per sweep on the same axes.
  3. Set lam = 0, where the problem is least squares. Which of the KKT rows changes, and what happens to the gap?

Problems, with solutions

Try each problem before opening its solution.

1. Logistic concavity. Show that the logistic log likelihood has Hessian \(-X'WX\), \(W = \operatorname{diag}(p_i(1 - p_i))\), so it is concave.

Solution

ℓ(β) = Σ[yᵢxᵢ'β − log(1 + e^{xᵢ'β})], so ∇ℓ = Σ(yᵢ − pᵢ)xᵢ and ∇²ℓ = −Σpᵢ(1 − pᵢ)xᵢxᵢ' = −X'WX. For any v, v'X'WXv = Σ pᵢ(1 − pᵢ)(xᵢ'v)² ≥ 0, so the Hessian is negative semidefinite and ℓ is concave. It is strictly concave if X has full column rank.

2. Maximum entropy. Maximize the entropy \(-\sum_k p_k \log p_k\) subject to \(\sum_k p_k = 1\) and \(\sum_k k\,p_k = \mu\): show \(p_k \propto e^{-\lambda k}\).

Solution

The Lagrangian is −Σp log p − α(Σp − 1) − λ(Σkp − μ). Setting ∂/∂p_k = −log p_k − 1 − α − λk = 0 gives p_k = e^{−1−α}e^{−λk} ∝ e^{−λk}, with α and λ fixed by the two constraints. This is an exponential family with sufficient statistic k when a normalizable interior solution exists. On a finite support an interior feasible mean gives this form; boundary constraints can force zeros or degenerate support with no finite multiplier. On infinite support, feasibility, existence and a finite normalizing constant must also be checked.

3. The bakery's dual. Write the dual of the bakery's LP and check that \(y = (1, 0, 2)\) is feasible and optimal.

Solution

min 14y₁ + 24y₂ + 9y₃ subject to y₁ + 3y₂ + y₃ ≥ 3, 2y₁ + 2y₂ + y₃ ≥ 4, y ≥ 0.

  • Feasibility of y = (1, 0, 2). 1 + 0 + 2 = 3 ≥ 3 and 2 + 0 + 2 = 4 ≥ 4.
  • Optimality. Its value is 14 + 18 = 32, the primal value, so by weak duality both are optimal.
  • Complementary slackness. The oven constraint is slack at x = (4, 5) (3·4 + 2·5 = 22 < 24), and y₂ = 0.

4. Newton for an exponential rate. Newton for an exponential rate: show \(\lambda_1 - \hat\lambda = -\bar x(\lambda_0 - \hat\lambda)^2\). When does it go negative?

Solution

ℓ(λ) = n log λ − λS, so ℓ' = n/λ − S and ℓ'' = −n/λ². Newton gives λ₁ = λ₀ − ℓ'/ℓ'' = 2λ₀ − λ₀²x̄. With λ̂ = 1/x̄, λ₁ − λ̂ = −x̄(λ₀ − λ̂)²: the error is squared at each step (quadratic convergence). λ₁ < 0 when λ₀ > 2/x̄ = 2λ̂: a start more than twice the answer jumps to an impossible rate.

5. The proximal operator of λ|x|. Derive the proximal operator of \(\lambda|x|\): soft thresholding.

Solution

Minimize λ|x| + (x − v)²/2.

  • For x > 0. The derivative λ + x − v vanishes at x = v − λ, which is valid if v > λ.
  • For x < 0. Symmetrically, x = v + λ if v < −λ.
  • Otherwise. The minimum is at the kink, x = 0, since 0 ∈ λ[−1, 1] − v exactly when |v| ≤ λ.

Together: x = sign(v)(|v| − λ)₊.

6. Robbins–Monro step size. Robbins–Monro for a median with steps \(a/k\): why \(a > 1/(2f(\theta^*))\)? The bound for \(N(10, 3^2)\).

Solution

Near θ*, M(θ) ≈ f(θ*)(θ − θ*), so the recursion behaves like e_{k+1} ≈ (1 − a f/k)e_k + noise/k.

  • The noise term. It contributes variance of order Σ a²/j² × Π(1 − af/i)², which is O(1/k) only if af > 1/2. At af = 1/2 the variance is O(log k / k); for 0 < af < 1/2 it is O(k^{−2af}), with a comparable initial-error contribution, slower than the usual 1/k variance.
  • For N(10, 3²). f(10) = 1/(3√(2π)) ≈ 0.133, so a > 1/(2 × 0.133) ≈ 3.76; our a = 10 qualifies.
  • Optimal choice. a = 1/f(θ*) gives the optimal asymptotic variance, τ(1 − τ)/f² per observation.

Notes and sources

Where it comes back

Idea Returns in
EM; the likelihood in depth; the sandwich 22
IRLS for every GLM 24
mixed models: optimizing over variance components 25
Bayesian computation 27
the lasso's theory 32
empirical risk minimization 54
optimal transport as an LP 61
training neural networks 64
the Coverage Board every part; 65

Glossary

  • Convex set and function; strong convexity: segments stay inside; chords lie above; curvature bounded below by m > 0.
  • Condition number κ: L/m, the ratio of largest to smallest curvature; it sets first-order methods' rates.
  • Jensen's inequality: f(EX) ≤ Ef(X) for convex f.
  • Lagrangian; multiplier: the objective plus priced constraints; the price, a shadow price or sensitivity.
  • KKT conditions: stationarity, primal and dual feasibility, complementary slackness.
  • Subgradient: a slope that supports a non-differentiable convex function (for |x| at 0, anything in [−1, 1]).
  • Dual problem; weak and strong duality; duality gap: the problem over prices; its value bounds the primal's; equality at the optimum; primal minus dual.
  • Linear program; simplex method; interior-point method: linear objective and constraints; walking vertices; crossing the interior.
  • Least absolute deviations; check loss; quantile regression: Σ|r|; ρ_τ; minimizing Σρ_τ over regression lines.
  • Newton's method; Fisher scoring; IRLS; Gauss–Newton: quadratic models of the objective with the Hessian, the expected information, weighted least squares steps, or J'J.
  • Line search; trust region; quasi-Newton (BFGS): safeguards and Hessian approximations.
  • MM algorithm; majorizer; descent property: minimize a surrogate that lies above and touches; never increase.
  • Coordinate descent; warm start; active set: one variable at a time; solving along a λ path; cycling over non-zeros.
  • Proximal operator; ISTA; FISTA; Nesterov acceleration: penalized nearest point; gradient step plus prox; with momentum and an O(1/k²) worst-case objective-gap bound under convex smooth/composite assumptions.
  • ADMM; consensus: alternating updates of split variables with a running dual; parallel copies forced to agree.
  • Stochastic gradient; Robbins–Monro; Polyak–Ruppert averaging: one-observation steps; steps with Σa = ∞, Σa² < ∞; averaging iterates for asymptotic efficiency under stability, moment and regularity conditions (typically 1/2 < γ < 1).
  • Observed information; sandwich: −∇²ℓ at the optimum; A⁻¹BA⁻¹ when the model may be wrong.
  • Isotonic regression; PAVA: least squares under an order constraint; pooling adjacent violators.
  • Bradley–Terry model: P(i beats j) = gᵢ/(gᵢ + gⱼ).

Sources

  • History.
    • G. Dantzig, Ann. Math. Stat. 11 (1940); G. Dantzig & A. Wald, Ann. Math. Stat. 22 (1951).
    • G. Dantzig, "Linear programming", in Activity Analysis of Production and Allocation (1951).
    • G. Stigler, J. Farm Economics 27 (1945).
    • R. Boscovich (1757), as tabulated by S. Stigler, The History of Statistics (1986).
    • E. Zermelo, Math. Zeitschrift 29 (1929).
  • Methods.
    • W. Karush (1939); H. Kuhn & A. Tucker (1951).
    • R. Koenker & G. Bassett, Econometrica 46 (1978); S. Portnoy & R. Koenker, Stat. Sci. 12 (1997).
    • V. Klee & G. Minty (1972); N. Karmarkar (1984).
    • D. Hunter & K. Lange, JCGS 9 (2000); D. Hunter, Ann. Stat. 32 (2004).
    • P. Tseng, JOTA 109 (2001); J. Friedman, T. Hastie & R. Tibshirani, J. Stat. Software 33 (2010).
    • A. Beck & M. Teboulle, SIAM J. Imaging Sci. 2 (2009); Y. Nesterov (1983).
    • S. Boyd, N. Parikh, E. Chu, B. Peleato & J. Eckstein, Found. Trends ML 3 (2011).
    • H. Robbins & S. Monro, Ann. Math. Stat. 22 (1951); D. Ruppert (1988); B. Polyak & A. Juditsky, SIAM J. Control Optim. 30 (1992).
    • L. Bottou & O. Bousquet, NIPS (2008); D. Kingma & J. Ba (2014).
  • Books.
    • S. Boyd & L. Vandenberghe, Convex Optimization (2004).
    • K. Lange, Optimization (2nd ed., 2013) and MM Optimization Algorithms (2016).
    • J. Nocedal & S. Wright, Numerical Optimization (2nd ed., 2006).
    • R. Koenker, Quantile Regression (2005).
About this partfrom its README

Part 21 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the first part of Stage III, Master's. Almost every estimator in the course is the solution of an optimization problem. This part is about how those problems are solved, how fast, and what their shape says about the estimator.

It opens with George Dantzig, who in 1939 copied two open problems from Neyman's blackboard as homework and solved them. Both formed his 1946 doctoral thesis; one became the Dantzig–Wald generalized Neyman–Pearson lemma, whose mathematics is linear-programming duality. In 1947 Dantzig invented the simplex method. The World's bakery is a two-variable LP: the simplex walks (0, 0) → (0, 7) → (4, 5), for profits 0 → 28 → 32, with shadow prices of 1, 0 and 2. Stigler's 1945 diet problem was solved by Laderman in 1947 at $39.69 a year.

From there the part covers:

  • Convexity. Definitions; chords and tangents; Jensen and KL ≥ 0. A concave logistic likelihood beside a Cauchy likelihood with two peaks (−1.28 and 4.0). The log-partition function is convex, so exponential families have concave likelihoods. Condition numbers set gradient descent's linear rate: κ = 10 gives about 22 steps per factor-ten reduction of a standard objective-gap bound, κ = 10⁴ about 23,000, under the stated smoothness, strong-convexity and step assumptions.
  • Lagrange and KKT.
    • The multinomial MLE derived with a multiplier.
    • A binomial MLE under p ≤ ½: with 30/50 the constraint binds, multiplier 20; with 20/50 the multiplier is 0 (complementary slackness).
    • The four KKT conditions; the lasso's subgradient conditions.
    • Isotonic regression of the World's vote on income by PAVA: 8 dips in 25 bins pooled into 12 blocks.
  • Duality.
    • Weak and strong duality; the bakery's dual (14 + 0 + 18 = 32).
    • The Neyman–Pearson lemma as an LP on a binomial(20), 0.5 vs 0.7, at α = 0.05: reject at 15+, randomize 0.79 at 14, power 0.568. The multiplier k = 5.18 is the likelihood ratio at 14.
    • Ridge's dual and kernels.
    • The lasso's duality gap as a stopping certificate: ten orders of magnitude in 120 coordinate updates.
  • Linear programming.
    • A modern unconstrained LAD fit to Boscovich's five meridian arcs (1757), distinct from his historical fit with zero-sum signed errors: the LAD line passes through Quito and Lapland (slope 800, against 725 for least squares; absolute error 327 against 349).
    • LAD as an LP; Klee–Minty and Karmarkar.
    • The check function and quantile regression (Koenker & Bassett 1978). On Engel's 235 households the slopes run from 0.40 (τ = 0.1) to 0.69 (τ = 0.9), and the lines fan out.
  • Newton and Fisher scoring.
    • Logistic regression of the World's vote on uncentred log income, drawn on the likelihood's contours: Newton reaches the top in 5 steps (errors 4.1, 0.45, 0.012, 8.7 × 10⁻⁶, 4.5 × 10⁻¹²); gradient ascent is still 0.58 away after 400.
    • Plain Newton on the Cauchy likelihood converges to a minimum (0.76); with a line search it reaches the peak (3.99).
    • Gauss–Newton and Levenberg–Marquardt; remedies.
  • MM algorithms. Exact touching surrogates give descent; convergence and rates require further conditions.
    • The descent property; the median by quadratic majorizers (9 → 7.09 → 6.86 → …).
    • EM (including the current-posterior entropy term), IRLS, Weiszfeld and SMACOF as MM.
    • Smoothed median-regression MM on Engel against the LP optimum; original check-loss monotonicity here is observed, not a general smoothing guarantee.
    • Bradley–Terry strengths for a toy season by Zermelo's iteration (Hunter 2004): 2.92, 1.10, 0.71, 0.44, with P(Harbour beats Quarry) = 0.87.
  • Coordinate descent.
    • The soft-threshold update; a two-predictor lasso staircase on the objective's contours.
    • Sweeps to convergence grow from 5 to 635 as the correlation rises from 0 to 0.99.
    • glmnet's tricks; a non-separable penalty on which coordinate descent is stuck.
  • Proximal methods. Proximal operators, with soft and hard thresholding. ISTA vs FISTA on a 40-predictor lasso with condition number 4,745: errors 10⁻¹·⁷ vs 10⁻⁴·⁸ after 400 steps, under their 1/k and 1/k² bounds. Nesterov's optimal worst-case order for the general smooth convex first-order oracle class, with bounded initial distance. The displayed optimum is a high-accuracy numerical reference; the hard-threshold map shows its jumps and set-valued ties.
  • ADMM.
    • Splitting; the fused lasso on a four-level signal (λ = 0.5, 3, 20); both primal and dual residuals. A local banded solver factors the tridiagonal system once, with linear work per update.
    • Two-block convex ADMM needs regularity and a saddle point; distributed coefficient sharing alone is not a privacy guarantee.
  • Stochastic gradient.
    • Robbins–Monro for a median (10.0 from a start of 0).
    • SGD's last iterate against the Polyak–Ruppert average for the World's vote, 20,000 adults.
    • A finite step-exponent study: the average is closest to the MLE near γ = ½, at 0.29 model-based SE. The endpoint γ = ½ is outside the classic square-summable-step condition; this finite experiment is not an efficiency theorem.
    • Minibatches, momentum, Adam, SVRG and SAGA, distinguishing velocity, adaptive scaling and variance reduction.
    • Two Board rows.
  • Optimization and inference.
    • The observed information gives SE 0.183, against a bootstrap's 0.196.
    • A genuine profile likelihood over the intercept, its quadratic at the joint MLE and a marginal slope Wald interval.
    • Optimization error against statistical error: compare with SE/10, here first crossed after 1,013 iterations (Bottou & Bousquet). Deterministic algorithm error can bias an estimate; it cannot automatically be added in quadrature to sampling variance.
    • A sandwich preview: 0.0508 vs 0.0513, against a 400-replicate Monte Carlo SD of 0.0497. IID asymptotics and model assumptions are explicit.
    • Warnings read from the landscape.

Every number on screen is computed in compute.py:

  • Boscovich's arcs and Engel's households are the Museum's;
  • the vote is the World's survey block;
  • the rest are seeded simulations or worked examples.

Built in this part:

  • statkit.optim (explainer/stats/kit/optim.py), checked in tests/test_stats_kit_optim.py:
    • Newton with backtracking, and the Cauchy location likelihood;
    • Fisher scoring for logistic regression;
    • the check loss, Hunter–Lange MM and the LP for quantile regression;
    • a dense simplex method that records its vertex path;
    • the Neyman–Pearson LP;
    • soft thresholding, ISTA/FISTA, coordinate descent and the duality gap for the lasso;
    • ADMM for the lasso and the fused lasso (this part uses a local banded TV solver recording both residuals);
    • SGD with Polyak–Ruppert averaging and Robbins–Monro;
    • PAVA and Bradley–Terry MM.
  • The landscape (Landscape and marching_squares in explainer/stats/viz.py): level sets of any function or grid of two parameters, and optimizer paths across them.
  • The Museum: Boscovich's arcs (BOSCOVICH) and Engel's households (engel()).

The Coverage Board gains two rows: 95% model-based Wald intervals after one pass of SGD. The target is the logistic projection in the entire finite adult World (slope 0.5712857), computed from the census score equation. Income-only logistic specification is imperfect; its model-based curvature intervals need not have exactly 95% coverage even after accurate optimization.

Method Setting Reps Achieved Verdict
SGD last iterate, Wald CI logistic slope, the World's vote, n = 2,000 500 81.6% broken
Polyak–Ruppert average, Wald CI logistic slope, the World's vote, n = 2,000 500 93.0% kept
Chapter notes
# Chapter Numbers
0 Dantzig's homework, 1939 bakery 0 → 28 → 32, shadow prices 1 / 0 / 2; Stigler $39.93, optimum $39.69
1 Convex sets and functions Cauchy peaks −1.28, 4.0; κ = 10: 22 steps per digit
2 Lagrange and KKT multipliers 20 and 0; PAVA: 8 dips, 12 blocks
3 Duality 14 + 18 = 32; NP: power 0.568, φ(14) = 0.79, k = 5.18; gap 10⁻¹⁰ after 120 updates
4 Linear programming Boscovich: LAD slope 800 vs 725, errors 327 vs 349; Engel slopes 0.40–0.69
5 Newton and Fisher scoring errors 4.1 → 0.45 → 0.012 → 8.7e−6 → 4.5e−12; gradient 0.58 after 400; Cauchy 0.76 vs 3.99
6 MM algorithms median 9 → 7.09 → 6.86 → 6.76; Bradley–Terry 2.92 / 1.10 / 0.71 / 0.44
7 Coordinate descent correlation 0.84; final (1.25, 0.10); sweeps 5 → 635
8 Proximal methods κ = 4,745; ISTA 0.0196, FISTA 1.5e−5 after 400
9 ADMM λ = 0.5, 3, 20; residual 10⁻²·⁸ after 400
10 Stochastic gradient Robbins–Monro 9.98; MLE 0.579 (SE 0.016); Board 81.6% / 93.0%
11 Optimization and inference SE 0.183 vs bootstrap 0.196; 1,013 iterations to SE/10; sandwich 0.0513
12 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Dantzig's "homework" (1939). Dantzig & Wald (1951) on the Neyman–Pearson lemma; the simplex method (1947).
  2. Convex sets and functions. Jensen; first- and second-order conditions; strong convexity.
  3. Lagrange and KKT. Constrained MLEs; complementary slackness.
  4. Duality. The dual of least squares and of the lasso; the Neyman–Pearson lemma as an LP.
  5. Linear programming. Least absolute deviations (Boscovich, Laplace) and quantile regression as LPs; the simplex method, drawn.
  6. Newton and Fisher scoring. Quadratic convergence and when it fails; line search; trust regions.
  7. MM algorithms (Lange). Majorize–minimize; EM as MM (Part 22); IRLS as MM.
  8. Coordinate descent. Convergence for separable penalties; the lasso's soft-threshold update.
  9. Proximal methods. Proximal operators; ISTA and FISTA (Beck & Teboulle 2009), with rates.
  10. ADMM (Boyd et al. 2011). Splitting; the fused lasso.
  11. Stochastic gradient. Robbins–Monro (1951); Polyak–Ruppert averaging (asymptotically efficient!).
  12. Optimization and inference. The curvature at the optimum is the observed information; optimization error vs statistical error.
  13. Outro.

Built: statkit.optim. Books: Boyd & Vandenberghe; Lange Optimization; Nocedal & Wright.

Build the film

python -m videos.stats.stats21.compute        # the part's numbers, into .cache/stats21
python tools/build.py stats21                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats21 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/stats/stats21. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.stats.stats21.compute         # once (under a minute; cached in .cache/stats21)
python tools/build.py stats21 -q l             # fast 480p preview
python tools/build.py stats21                  # 1080p30 -> renders/stats21.mp4
python tools/qa_scene.py stats21 Newton
python tools/lecture_length.py stats21 --floor 50