← All examples

Machine Learning: Regularized & Kernel Learning

Two ideas run through this section, and they turn out to be the same idea seen twice.

The first is the penalty. Least squares has no unique answer when there are more predictors than observations, and a penalty supplies the missing constraint — but its shape decides what you get: an L2 penalty shrinks everything and zeroes nothing, an L1 penalty produces exact zeros and therefore selects. The second is the kernel, which lets a linear method act non-linearly by working with inner products in a space it never has to construct. Support vector machines are the classic instance; kernel ridge regression is the same trick applied to the penalty above.

Where they meet is Bayesian. A penalty is a prior — ridge is the MAP estimate under a Gaussian prior on the coefficients, lasso the MAP under a Laplace prior — and a kernel is a covariance function, which makes kernel ridge the posterior mean of a Gaussian process. So this section and the Bayesian Nonparametrics and Variable Selection sections are three views of one structure: the same regularisation appears as a penalty here, as a prior there, and as a posterior over which coefficients are nonzero in the third. A recurring theme is honesty about when any of it is needed — on data where n comfortably exceeds p, the penalties barely separate, and ridge can be very slightly worse than plain least squares.

Why the kernel trick is a theorem rather than a convenience. Saying a kernel lets you work in a space you never construct invites the obvious objection: if the feature space is infinite, why is the answer finite? The representer theorem is the reason. For any penalised fit of this kind, the optimal function provably lies in the span of the training points — it is a weighted sum of the kernel evaluated at the data you actually have, and nowhere else. So a model living in an infinite-dimensional space is determined by n numbers, and everything the fit needs about the feature space arrives through the Gram matrix: the n × n table of kernel values between every pair of observations. That is also the source of the cost that recurs in every example below — the Gram matrix is n2 entries and inverting it is n3, which is why the kernel examples subsample where the tree examples do not. What makes a function admissible as a kernel is Mercer’s condition: it must produce a positive semi-definite Gram matrix for any inputs, which is exactly the condition for it to be an inner product in some space and for the optimisation to be convex. The space it implies is a reproducing-kernel Hilbert space, and the penalty in these methods is a norm in that space — which is the sense in which a kernel method is still just a penalised linear fit.

The one kernel that does most of the work. Nearly every kernel below is the RBF, or radial basis function, sometimes called the squared-exponential or Gaussian kernel: similarity decays with distance, k(xx′) = exp(−γ∥x − x′∥2). Its single hyperparameter γ sets how fast that decay happens, and it is the whole model in one number. Small γ means similarity reaches a long way, so the fitted function is smooth and the method behaves almost linearly; large γ means only near-neighbours count, and the boundary can wrap around individual points. It is the same quantity a Gaussian process calls the inverse squared length-scale, which is one more place the two vocabularies describe one object — and the reason a kernel machine and a GP posterior mean land on the same number here, 0.612 against 0.611.

Choosing how much to penalise. The penalty strength λ is not estimated from the fit — it is chosen from outside, almost always by cross-validation, and the curve it produces is flatter near its bottom than people expect. Two conventions matter. The one-standard-error rule, which is glmnet’s default, does not take the λ that minimises the curve but the largest λ whose error is still within one standard error of that minimum — deliberately over-penalising, on the grounds that the minimum is itself a noisy estimate and the simpler model is the safer bet. And effective degrees of freedom turn a value of λ into something interpretable: for ridge it is the sum of dj2 / (dj2 + λ) over the design’s singular values, running from p at λ = 0 down toward zero, so it answers “how many parameters am I really fitting?” in a way the raw λ never does.

Reading the numbers. Three scores recur. AUC, the area under the receiver-operating-characteristic curve, is the probability that a randomly chosen positive case is scored above a randomly chosen negative one — a measure of ranking only, indifferent to whether the predicted probabilities are believable, with 0.5 the coin flip. RMSE, root-mean-square error, is the typical size of a prediction error in the units of the outcome, so on the California data, where the target is measured in units of $100,000, an RMSE of 0.61 is a typical miss of about six tenths of that. And the Sharpe ratio, which the two finance examples turn on, is mean excess return divided by its own standard deviation — return per unit of risk taken, annualised by √52 for the weekly portfolio data. It is worth knowing that it rewards steadiness as much as size: halving the volatility of a strategy improves it exactly as much as doubling the return.

When the penalty matters, and the object it turns out to be

All values are committed notebook output. A and B come from the ridge/lasso project, C from the kernel project with the Gaussian-process figure taken from the benchmark that shares the data.

A · When n ≫ p — the penalty barely matters California test RMSE 0.7370 OLS 0.7374 Ridge 0.7371 Lasso 0.7372 ElasticNet 0.7360 0.7370 0.7380 spread 0.0004 — and ridge is slightly WORSE than plain OLS B · When p ≫ n — it is everything test RMSE 3.941 OLS 1.719 CV-lasso 0 1 2 3 4 200 predictors, 8 true signals ridge keeps all 200 lasso keeps 26 and finds 8 of 8 C · The same estimator under three names California test RMSE linear model 0.737 kernel ridge (assumed) 0.647 kernel ridge (CV-tuned) 0.612 GP posterior mean (marginal likelihood) 0.611 0.60 0.65 0.70 0.75 identical to 3.4e−14, correlation 1.000000 a penalty, and a posterior mean — one object

A and B are the same experiment run in two regimes, and they disagree completely. On the California data, where 14,448 rows carry 8 predictors, the four fits are indistinguishable — a spread of 0.0004 across OLS, ridge, lasso and elastic net — and ridge is not merely neutral but very slightly worse than plain least squares, which is what a penalty costs you when there is no variance to trade against. On 200 predictors with 8 true signals the same lasso more than halves the error, 1.719 against 3.941, keeps 26 variables and recovers all eight signals while ridge stays dense at 200. A penalty is not a good habit; it is a trade, and whether it pays depends entirely on which regime you are in.

C is the section’s thesis, and it is an identity rather than an analogy. Kernel ridge regression fitted with hand-chosen hyperparameters reaches RMSE 0.647. Choosing the same two numbers by cross-validation on the training subsample alone gives 0.612. The Gaussian process, choosing them by maximising the marginal likelihood instead, reaches 0.611. They are close because they are the same estimator: the notebook checks the kernel-ridge fit against the GP posterior mean directly and finds a maximum absolute difference of 3.4×10−14 at a correlation of 1.000000. The difference between the two rungs is not the model but how the hyperparameters were chosen — cross-validation against marginal likelihood.

Which is why a penalty, a prior and a covariance function keep turning out to be the same object described by three vocabularies. Ridge is the posterior mode under a Gaussian prior; the kernel is that prior’s covariance; and the GP is what you get when you keep the whole posterior instead of its mode. The only thing the Bayesian route adds here is the variance — which is worth nothing on this scoreboard and everything the moment someone asks how sure the prediction is.

How the five examples relate

Three method projects and two applications. The applications are not extra topics — they are the first three put to work where p is genuinely large relative to n, which is the only regime in which any of this earns its keep.

Parts 1 and 5 are the pair that makes the case. The first shows a penalty earning nothing when the data are plentiful; the last shows the sample covariance becoming barely invertible and the “optimal” portfolio turning into an error-maximiser without one. Same tool, opposite verdicts, and the difference is only the ratio of parameters to observations.

Ridge, Lasso & Elastic Net — Regularized Linear Models

The foundation: coordinate descent and the soft-thresholding operator, which is why L1 yields exact zeros rather than merely small numbers. Validated against scikit-learn to 4×10⁻¹⁰ in the worst case and — the harder test — picking the identical active set every time, 63/63, 93/93, 180/180. On a constructed p > n problem the payoff is unambiguous: cross-validated lasso keeps 26 of 200 predictors, recovers all 8 true signals, and cuts test RMSE from 3.94 to 1.72, where ridge stays dense at 200 variables and finds nothing. On real n ≫ p data the honest result is the opposite: the four fits differ by 0.0004, and ridge is slightly worse than OLS — regularisation answering a problem the data does not have. Closes on the bridge the rest of the collection picks up: penalties are priors.

View example →

Support Vector Machines & Kernel Methods

The loss changes, and then the geometry does. The hinge loss makes most of the data irrelevant to the fit — on the toy problem only 18 of 240 points are support vectors — and the kernel trick bends the boundary without ever constructing the feature space. The honest classification result is that max-margin buys nothing here: the exact linear SVM ties a logistic regression, and in R it loses to one fit to the very same 3,000 rows. Regression is where the kernel pays, cutting California RMSE from 0.737 to 0.644. The payoff is the identity in the second half: kernel ridge regression is the posterior mean of a Gaussian process, verified to 3.6×10⁻¹⁴. Chasing down why the GP still scored better resolves it — cross-validate the same two hyperparameters and kernel ridge lands on 0.612 against the GP’s 0.611. The marginal likelihood was buying hyperparameter selection, not a better estimator.

View example →

Gaussian Processes & Splines — the Bayesian Kernel View

The Bayesian counterpart, benchmarked on the machine-learning arc’s own two datasets rather than on a toy. A Gaussian process reaches California RMSE 0.611 from a 1,500-point subsample with 90% intervals covering a measured 91.0% — and error that grows with the reported standard deviation, so the uncertainty is calibrated and usable. An additive-spline GAM comes within 0.01 AUC of the tree ensembles on credit while every effect stays a readable curve with a credible band. The verdict is competitive, not dominant: boosting still edges raw accuracy, and exact GPs pay an O(n³) cost that forces the subsampling — which is exactly why boosting owns large tabular data. Also settles two bookkeeping questions the arc had left loose: BART’s regression gap is a pymc-bart implementation limit (dbarts gets 0.526, not 0.665), and Python and R scoreboards must never be pooled, since their 70/30 splits differ.

View example →

Finance — Shrinking the Factor Zoo

The first application: penalised regression turned on empirical asset pricing’s factor zoo. Britten-Jones’ result makes the tangency portfolio a regression — regress ones on factor returns — so the Lasso drops straight in and produces a sparse stochastic discount factor. The in-sample tangency posts a Sharpe of 2.41 and delivers 0.40 out of sample; more bluntly, twenty published factors optimally combined are beaten by holding the market alone (0.55). Cross-validated Lasso keeps 10 of 20, dropping three of four value proxies and two of three low-risk proxies, and lands essentially on the out-of-sample peak at 0.44 without seeing the test period. The R companion measures something the literature rarely states: at lambda.min the same fit keeps 19 of 20 and prunes nothing, so reported sparsity is a cross-validation rule as much as a finding.

View example →

Finance — High-Dimensional Portfolios

Where shrinkage stops being optional. Minimum-variance on 48 stocks: the covariance carries 1,176 parameters and a one-year window supplies 52 observations, so the sample optimiser runs to 15× leverage and 46% out-of-sample volatility — three times the shrunk estimators. Below T = N the estimate does not merely degrade, it ceases to exist: the matrix is singular and solvers return floating-point noise without complaint, so those windows are excluded rather than plotted. The comparison worth testing is with naive 1/N: on Sharpe the optimised portfolios beat it by +0.03, with a bootstrap interval of [−0.58, +0.61] — a coin flip, exactly as DeMiguel et al. claimed. On volatility, the objective they actually minimise, the advantage is −5.5pp and solidly outside noise. Shrinkage buys lower risk, not more return per unit of it.

View example →