SStatistics, Built

Stage III · Master's

Part 29 of 65

Smoothing

Master'sstarts at this level53 min of film14 chaptersprerequisites: Part 16, Part 23, Part 25

How do you estimate a whole curve, and how much data does it take?

Old Faithful's 272 eruption lengths have two humps, or twelve, or one, depending on the bandwidth; Silverman's critical bandwidths and his smoothed bootstrap reject one mode and do not reject two. The part then treats the picture as an estimator. A histogram's bias and variance balance at a bin width of order n to the minus one third; a kernel estimate does better, with squared error of order n to the minus four fifths, and Marron and Wand's exact MISE on a two-humped stand-in shows both rates arriving. Bandwidth selectors are raced, and the curse of dimensionality prices the same accuracy at 4 points in one dimension and 841,616 in ten. For regression the part builds local polynomials, proves that the penalized criterion is minimized by a natural cubic spline, turns the dial on the spline spectrum, and chooses lambda by GCV and REML on the motorcycle crash data. Reproducing kernels, wavelets and additive models follow. It ends with what smoothing costs inference: at the optimal bandwidth the conventional interval covers 91%, and robust bias correction restores 95%; and with shape constraints, where Grenander's estimator converges at the cube-root rate.

What you need. Taylor expansions and integration by parts; Part 16's cross-validation, Part 23's linear model (hat matrices, ridge) and Part 25's mixed models and REML.

Hook
Old Faithful's two humps
Mathematics
KDE and spline theory, local polynomials, RKHS, wavelets, GAMs, shape constraints
Built
statkit.smooth

What you will be able to do

Bachelor's

  • Explain why a histogram or a kernel estimate changes with the bin or the bandwidth, and what is traded when the bandwidth grows.
  • Explain the curse of dimensionality with the ball in the cube and the distance to the nearest neighbour.

Master's

  • Derive the bias and variance of a kernel density estimate, its AMISE, the optimal bandwidth and the rate.
  • Prove the Reinsch-Schoenberg theorem and write a smoothing spline as ridge regression in the Demmler-Reinsch basis.
  • Implement a kernel density estimate with a bandwidth selector and a local linear smoother.

PhD

  • Prove the representer theorem and identify kernel ridge regression with a Gaussian process's posterior mean.
  • Explain why Grenander's estimator has a cube-root rate and Chernoff's limit, and state the smoothness classes under which each rate of the part holds.

Practice

  • Choose a bandwidth or a smoothing parameter by Sheather-Jones, GCV or REML, and say why the normal-reference rule oversmooths two humps.
  • Report a pointwise interval for a curve that covers: undersmooth or use robust bias correction, and say that the band is pointwise.

Contents

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

  1. 0Old FaithfulBachelor's4 min
  2. 1Histograms as estimatorsMaster's4 min
  3. 2Kernel density estimatesMaster's5 min
  4. 3Choosing the bandwidthPractice4 min
  5. 4The curse of dimensionalityBachelor's3 min
  6. 5Local polynomialsMaster's4 min
  7. 6Smoothing splinesMaster's4 min
  8. 7Choosing lambdaPractice4 min
  9. 8Kernels and the representer theoremPhD4 min
  10. 9WaveletsMaster's4 min
  11. 10Additive modelsMaster's4 min
  12. 11Inference for curvesPractice4 min
  13. 12Shape constraintsPhD3 min
  14. Recap, problems, and the road aheadAll tracks4 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.

Old FaithfulBachelor's4 min

Old Faithful, in Yellowstone, erupts every hour or so. The R faithful data contain two hundred and seventy-two eruption durations and waits to the next eruption. We use the documented data without attributing an unverified collection date. How long does an eruption last? Not a mean and a standard deviation: the answer is a whole distribution, and the question this part asks is how to estimate a curve. In 1981 Bernard Silverman asked a sharper version: how many humps does the distribution have?

The rug along the bottom shows the eruptions: about a third last two minutes or less, the rest four or more. A histogram with half-minute bins shows two humps. Slide the same bins a little to the right, and the shape changes: the tops move, a shoulder comes and goes. Halve the bin width, and the long eruptions seem to split into two. Is that third hump real, or the noise of two hundred and seventy-two observations?

Part 16's kernel estimate removes the bin edges: put a small normal bump on every eruption and add them up. One choice remains, the bumps' width h. At h of point oh five the curve has twelve modes, one for every little clump. At point one, three. At a quarter of a minute, two. At a full minute, one: everything is smoothed into a single lump. The number of humps is a function of the bandwidth, so the question becomes: how much smoothing is too little?

Silverman's key fact: with a normal kernel, modes can only disappear as h grows, never appear. So for each k there is a critical bandwidth, the smallest h at which the estimate has at most k modes. To squeeze Old Faithful into one hump takes h of point eight three, a huge amount of smoothing. Two humps need only point one three. And a third appears just below, at point oh nine. A large critical bandwidth is evidence against k modes, if we know how large it would be by chance.

Silverman's test: simulate from the k-mode estimate itself, by resampling the data and adding kernel noise, and see how often the simulated data need more smoothing than h k to reach k modes. One mode: never, in five hundred tries. Rejected. Two modes: half the time, so this calculation does not reject at most two modes. Three: ninety-three percent. The two broad humps are clear; the test supplies no compelling evidence for an additional mode. These are raw smoothed-bootstrap results, whose nominal levels need calibration; non-rejection does not prove the number of modes. Getting there needed every idea in this part: how a curve estimate's error depends on its smoothing.

Part 28 chose among models with a fixed number of parameters. A curve has infinitely many, and no finite family need contain it. Every method in this part smooths: by bin width, bandwidth or penalty. Too little smoothing and you see noise; too much and you flatten real structure. For a twice-smooth density class, optimal worst-case integrated squared error has rate n to the minus four fifths. The rate depends on smoothness and deteriorates with dimension.

Numbers: h₁ 0.83, h₂ 0.13; raw bootstrap p = 0.002 / 0.501 / 0.930

1Histograms as estimatorsMaster's4 min

Part 1 said that the histogram's bin width trades variance against bias, and quoted David Scott's rule, three point four nine s times n to the minus a third. It never said what error was being traded, or where the cube root came from. Now we define the error, derive it, and find the best bin width and how fast the error falls.

The histogram's height in bin j is the count there, divided by n times the bin width h, so that the area is one. Its error, for one data set, is the integrated squared difference from the true density. Averaged over data sets, the mean integrated squared error splits into integrated variance plus integrated squared bias. For a histogram it can even be computed exactly, from the bins' probabilities: each count is binomial.

The count in a bin is binomial, so the height's variance is about f over n h: wide bins collect more points and wobble less. The bias: a flat top can't follow a sloping density, and at a point x the error is the slope times the distance from the bin's centre. Averaged over the bin, that distance squared is h squared over twelve, so the integrated squared bias is h squared over twelve times the integral of f prime squared, written R of f prime. The asymptotic MISE: one over n h, falling with h, plus a bias term growing like h squared.

Differentiate and set to zero. The best bin width is six over n R of f prime, to the one third: that is the cube root. For a normal density R of f prime is one over four root pi sigma cubed, which gives three point four nine sigma n to the minus a third: Part 1's rule, Scott's, derived. Plugged back in, the best achievable error falls like n to the minus two thirds. A parametric estimate's error falls like one over n; estimating a whole curve is slower.

Exactly computed curves of MISE against bin width, for a two-humped density shaped like Old Faithful's. With a hundred observations the best bin is a third of a minute wide, and the formula says the same. With a thousand, point one five. With ten thousand, point oh seven: ten times the data, bins narrower by the cube root of ten. Each curve rises steeply on the left, where variance dominates, and more gently on the right, where bias does; both extremes are costly; the relative loss depends on the density and the range considered.

The rates, from the exact errors. The histogram's best MISE falls with slope minus point six five in log n, close to the theory's minus two thirds. The kernel estimate of the next chapter falls faster, slope minus point seven six on its way to minus four fifths: two and a half times better at a hundred points and four times better at ten thousand. For smooth densities away from boundaries, flat histogram bins have bias of order h, whereas symmetric second-order kernels have bias of order h squared.

Numbers: h* 0.34 / 0.15 / 0.07; slope −0.65

2Kernel density estimatesMaster's5 min

The kernel estimate, from Murray Rosenblatt in 1956 and Emanuel Parzen in 1962: at each point, average kernel bumps centred on the observations, each of width h. Here are thirty of the eruptions, each with its normal bump, drawn taller so they can be seen. Their average is a smooth curve, with no bin edges and no origin to choose. With all two hundred and seventy-two eruptions, two clear humps.

The estimate's expectation is the true density blurred by the kernel, after substituting u for x minus y over h. Expand f around x. The constant term returns f; the slope term vanishes, because a symmetric kernel has mean zero, unlike the histogram's off-centre bins; what's left is half h squared times the kernel's variance times the curvature f double prime. Bias is negative at peaks and positive in valleys: smoothing flattens. Integrated and squared: a quarter h to the fourth mu two squared R of f double prime.

The variance: the estimate is an average of n independent bump heights. Each bump's second moment, after the same substitution, is about f of x times R of K over h; the squared mean is of smaller order. So the integrated variance is R of K over n h. n h is roughly the number of observations within a bandwidth of x: the effective sample size of a local average, as for the histogram.

Add them. Variance falls like one over n h; squared bias grows like h to the fourth, not the histogram's h squared. Setting the derivative to zero gives the best bandwidth, which shrinks like n to the minus one fifth. The minimal error is a constant depending on the kernel, times one depending on the density's roughness, times n to the minus four fifths. Against the histogram's minus two thirds, that is a real gain, and Part 50 proves that the worst-case integrated squared-error rate over suitable bounded two-derivative classes cannot be improved. This is not a pointwise lower bound for every particular density.

Pictured for a thousand points at the optimal bandwidth. Gold is the truth. Blue uses the leading bias and standard-deviation approximations, with a band of two standard deviations: widest at the peaks, where there's most data and so most absolute noise. Red is the bias, magnified five times: negative at the two peaks, positive in the valley and the shoulders. The optimal bandwidth deliberately leaves in bias comparable to the noise, a point chapter eleven will make costly.

For normal mixtures and a normal kernel the MISE is exactly computable, Steve Marron and Matt Wand's formula. Here it is for a thousand points. On log scales the variance term is a line of slope minus one, the squared bias a line of slope four. Their sum, the asymptotic approximation, hugs the exact curve near the optimum and departs for large h, where the Taylor expansion fails. With a hundred or ten thousand points the whole curve shifts: the optimum moves as n to the minus one fifth, and the minimal error as n to the minus four fifths.

Which kernel is best? The minimal error depends on the kernel only through root mu two times R of K, invariant to rescaling the kernel. Fix mu two and minimize the integral of K squared subject to K being a density, with Lagrange multipliers. Differentiating pointwise in K, the calculus of variations, says that wherever K is positive it is a downward parabola in u. Normalized and truncated at zero: three quarters of one minus u squared, Vassiliy Epanechnikov's kernel of 1969.

How much does it matter? Express each kernel's efficiency as the ratio of sample sizes needed for the same error. The biweight and triangle lose less than one and a half percent. The normal kernel loses five. Even a flat box, the crudest kernel there is, needs only seven and a half percent more data. The kernel hardly matters; the bandwidth matters enormously, and the next chapter chooses it.

Numbers: slope −0.76; Gaussian efficiency 0.951

3Choosing the bandwidthPractice4 min

The best bandwidth depends on the unknown curvature of f, the very thing we're estimating. The simplest escape: pretend f is normal. Then R of f double prime is known, and h is one point oh six sigma n to the minus a fifth. Silverman's rule of thumb, Part 16's choice, shrinks the constant and uses a robust spread. These are normal-reference rules, not guarantees for arbitrary unimodal densities. For two humps the standard deviation is inflated by the gap between them, and both rules oversmooth.

Cross-validation instead. Expand the integrated squared error: the last term doesn't depend on h, the first is computable, and the middle one involves the unknown f. But the middle term is an expectation over a new observation, which leave-one-out estimates. So the least-squares cross-validation criterion of Mats Rudemo and Adrian Bowman estimates ISE up to a constant. With normal kernels both terms are sums of normal densities at the pairwise gaps.

On Old Faithful the criterion falls steeply from tiny bandwidths, reaches its minimum at h of point one oh, where the estimate has three modes, and rises slowly. The minimum is shallow, so small changes in the data move it a lot: the cross-validation criterion is unbiased for the relevant expected error up to constants, but its minimizing bandwidth can be biased and variable.

The other strategy plugs in an estimate of the unknown curvature. Integrating by parts twice, R of f double prime is the integral of f's fourth derivative times f, called psi four. That can itself be estimated by a kernel sum over all pairs, with its own pilot bandwidth g. The best pilot depends on psi six, whose pilot depends on psi eight, where a normal reference finally stops the regress. Simon Sheather and Chris Jones's plug-in bandwidth puts the estimate into the formula.

The four choices on Old Faithful. The normal reference, h of point three nine, blurs the short eruptions into a low mound. Silverman's point three three, a little sharper. Sheather–Jones, point one seven: two crisp humps. Cross-validation, point one oh: three. Silverman's test of chapter zero sides with the plug-in.

A race: three hundred samples of two hundred from the two-humped density, each bandwidth measured against the one minimizing the true MISE. The normal reference bandwidth is almost three times too wide, Silverman's two and a third: in this experiment they smooth too much, with average errors about three and a half and five times the best fixed-bandwidth MISE. Cross-validation has median bandwidth close to the reference optimum, but its middle eighty percent runs from point seven two to one point two. Sheather–Jones is a fifth too wide, but consistently, and has the lowest average error, in this seeded comparison. Broader comparisons depend on the density, sample size and selector; no selector wins universally.

In practice, look at several bandwidths; structure that persists across a range is probably real. A plug-in is a good default, cross-validation a useful check. Normal-reference rules can oversmooth separated modes and other sharp structure, though not every departure from normality causes oversmoothing. And Probal Chaudhuri and Steve Marron's SiZer map turned the advice into a method: at every bandwidth and location, is the estimated slope significantly up or down?

Numbers: SJ 0.166, LSCV 0.103; NR 2.8× too wide

4The curse of dimensionalityBachelor's3 min

In d dimensions, the bias of a kernel estimate is still of order h squared. But the number of observations in a window of width h is now n times h to the d, so the variance is one over n h to the d. Balancing gives a bandwidth shrinking like n to the minus one over four plus d, and an error falling like n to the minus four over four plus d. In one dimension, minus point eight. In ten, minus point two nine. Richard Bellman named the problem the curse of dimensionality in 1961.

Silverman's table makes it concrete. Estimate a standard normal density at its centre, where it is easiest, to within ten percent relative mean squared error, at the best bandwidth, computing the error exactly. In one dimension, four observations suffice; in two, nineteen. In five, seven hundred and sixty-eight. In ten, eight hundred and forty-two thousand. These are statkit's numbers; they reproduce Silverman's 1986 table.

Geometry explains it. Inscribe a ball in a cube. In two dimensions the disc fills seventy-nine percent of the square; in three, the ball fills fifty-two percent of the cube. In ten dimensions, a quarter of one percent. Almost all of a high-dimensional cube is corners, far from its centre, so any neighbourhood small enough to be local contains almost none of the data.

Or measure it. Scatter a thousand points uniformly in a cube and find each point's nearest neighbour. In one dimension it is a few ten-thousandths away. In ten dimensions, half the cube's side. In fifty, more than twice the side. And the nearest neighbour is nearly as far as the farthest: the ratio climbs towards one. Kevin Beyer and colleagues asked in 1999 when 'nearest neighbour' is meaningful at all.

Even a normal cloud is mostly far from its centre. The squared distance of a standard normal point from the origin is chi-squared with d degrees of freedom. Its mean is d, its standard deviation root two d. So the distance itself is about root d, with asymptotic standard deviation one over root two, about point seven, as d grows: in high dimensions the points live in a thin shell. The density is highest at the centre, where Silverman's table estimated it, and yet almost no observations fall anywhere near it.

The escapes all assume structure. With a fixed number of components and suitable design and smoothness conditions, additive models can recover one-dimensional component rates. Index models smooth along a few estimated directions. Sparsity assumes only a few variables matter, Part 32. And smoother truths permit faster rates: over suitable bounded smoothness classes, the minimax squared-error rate is n to the minus two s over two s plus d, with regularity and design conditions.

Numbers: 4 → 841,616 points from 1-D to 10-D

5Local polynomialsMaster's4 min

Now regression: estimate the conditional mean m of x, of any shape. Elizbar Nadaraya and Geoffrey Watson's estimator, both in 1964, is a kernel-weighted average of the responses near x. It is the weighted least-squares fit of a constant. Fitting a weighted line instead and keeping its intercept gives local linear regression, and in general a local polynomial, the approach Jianqing Fan and Irène Gijbels systematized.

Both are linear smoothers: the fit is a weighted sum of the responses, with weights l of x called the equivalent kernel. Nadaraya–Watson's bias has a curvature term and a second term, slope times f prime over f, which appears wherever the design density changes. In the interior the extra design-density term vanishes. At a boundary local linear retains order h squared bias, but its coefficient and variance differ from the interior formulas. Their leading variances agree at regular interior points. Boundary adaptation is a major advantage of local linear fitting; this is not uniform dominance over every regression function or design.

The equivalent kernels for a hundred and one equally spaced points and h of point one. At the centre, both methods give the same symmetric bump. At the left boundary, Nadaraya–Watson can only average points to the right, so its weights are half a bump, centred away from zero. Local linear's weights reach further and turn negative: it extrapolates the local trend back to the edge, which removes the first-order slope bias; curvature bias remains.

The consequence, with no noise at all: data exactly on the line y equals two x. Nadaraya–Watson bends at both ends, to point one five at zero and one point eight five at one, because it can only average neighbours on one side. Local linear reproduces the line exactly: any local polynomial of degree p reproduces polynomials of degree p.

A real regression: each Old Faithful eruption's length against the wait that followed it, a descriptive relationship used to motivate waiting-time prediction. The local linear fit with h of point three. It is close to the least-squares line, thirty-three plus eleven minutes per minute of eruption, with a flattening among the long eruptions. Through the gap between the two clusters, where there are almost no data, the local fit simply interpolates.

The classic test bed: recorded head accelerations in a simulated motorcycle crash, and the acceleration of its head over the first sixty milliseconds, a hundred and thirty-three readings at irregular times. Flat, then a sharp dip to minus a hundred and thirty g, a rebound, and a ringing decay. Nadaraya–Watson with a two-millisecond bandwidth. Local linear with the same bandwidth. They agree where the curve is flat and part where the slope is steep and the times are unevenly spaced: there the design bias of Nadaraya–Watson shows.

William Cleveland's widely used LOESS is local linear or quadratic regression on the nearest fraction alpha of the points. With the tricube kernel. And with robustness iterations: residuals far from zero, measured against six median absolute residuals, get small bisquare weights, and the fit is redone, reducing sensitivity to isolated response outliers, without immunity to leverage or substantial contamination. Using a fixed number of neighbours rather than a fixed width makes the bandwidth wide where data are sparse and narrow where they are dense, a useful adaptation to uneven design density; it does not remove high-dimensional rates.

Numbers: NW 0.15 at the boundary; 14 g apart on the crash

6Smoothing splinesMaster's4 min

Instead of a local average, penalize roughness. Among all curves, minimize the residual sum of squares plus lambda times the integrated squared second derivative, the bending energy. As positive lambda tends to zero, distinct observations are interpolated; tied x values are fitted by their averages. As lambda grows, curvature becomes unaffordable and the solution tends to the least-squares line, which has no curvature at all. The search is over functions with square-integrable weak second derivative, an infinite-dimensional space. Remarkably, the answer is finite-dimensional.

Take any candidate g, and let s be the natural cubic spline through g's values at the data points: cubic between them, linear beyond the ends. Then s fits the data exactly as well as g. Integrate s double prime times g double prime minus s double prime by parts: the boundary term vanishes because s double prime is zero at the ends, and the remaining integral vanishes because s triple prime is constant between knots, where g minus s takes equal values at both ends. So the bending energy of g is that of s plus a non-negative remainder, Pythagoras in function space. Every candidate is beaten by a natural cubic spline, so the minimizer is one, with knots at the data: the theorem of Isaac Schoenberg and Christian Reinsch.

A natural cubic spline is determined by its values at the knots, and its bending energy is a quadratic form in them, g transpose K g, with K built from two banded matrices, Peter Green and Bernard Silverman's Q and R. The infinite problem becomes a finite penalized least squares, with solution I plus lambda K, inverse, times y. The smoother matrix S; its trace is the degrees of freedom of Part 28. A banded Reinsch implementation can solve a fixed-lambda fit in order n operations after sorting. Our teaching implementation forms dense matrices; tests compare its values with SciPy, rather than claiming linear complexity for this code.

Smoothing splines on the motorcycle data, indexed by their degrees of freedom rather than lambda, which has awkward units. Four degrees of freedom: too stiff to follow the dip. Eight: the dip, but the rebound is flattened. Twelve: dip, rebound and decay. Twenty-five: the curve starts chasing individual readings.

The spline spectrum: this part's instrument. Diagonalize K. Its eigenvectors, the Demmler–Reinsch basis, are oscillating curves on the crash times, ordered from smooth to wiggly, and the smoother keeps each component in proportion one over one plus lambda d j. The first two, a constant and a line, have zero bending energy and pass whole. At eight degrees of freedom the components with more and more oscillations are damped harder and harder. At twenty-five, more of them get through. A smoothing spline is a low-pass filter in this basis, and its degrees of freedom are the sum of the bars.

So the fit is: project the data on each basis curve, shrink by its factor, add up. The degrees of freedom are the sum of the factors, between two, for the line, and n, for interpolation. Under regular designs the eigenvalues grow roughly like the fourth power of the oscillation index. Irregular knot spacing changes the spectrum. It is Part 25's ridge regression, which shrinks each principal direction, with the roughness penalty deciding which directions are rough.

Numbers: df 4 / 8 / 12 / 25; the spectrum

7Choosing lambdaPractice4 min

First, Part 28's tools. A smoothing spline is a linear smoother, so its leave-one-out error needs no refitting. Craven and Wahba invented generalized cross-validation for exactly this problem in 1979: replace each leverage by the average, one minus the degrees of freedom over n. It aims at prediction error. Its weakness is variability: its minimum can be flat, and now and then it chooses a nearly interpolating spline.

Second, Part 25's tools. Write the spline as a mixed model: the constant and line as fixed effects, and rescaled wiggly basis columns u j divided by root d j, with independent random coefficients of variance sigma squared over lambda. The best linear unbiased predictor of the curve is then exactly the smoothing spline. Lambda is a ratio of variances, noise over signal. So it can be estimated by restricted maximum likelihood like any variance component, Grace Wahba's generalized maximum likelihood of 1985, and the reason mixed-model software fits splines.

The mixed-model view gives more than lambda. For fixed lambda and sigma, unit weights and distinct x values, the Gaussian prior with flat linear component gives a normal posterior, with mean S y and covariance sigma squared S. So a band at each design point is the fit plus or minus one point nine six sigma hat root S i i, Grace Wahba's Bayesian confidence interval. The displayed sigma estimate uses n minus trace S as a smoothing approximation; it is not an exact unbiased residual degrees-of-freedom formula. Nychka studied approximate average frequentist coverage under smoothness and smoothing assumptions. Neither arbitrary fixed curves nor every location have guaranteed ninety-five percent coverage; plugging in smoothing and noise estimates also omits their uncertainty.

On the motorcycle data, both criteria against degrees of freedom. GCV's minimum is at about twelve and a half. REML's at about fourteen, computed from all observations, including independent replicate contrasts at tied times. These criteria favor smoother fits in this example; they do not test whether the visible features are real.

The two fits, almost the same curve. REML's is a touch wigglier. Their residual standard deviation is about twenty-three g, but the scatter is tiny in the first fifteen milliseconds and large afterwards. A single lambda and constant noise are both assumptions here; adaptive smoothers, with lambda varying along the curve, and weighted fits relax them.

Which is better? Three hundred simulated data sets, scored against the true curve. The oracle, which knows the truth, picks around eleven degrees of freedom. GCV centres there too, but its choices spread up to fourteen and a half: on some data sets it undersmooths. REML's choices are tighter, and its average error, and especially its worst five percent, are smaller. Philip Reiss and Todd Ogden explained why in 2009: GCV's criterion has multiple minima more often, and REML is less variable. REML is a common option in modern GAM software; defaults depend on the package and version.

GCV targets prediction and needs no model for the curve. REML treats roughness through a variance-component model, and is more stable in this experiment, rather than universally. The mixed-model view also gives the spline a posterior, and so intervals, chapter eleven. And it lets smooth terms sit inside larger models: additive models, generalized mixed models, Simon Wood's GAM software.

Numbers: GCV df 12.4, REML 14.1; REML's worst 5% 0.0187 vs 0.0220

8Kernels and the representer theoremPhD4 min

The general idea behind the spline. Start with a symmetric positive semidefinite kernel, now a function of two points, like a Gaussian bump in their distance. It generates a Hilbert space of functions, sums of kernel sections, with the inner product of two sections defined as the kernel itself, Nachman Aronszajn's construction. Then evaluating a function at x is an inner product with the section at x: the reproducing property. And the space's norm is a measure of roughness, decided by the kernel.

For positive lambda and a loss admitting a minimizer, minimize data loss plus lambda times the squared norm. Split any candidate into its projection on the n kernel sections at the data points, and the rest. By the reproducing property, the rest is zero at every data point: the data cannot see it, and it only adds to the norm. So the minimizer is a combination of n kernel sections: George Kimeldorf and Grace Wahba's representer theorem of 1970. An infinite-dimensional problem with an n-dimensional answer.

With squared loss the coefficients solve a linear system: kernel ridge regression. The fit at a new point is the vector of kernels to the data times that system's solution. The cubic spline uses a roughness seminorm with a two-dimensional linear null space: the representer argument must retain those unpenalized lines. Support vector machines use a representer theorem too. Kernel PCA uses related Gram-matrix geometry, and Gaussian-process conditioning gives a matching posterior mean under Gaussian noise.

Kernel ridge regression on the motorcycle data, with a Gaussian kernel of width ell. A wide kernel, six and a half milliseconds, can't bend fast enough: seven degrees of freedom, and the dip is too shallow. A kernel of two milliseconds: eighteen degrees of freedom, close to the smoothing spline. A narrow kernel with little penalty: fifty-six degrees of freedom and a wiggly fit. The kernel's width and lambda together set the smoothness.

The same fit has a Bayesian reading. Put a Gaussian-process prior on the curve, with covariance tau squared times the kernel, and normal noise. The posterior mean is exactly the kernel ridge fit, with lambda the ratio of noise to signal variance, as for the spline's mixed model. At fixed hyperparameters the posterior gives pointwise uncertainty for the latent curve, not a simultaneous band or a predictive interval for a new noisy observation. Its width assumes one noise level, twenty-three g, everywhere: a potentially inadequate assumption given the changing residual spread. Plugging in an estimated noise level also leaves hyperparameter uncertainty out. Part 39 builds Gaussian processes properly, with estimated kernels.

The dictionary: penalized least squares in a reproducing kernel space is a Gaussian-process posterior mean. The penalty is the prior, and lambda the noise-to-signal ratio. The kernel's width and lambda are hyperparameters, chosen by cross-validation or by the marginal likelihood, REML's cousin. A general dense solve costs order n cubed; specialized banded spline solvers and approximate kernel methods can cost less.

Numbers: df 7 / 18 / 56; GP band

9WaveletsMaster's4 min

Basic fixed-bandwidth kernels and fixed-penalty splines use global tuning. Wavelet thresholding offers another way to adapt locally. A wavelet basis is one small wave, dilated by powers of two and shifted along. The simplest is Alfréd Haar's of 1910, a step up then down; Ingrid Daubechies built smooth ones in 1988, and statkit uses her four-tap filter. Any signal is a coarse picture plus detail coefficients at every scale and location. the periodic basis is orthonormal, so iid Gaussian noise maps to iid Gaussian noise with the same variance, and Stéphane Mallat's pyramid computes it in order n.

David Donoho and Iain Johnstone's four test signals, each sampled at a thousand and twenty-four points and scaled to signal-to-noise ratio seven: blocks, with jumps; bumps, with sharp spikes; heavisine, a sine wave with two breaks; and the Doppler, oscillating faster and faster towards the left. Grey is the signal plus unit noise. No single bandwidth suits any of them.

Why wavelets work: look at the blocks signal's detail coefficients, coarse scales at the bottom, fine at the top. The signal's own coefficients are sparse: only seventy-six of about a thousand exceed the unit-noise universal threshold, clustered at the jumps. The sticks are vertically clipped for display; the count uses the original coefficients. The noise spreads evenly over every coefficient, because the basis is orthonormal. So keep the big coefficients and kill the small ones.

Soft thresholding: coefficients below t are set to zero, the rest pulled towards zero by t. If the finest detail scale is mostly Gaussian noise, its median absolute coefficient divided by point six seven four five estimates sigma. Fine-scale signal can contaminate this estimate. VisuShrink uses one universal threshold, sigma times root two log n. SureShrink chooses a threshold at each scale by minimizing Stein's unbiased risk estimate, Part 25's SURE, falling back to the universal one where the coefficients look sparse.

Where root two log n comes from: it is the size of the largest of n independent standard normals. In two hundred simulations at each n, the largest absolute value sits just below it, and the chance of exceeding it shrinks to zero. So the universal threshold kills pure noise with high probability, a known-noise asymptotic statement, not a literal guarantee of smoothness or of zero false retained coefficients at every finite sample size. At n of a thousand and twenty-four, a unit-noise threshold is about three point seven.

On the blocks. The best spline, chosen by GCV, needs three hundred and fifty degrees of freedom to follow the jumps, and so it rings with noise along every flat step. SureShrink keeps the jumps sharp and the steps flat, because it spends its coefficients only where the signal changes.

The scores, as mean squared error per point; the noise alone scores one. VisuShrink is too conservative at this high signal-to-noise ratio: shrinking every large coefficient by three point seven costs it more than it saves on blocks, bumps and Doppler. SureShrink is best on blocks and bumps, which jump and spike. On the piecewise smooth heavisine its error is close to the spline's, and on the Doppler, smooth but with changing frequency, the spline edges it. Appropriately chosen wavelet procedures achieve adaptive near-minimax bounds over specified Besov smoothness classes. This single noise realization illustrates behavior, rather than proving a universal ranking.

Numbers: SureShrink 0.40 vs spline 0.71 on blocks

10Additive modelsMaster's4 min

Chapter four's escape, made concrete. Assume the regression function is a sum of smooth curves, one per variable, with no interactions. Centering separates the intercept; identifying individual curves also requires a design without exact concurvity. Charles Stone proved in 1985 that for a fixed number of twice-smooth additive components under suitable design conditions, each has the one-dimensional squared-error rate. The claim is not uniform as the number of predictors grows. Trevor Hastie and Robert Tibshirani added Part 24's link functions: the generalized additive model.

The fitting algorithm is simple. For variable j, form the partial residual: the response minus every other curve. Smooth it against x j alone, with any one-dimensional smoother, and centre the result. Cycle through the variables until nothing changes: backfitting, from Jerome Friedman and Werner Stuetzle. Andreas Buja, Hastie and Tibshirani showed it is Gauss–Seidel iteration on a linear system, with convergence under appropriate compatibility and contraction conditions. Exact concurvity can prevent unique component estimates.

One caution. Part 23 met collinearity: when one predictor is nearly a linear function of another, their slopes are unstable. Additive models have a nonparametric version, concurvity: a smooth function of one variable that nearly equals a smooth function of another. Then the two curves can trade signal back and forth. Backfitting slows down and the curves' uncertainty grows. In the ozone data hot days also tend to be calm and sunny, so each curve is a partial effect, holding the others fixed, not a causal one.

New York's ozone in the summer of 1973, a hundred and eleven complete days, on a chosen cube-root response scale, against temperature, wind and sunshine, each as a smooth curve with four degrees of freedom. Backfitting converged in seventeen sweeps in this fit. Temperature: ozone rises with heat, gently at first and more steeply above about seventy-five degrees. Wind: ozone falls with wind, steeply at first and then levelling off, as a partial association; this fit alone does not establish a causal wind effect. Sunshine: ozone rises with radiation and then flattens or dips on the brightest days. In each panel the dashed line is the linear model's slope; every curve bends where the line cannot.

Is the extra flexibility real? The linear model explains sixty-eight percent of the variation; the additive model seventy-six. More to the point, ten-fold cross-validation, with training-fold smoothing parameters and natural-spline prediction, compares held-out squared error on the cube-root scale. The displayed paired loss error describes this split, not uncertainty from re-running the entire CV procedure. And unlike a black box, every piece of the model is a curve you can plot and argue with.

Extensions add structure back carefully: a few two-dimensional tensor-product smooths for interactions that matter. Simon Wood's penalized regression splines use a few dozen knots instead of n, and choose every smoothing parameter at once by REML, chapter seven's lesson. Varying-coefficient models let slopes change smoothly with time or place. But additivity is itself an assumption, to be checked like linearity was in Part 23.

Numbers: R² 0.76 vs 0.68; CV −10% (one split)

11Inference for curvesPractice4 min

The usual interval, estimate plus or minus one point nine six standard errors, assumes the standardized error is standard normal. For a curve estimate it is that plus the bias over the standard error. At the MSE-optimal bandwidth, chosen precisely to balance bias against variance, at a regular point with nonzero curvature, that ratio has a nonzero limit rather than vanishing. So the interval is centred in the wrong place and undercovers, however much data you have. The relevant standardized shift is curvature relative to density-dependent noise; a peak or valley alone does not identify the worst coverage.

At the long eruptions' mode, with three hundred observations from the two-humped density and the pointwise MSE-optimal bandwidth. The true density there is point six one seven. A normal curve fitted to the mean and SD of two thousand simulated estimates is centred at point five eight seven: a bias of minus point oh three, as the formula predicts, more than half a standard deviation. The interval built around such an estimate misses the truth too often.

Two classical fixes. Undersmooth: use a smaller bandwidth than optimal, so the bias becomes negligible relative to the noise; but how much smaller is a new tuning problem. Or estimate the bias, which needs f double prime, and subtract it. Peter Hall showed in 1992 that, done naively, the second loses: the estimated correction adds variance that the usual standard error ignores. Sebastian Calonico, Matias Cattaneo and Max Farrell's robust bias correction keeps the correction but computes the standard error of the corrected estimator itself, and derived improved coverage-error properties under specified smoothness and bandwidth conditions, not uniform dominance for every density and tuning choice.

With the pilot bandwidth equal to h, the estimated curvature is a kernel sum with the kernel's second derivative. The bias-corrected estimate is then a kernel estimate with a new kernel M, K minus half K double prime. The robust standard error is just the standard error of that average. For our unit-variance Gaussian kernel, M has zero second moment. Under four derivatives and the required integrability, its leading bias is order h to the fourth. For a general kernel the correction includes its second moment. The interval is wider than the naive one, because it is honest about both the bias and its correction.

The Board: two thousand samples, the ninety-five percent interval for the density at the long eruptions' mode. At the MSE-optimal bandwidth the conventional interval covers ninety-one percent: broken, in this simulation. The asymptotic shift follows from the bandwidth calculation, rather than from a single sample-size experiment. Undersmoothing, with the bandwidth shrunk by n to the minus a tenth, restores ninety-five, with intervals forty-four percent wider. Robust bias correction also reaches about ninety-five in this experiment. We explicitly choose the pilot b equal to h; other pilot ratios are possible.

These are pointwise intervals: each covers at its own x. Covering the whole curve at once needs simultaneous bands, built from the distribution of the supremum of a Gaussian process, Peter Bickel and Murray Rosenblatt's result. Nychka studied approximate average frequentist coverage of Bayesian spline intervals under regularity and smoothing conditions; fixed curves and individual locations need not have nominal coverage. But bias can never be seen in the data alone: it is bounded only by assumptions about smoothness, which Part 53 studies in Bayesian form.

Numbers: 91.0% vs 95.4% (RBC)

12Shape constraintsPhD3 min

Sometimes all we know is the shape: a dose-response curve rises, a hazard falls. Then fit the best monotone sequence: isotonic regression. Part 21's pool-adjacent-violators algorithm solves it exactly: whenever adjacent fitted blocks violate the order, pool them using their sample-count weighted average. There is no bandwidth and no lambda: the constraint alone does the smoothing. Geometrically, the solution is the slope of the greatest convex minorant of the cumulative sums, the picture behind its theory.

Sixty noisy readings of a rising curve. The truth in gold. The isotonic fit is a staircase of eighteen steps, flat where the data dither and steep where they climb. Its steps are chosen by the data, as wavelets chose their coefficients.

For densities: suppose only that f is non-increasing, as for many waiting times. Ulf Grenander's estimator of 1956 is the slope of the least concave majorant of the empirical distribution function: the tightest concave curve lying above it. It is also the maximum likelihood estimate among all decreasing densities, and needs no bandwidth. At a positive interior density with strictly negative derivative and suitable regularity, its error has cube-root rate and a limit found by B. L. S. Prakasa Rao: a scaled Chernoff distribution, the location of the maximum of Brownian motion minus a parabola.

Two hundred exponential waiting times. The true density in gold. Grenander's estimate, a decreasing staircase that follows it closely in the middle. At zero it overshoots, a known inconsistency at the boundary, where the majorant's first slope can be enormous.

The rates, by simulation at x equals one. The Grenander estimate's standard deviation, multiplied by n to the one third, settles near point four, close to the Chernoff limit of point four two. A kernel estimate's, multiplied by n to the two fifths, settles too, near point two eight. Monotonicity alone buys the cube-root rate, the same as one derivative would; assuming two derivatives buys n to the minus two fifths. Each assumption about shape or smoothness has an exchange rate in sample size.

The idea has grown: Log-concave densities include normals and gamma laws with shape at least one. Their MLE exists under a full-dimensional convex-hull condition, with sample size sufficient for the dimension. Convex regression and unimodal density estimation are other shape problems, but constraints do not by themselves guarantee that an unrestricted likelihood maximizer exists. Monotone hazards return in survival analysis, Part 40. And shape-constrained estimators adapt: some procedures attain near-parametric risk bounds for suitable simple piecewise truths, with the dimension, loss and model class specified.

Numbers: SD·n^{1/3} ≈ 0.39 vs Chernoff 0.42

Recap, problems, and the road aheadAll tracks4 min

Part twenty-nine in thirteen lines. Old Faithful has two broad modes, without compelling evidence of a third in our approximate bootstrap calculation. The histogram's best bin shrinks like n to the minus a third, and its error like n to the minus two thirds. Kernel estimates do better, n to the minus four fifths, and the kernel's shape hardly matters. Plug-in bandwidths outperform the normal-reference rules in our bimodal example and are less variable than LSCV there. In ten dimensions the same accuracy needs eight hundred and forty-two thousand points. Local linear fitting removes the leading slope and design-density bias, retaining curvature bias at the boundary. Smoothing splines are natural cubic splines, low-pass filters in the Demmler–Reinsch basis, and REML chooses their smoothness more steadily than GCV in our experiment. The representer theorem makes infinite-dimensional problems finite, and the same fits are Gaussian-process posterior means. Wavelets exploit sparsity and adapt to jumps. Fixed-dimensional additive structure can recover one-dimensional component rates under design conditions. Intervals at the optimal bandwidth undercover, and robust bias correction improves coverage under its regularity and bandwidth conditions. And shape constraints smooth without any tuning at all.

A promise for later. This part derived rates: n to the minus four fifths for densities with two derivatives, a cube-root pointwise estimation-error scale at a strictly decreasing interior density; this differs from a squared-error risk rate. It did not show that nothing can do better. Part 50 proves it, with the lower-bound methods of Lucien Le Cam, Patrice Assouad and Robert Fano: the rates are minimax.

Where it comes back. Part 30 makes smoothers robust. Part 32 fits sparse additive models in high dimensions. Part 34 wraps any smoother in conformal prediction bands. Part 37 uses local linear regression at a cutoff, the regression discontinuity design, with exactly this chapter's robust bias correction. Part 39 builds Gaussian processes and kriging. Part 40 smooths hazards. Part 50 proves the rates minimax. And Part 53 studies how fast posteriors for curves contract.

Six problems, with full solutions in the README. The histogram's bias and best bin; the kernel estimate's bias and variance; Epanechnikov's optimality; the Reinsch–Schoenberg theorem; the representer theorem; and the bound on the maximum of n normals behind the universal threshold. Pause here if you want to try them.

The books this part follows: Silverman on density estimation, Wand and Jones on kernel smoothing, Fan and Gijbels on local polynomials, Green and Silverman and Wahba on splines, Wasserman's All of Nonparametric Statistics and Wood on additive models; with the papers from Rosenblatt to Calonico, Cattaneo and Farrell.

Twenty-nine parts of sixty-five. We can estimate whole curves, and say how fast and how honestly. Robust LOESS already downweighted large residuals, but most examples still trusted every observation. In 1960 John Tukey showed that a few percent of contamination is enough to make the sample standard deviation worse than a crude alternative. When a few points are wrong, everything can be wrong. Part 30: robust statistics.

Where it goes next. Robust smoothing follows in Part 30; local linear fits at a cutoff with robust bias correction become regression discontinuity in Part 37, kernels become Gaussian processes and kriging in Part 39, and Part 50 proves that the rates derived here cannot be beaten.

Key results

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

The histogram\(\displaystyle \mathrm{AMISE}=\frac{1}{nh}+\frac{h^2R(f')}{12},\qquad\allowbreak h^*=\Bigl(\frac{6}{nR(f')}\Bigr)^{1/3}\)
The kernel estimate\(\displaystyle \operatorname{bias}\approx\tfrac12h^2\mu_2f''(x),\qquad\allowbreak \operatorname{Var}\approx\frac{f(x)R(K)}{nh}\)
Its optimal bandwidth and rate\(\displaystyle h^*=\Bigl(\frac{R(K)}{\mu_2^2R(f'')\,n}\Bigr)^{1/5},\qquad\allowbreak \mathrm{AMISE}(h^*)=\tfrac54\bigl(\mu_2R(K)^2\bigr)^{2/5}R(f'')^{1/5}n^{-4/5}\)
The curse of dimensionality\(\displaystyle \mathrm{MISE}\asymp n^{-4/(4+d)}\)
The smoothing spline\(\displaystyle \hat g=\arg\min_g\sum_i\bigl(y_i-g(x_i)\bigr)^2+\lambda\int g''(x)^2\,dx\ \Longrightarrow\ \hat g=(I+\lambda K)^{-1}y,\ \text{a }\allowbreak \text{natural }\allowbreak \text{cubic }\allowbreak \text{spline}\)
The representer theorem\(\displaystyle \hat f=\sum_j\alpha_jk(x_j,\cdot),\qquad\allowbreak \alpha=(K+\lambda I)^{-1}y\)

Try it

Lab 29 · The bandwidth trade-off, exactly and by simulation

Draw 200 points from the film's two-humped stand-in for Old Faithful 150 times, estimate the density at twelve bandwidths, and compare the average integrated squared error with Marron and Wand's exact MISE from statkit.smooth. Then check the rate at which the best MISE falls, and what the normal-reference rule costs.

Figure produced by Lab 29: The bandwidth trade-off, exactly and by simulation
Produced by the lab below, seed 0, in 0.7 s.
python -m videos.stats.labs 29 needs numpy, scipy, matplotlib · download lab29.py · source on GitHub
mean ISE against exact MISE, twelve bandwidths   largest relative gap 2.7%
best bandwidth at n = 200: exact, AMISE formula  0.154, 0.141   (film: 0.154)
simulated ISE is lowest at h =                   0.156   (mean ISE 0.0101; best possible MISE 0.0099)
slope of log best MISE in log n                  -0.759   (film: -0.759; limit -4/5; histogram -2/3)
normal-reference h over the best h, median       2.76   (film: 2.77)
mean ISE with the normal-reference h             0.0513   (film: 0.0511; best possible 0.0099)

Too small a bandwidth is all variance, too large is all bias, and the exact formula says where they balance. The normal-reference rule, tuned for one hump, is nearly three times too wide here.
The code (84 lines; it asserts its own result)
"""Lab 29: simulate a kernel density estimate's integrated squared error and check it against the exact MISE."""

import numpy as np

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

TITLE = "The bandwidth trade-off, exactly and by simulation"
GOAL = ("Draw 200 points from the film's two-humped stand-in for Old Faithful 150 times, estimate the density at twelve "
        "bandwidths, and compare the average integrated squared error with Marron and Wand's exact MISE from "
        "statkit.smooth. Then check the rate at which the best MISE falls, and what the normal-reference rule costs.")
TASKS = [
    "Change the kernel to 'epanechnikov' in smooth.kde. The exact curve is for the Gaussian kernel: how far off is it, and at which h?",
    "Replace the truth by one normal, NormalMixture([1], [0], [1]). How close is the normal-reference bandwidth to the best now?",
    "Add smooth.sheather_jones_h(x) and smooth.lscv_h(x, HS) to the selectors and compare their mean ISE with the film's table.",
]

TRUTH = smooth.NormalMixture([0.35, 0.65], [2.0, 4.3], [0.27, 0.42])  # short and long eruptions
HS = np.geomspace(0.04, 0.8, 12)


def best_h(n):
    hs = np.geomspace(0.01, 1.0, 400)
    m = np.array([TRUTH.kde_mise(h, n) for h in hs])
    return float(hs[m.argmin()]), float(m.min())


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    n, reps = 200, 150
    grid = np.linspace(0.5, 6.8, 316)
    dx, f = grid[1] - grid[0], TRUTH.pdf(grid)
    ise, ise_nr, ratio = np.zeros((reps, len(HS))), np.zeros(reps), np.zeros(reps)
    h_star, m_star = best_h(n)
    for r in range(reps):
        x = TRUTH.rvs(n, rng)
        for k, h in enumerate(HS):
            ise[r, k] = np.sum((smooth.kde(x, grid, h) - f) ** 2) * dx
        h_nr = smooth.normal_reference_h(x)
        ratio[r] = h_nr / h_star
        ise_nr[r] = np.sum((smooth.kde(x, grid, h_nr) - f) ** 2) * dx
    sim = ise.mean(0)
    se = ise.std(0, ddof=1) / np.sqrt(reps)
    exact = np.array([TRUTH.kde_mise(h, n) for h in HS])
    worst = np.max(np.abs(sim - exact) / exact)
    k_sim = int(sim.argmin())
    lab.row("mean ISE against exact MISE, twelve bandwidths", f"largest relative gap {worst:.1%}")
    lab.row("best bandwidth at n = 200: exact, AMISE formula", f"{h_star:.3f}, {TRUTH.kde_amise_h(n):.3f}   (film: 0.154)")
    lab.row("simulated ISE is lowest at h =", f"{HS[k_sim]:.3f}   (mean ISE {sim[k_sim]:.4f}; best possible MISE {m_star:.4f})")
    assert worst < 0.12, "the simulation agrees with Marron and Wand's formula"
    assert abs(np.log(HS[k_sim] / h_star)) < 0.45, "the simulated optimum is next to the exact one"

    ns = np.array([100, 1000, 10000])
    best = np.array([best_h(m)[1] for m in ns])
    slope = np.polyfit(np.log(ns), np.log(best), 1)[0]
    lab.row("slope of log best MISE in log n", f"{slope:.3f}   (film: -0.759; limit -4/5; histogram -2/3)")
    assert -0.8 < slope < -0.72, "the kernel estimate's rate is on its way to n^(-4/5)"

    lab.row("normal-reference h over the best h, median", f"{np.median(ratio):.2f}   (film: 2.77)")
    lab.row("mean ISE with the normal-reference h", f"{ise_nr.mean():.4f}   (film: 0.0511; best possible {m_star:.4f})")
    assert 2.4 < np.median(ratio) < 3.1 and ise_nr.mean() > 3 * m_star, "a one-hump rule oversmooths two humps"
    lab.note = ("Too small a bandwidth is all variance, too large is all bias, and the exact formula says where they "
                "balance. The normal-reference rule, tuned for one hump, is nearly three times too wide here.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    x = TRUTH.rvs(n, rng)
    ax[0].plot(grid, f, color=labs.MUTED, ls="--", label="truth")
    for h, color, name in ((0.04, labs.RED, "h = 0.04: variance"), (h_star, labs.GOLD, f"h = {h_star:.2f}: best"),
                           (smooth.normal_reference_h(x), labs.BLUE, "normal reference: bias")):
        ax[0].plot(grid, smooth.kde(x, grid, h), color=color, lw=1.4, label=name)
    ax[0].plot(x, np.full(n, -0.02), "|", color=labs.GREY, ms=5, alpha=0.5)
    ax[0].set(title="One sample of 200, three bandwidths", xlabel="eruption length (minutes)", ylabel="density")
    ax[0].legend()
    hs = np.geomspace(0.03, 1.0, 200)
    ax[1].plot(hs, [TRUTH.kde_mise(h, n) for h in hs], color=labs.GOLD, label="exact MISE (Marron & Wand)")
    ax[1].errorbar(HS, sim, yerr=2 * se, fmt="o", color=labs.BLUE, ms=4, label="mean ISE of 150 samples, with 2 SE")
    ax[1].axvline(h_star, color=labs.GOLD, lw=0.8, ls=":")
    ax[1].axvline(np.median(ratio) * h_star, color=labs.RED, lw=0.8, ls=":", label="normal-reference h (median)")
    ax[1].set(title="Integrated squared error against bandwidth", xlabel="bandwidth h", ylabel="MISE", xscale="log",
              yscale="log")
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Change the kernel to 'epanechnikov' in smooth.kde. The exact curve is for the Gaussian kernel: how far off is it, and at which h?
  2. Replace the truth by one normal, NormalMixture([1], [0], [1]). How close is the normal-reference bandwidth to the best now?
  3. Add smooth.sheather_jones_h(x) and smooth.lscv_h(x, HS) to the selectors and compare their mean ISE with the film's table.

Problems, with solutions

Try each problem before opening its solution.

1. The histogram's bias and optimal bin. Show that the histogram's integrated squared bias is \(\tfrac{h^2}{12} R(f') + o(h^2)\) and find \(h^*\); evaluate it for \(N(0, \sigma^2)\).

Solution

For x in bin B_j = [t_j, t_j + h), E f̂(x) = p_j/h with p_j = ∫_{B_j} f = h f(t_j) + ½h² f′(t_j) + O(h³). So the bias at x is f′(t_j)(h/2 − (x − t_j)) + O(h²). Squaring and integrating over the bin gives f′(t_j)² h³/12 per bin, so the integrated squared bias is (h²/12) R(f′) + o(h²). The variance is p_j(1 − p_j)/(nh²) ≈ f(x)/(nh), so the integrated variance is about 1/(nh). Minimizing 1/(nh) + h²R(f′)/12 gives h* = (6/(nR(f′)))^{1/3}. For N(0, σ²), R(f′) = 1/(4√π σ³), so h* = (24√π)^{1/3} σ n^{−1/3} = 3.49 σ n^{−1/3}.

2. The kernel estimate's bias and variance. Derive the KDE's bias \(\tfrac12 h^2 \mu_2 f''(x)\) and variance \(f(x) R(K)/(nh)\); minimize the AMISE.

Solution

E f̂_h(x) = ∫K(u) f(x − hu) du. Expand f(x − hu) = f − huf′ + ½h²u²f″ + o(h²). Then ∫K = 1 and ∫uK = 0 give bias ½h²μ₂f″(x) + o(h²). The variance is n⁻¹ Var(h⁻¹K((x − X)/h)), and E h⁻²K²((x − X)/h) = h⁻¹ ∫K²(u) f(x − hu) du = f(x)R(K)/h + O(1). So Var = f(x)R(K)/(nh) + O(1/n). Integrating, AMISE = R(K)/(nh) + ¼h⁴μ₂²R(f″). Its minimizer is h* = (R(K)/(μ₂²R(f″)n))^{1/5}, and the minimum is (5/4)(μ₂R(K)²)^{2/5}R(f″)^{1/5} n^{−4/5}.

3. Epanechnikov's kernel. Show that the Epanechnikov kernel minimizes \(\mu_2^{1/2} R(K)\) among non-negative symmetric kernels.

Solution

The functional μ₂^{1/2}R(K) is invariant to K ↦ K(u/a)/a, so fix μ₂ = 1/5 and minimize ∫K² subject to ∫K = 1, ∫u²K = 1/5 and K ≥ 0. For the candidate K₀ = ¾(1 − u²)₊ and any admissible K, write K = K₀ + δ with ∫δ = 0 and ∫u²δ = 0. Then ∫K² = ∫K₀² + 2∫K₀δ + ∫δ². On |u| ≤ 1, K₀ = ¾ − ¾u², so ∫{|u|≤1} K₀δ = −∫{|u|>1} (¾ − ¾u²)δ. Outside, δ = K ≥ 0 and ¾ − ¾u² < 0, so this term is ≥ 0. Hence ∫K² ≥ ∫K₀², with equality only at K = K₀.

4. The Reinsch–Schoenberg theorem. Prove the Reinsch–Schoenberg theorem: \(\int s''(g'' - s'') = 0\) for the natural spline \(s\) interpolating \(g\).

Solution

Let s be the natural cubic spline with s(x_i) = g(x_i), and h = g − s, so h(x_i) = 0. Integrating by parts on [x₁, x_n], ∫s″h″ = [s″h′] − ∫s‴h′. The boundary term is zero since s″(x₁) = s″(x_n) = 0. On each (x_i, x_{i+1}), s‴ is a constant c_i, so ∫s‴h′ = Σ c_i (h(x_{i+1}) − h(x_i)) = 0. Outside [x₁, x_n], s is linear, so s″ = 0 there. Thus ∫g″² = ∫s″² + ∫h″² ≥ ∫s″², with the same fit to the data. The penalized criterion is therefore minimized by a natural cubic spline, with equality only if h is linear and vanishes at the x_i, i.e. h = 0.

5. The representer theorem. Prove the representer theorem for \(\sum (y_i - f(x_i))^2 + \lambda \|f\|^2_{\mathcal H}\) and solve for \(\alpha\).

Solution

Write f = f∥ + f⊥ with f∥ ∈ span{k(x_i, ·)} and f⊥ orthogonal to it. By the reproducing property, f(x_i) = ⟨f, k(x_i, ·)⟩ = f∥(x_i), so the loss depends only on f∥. Meanwhile ‖f‖² = ‖f∥‖² + ‖f⊥‖², so the minimizer has f⊥ = 0 and f = Σα_j k(x_j, ·). Substituting gives ‖y − Kα‖² + λα′Kα. Setting the gradient −2K(y − Kα) + 2λKα to zero gives K((K + λI)α − y) = 0, solved by α = (K + λI)⁻¹y.

6. The maximum of n normals. Show that \(E \max_{i \le n} |Z_i| \le \sqrt{2 \log(2n)}\) for \(Z_i \sim N(0, 1)\), by Jensen on \(e^{t \max |Z_i|}\).

Solution

Let M = max|Z_i|. For t > 0, Jensen gives e^{tEM} ≤ E e^{tM} ≤ Σ E e^{t|Z_i|} ≤ 2n e^{t²/2}. So EM ≤ log(2n)/t + t/2, and t = √(2 log 2n) gives EM ≤ √(2 log(2n)). A matching lower bound shows EM ~ √(2 log n), with Gaussian tail bounds giving P(max|Zᵢ| > √(2 log n)) → 0 for known noise scale. This is convergence in probability, not a zero finite-sample error probability or an almost-sure guarantee.

Notes and sources

Where it comes back

Idea Returns in
robust smoothing; influence 30
sparse additive models 32
conformal bands for smoothers 34
local linear at a cutoff (RD), robust bias correction 37
Gaussian processes, kriging 39
hazard smoothing; monotone hazards 40
minimax rates (Le Cam, Assouad, Fano) 50
posterior contraction for curves 53
the Coverage Board every part; 65

Glossary

  • Density estimate; ISE; MISE; AMISE: an estimate of a whole density; its integrated squared error for one sample; the average over samples; the leading terms.
  • Histogram; bin width; bin origin; Scott's and Freedman–Diaconis rules: the step estimate and its tuning.
  • Kernel; bandwidth; μ₂(K); R(K); Epanechnikov kernel; efficiency: the bump, its width, its variance and roughness, the optimal shape, and the sample-size price of others.
  • Normal reference; Silverman's rule; LSCV; plug-in (Sheather–Jones); ψ_r functionals; pilot bandwidth: ways to choose h.
  • Mode; critical bandwidth; Silverman's test; smoothed bootstrap: counting humps, and testing how many there are.
  • Curse of dimensionality; n^{−4/(4+d)}; Silverman's table: the rate's decay in d.
  • Nadaraya–Watson; local linear; local polynomial; equivalent kernel; boundary and design bias; LOESS; tricube; bisquare robustness: local regression and its parts.
  • Smoothing spline; natural cubic spline; Reinsch form; smoother matrix; effective df; Demmler–Reinsch basis: the penalized fit, its form, and its spectrum.
  • GCV; REML/GML; splines as mixed models; Bayesian bands: choosing λ, and the posterior view.
  • RKHS; reproducing property; representer theorem; kernel ridge regression; Gaussian process: the general penalized framework and its Bayesian twin.
  • Wavelet; multiresolution; DWT; soft and hard thresholding; MAD σ; VisuShrink; SureShrink; universal threshold: sparse representations and denoising by thresholding.
  • Additive model; GAM; backfitting; partial residual; concurvity: sums of one-dimensional smooths.
  • Pointwise vs simultaneous bands; undersmoothing; bias correction; robust bias-corrected (RBC) intervals; fourth-order kernel: honest inference for curves.
  • Isotonic regression; PAVA; Grenander estimator; least concave majorant; Chernoff's distribution; log-concave MLE: shape-constrained estimation.

Sources

  • History and data.
    • A. Azzalini & A. Bowman, Applied Statistics 39 (1990); W. Härdle, Smoothing Techniques (1991).
    • B. Silverman, JRSS B 43 (1981) and 47 (1985); G. Schmidt, R. Mattern & F. Schüler (1981).
    • J. Chambers, W. Cleveland, B. Kleiner & P. Tukey, Graphical Methods for Data Analysis (1983).
  • Densities.
    • M. Rosenblatt, Ann. Math. Stat. 27 (1956); E. Parzen, Ann. Math. Stat. 33 (1962); V. Epanechnikov, Theory Prob. Appl. 14 (1969).
    • D. Scott, Biometrika 66 (1979); H. Sturges, JASA 21 (1926).
    • J. S. Marron & M. Wand, Ann. Stat. 20 (1992); P. Hall, Ann. Stat. 20 (1992).
  • Bandwidths. M. Rudemo, Scand. J. Stat. 9 (1982); A. Bowman, Biometrika 71 (1984); S. Sheather & M. C. Jones, JRSS B 53 (1991); M. C. Jones, J. S. Marron & S. Sheather, JASA 91 (1996); P. Chaudhuri & J. S. Marron, JASA 94 (1999).
  • Dimension. R. Bellman, Adaptive Control Processes (1961); C. Stone, Ann. Stat. 8 (1980) and 13 (1985); K. Beyer, J. Goldstein, R. Ramakrishnan & U. Shaft, ICDT (1999).
  • Regression.
    • E. Nadaraya, Theory Prob. Appl. 9 (1964); G. Watson, Sankhyā A 26 (1964); W. Cleveland, JASA 74 (1979).
    • J. Fan, JASA 87 (1992); J. Fan & I. Gijbels, Local Polynomial Modelling (1996).
  • Splines and kernels.
    • I. Schoenberg, PNAS 52 (1964); C. Reinsch, Numer. Math. 10 (1967); A. Demmler & C. Reinsch, Numer. Math. 24 (1975).
    • P. Craven & G. Wahba, Numer. Math. 31 (1979); G. Wahba, JRSS B 45 (1983), Ann. Stat. 13 (1985); D. Nychka, JASA 83 (1988).
    • T. Speed, Stat. Sci. 6 (1991); P. Reiss & R. T. Ogden, JRSS B 71 (2009).
    • N. Aronszajn, Trans. AMS 68 (1950); G. Kimeldorf & G. Wahba, Ann. Math. Stat. 41 (1970).
  • Wavelets. A. Haar, Math. Ann. 69 (1910); I. Daubechies, Comm. Pure Appl. Math. 41 (1988); S. Mallat, IEEE PAMI 11 (1989); D. Donoho & I. Johnstone, Biometrika 81 (1994), JASA 90 (1995).
  • Additive models.
    • J. Friedman & W. Stuetzle, JASA 76 (1981); A. Buja, T. Hastie & R. Tibshirani, Ann. Stat. 17 (1989).
    • T. Hastie & R. Tibshirani, Generalized Additive Models (1990); S. Wood, JRSS B 73 (2011).
  • Inference. P. Bickel & M. Rosenblatt, Ann. Stat. 1 (1973); S. Calonico, M. Cattaneo & M. Farrell, JASA 113 (2018).
  • Shape.
    • M. Ayer, H. Brunk, G. Ewing, W. Reid & E. Silverman, Ann. Math. Stat. 26 (1955); U. Grenander, Skand. Aktuarietidskr. 39 (1956).
    • B. L. S. Prakasa Rao, Sankhyā A 31 (1969); R. Barlow, D. Bartholomew, J. Bremner & H. Brunk, Statistical Inference under Order Restrictions (1972).
    • G. Walther, JASA 97 (2002); M. Cule, R. Samworth & M. Stewart, JRSS B 72 (2010).
  • Books.
    • B. Silverman, Density Estimation for Statistics and Data Analysis (1986).
    • M. Wand & M. C. Jones, Kernel Smoothing (1995).
    • P. Green & B. Silverman, Nonparametric Regression and Generalized Linear Models (1994).
    • G. Wahba, Spline Models for Observational Data (1990).
    • L. Wasserman, All of Nonparametric Statistics (2006).
    • S. Wood, Generalized Additive Models (2nd ed., 2017).
About this partfrom its README

Part 29 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the ninth part of Stage III, Master's. Part 28 chose among models with a fixed number of parameters. This part estimates whole curves, densities and regression functions, and asks how fast it can be done:

  • histograms and kernel density estimates, their bias, variance and rates; bandwidth selection; the curse of dimensionality;
  • local polynomials, smoothing splines (with GCV and REML), reproducing kernels and Gaussian processes, wavelets, and additive models;
  • honest intervals for curves (robust bias correction) and estimation under shape constraints.

The rate statements assume the specified smoothness classes and regular designs; n⁻¹/³ for Grenander is a pointwise estimation-error scale, whereas n⁻⁴/⁵ for KDE is a squared-error rate. Local linear boundary bias remains order h² with a different coefficient from the interior. Fixed-dimensional additive rates require an identifiable design, and Bayesian pointwise bands condition on smoothing hyperparameters; their average frequentist coverage requires additional conditions.

Its instrument is the spline spectrum (SplineSpectrum): the Demmler–Reinsch basis of a smoothing spline with the shrinkage factor 1/(1 + λdⱼ) on each component. Its kit is statkit.smooth.

It opens with Old Faithful: 272 observations in R’s datasets::faithful, 36% of them under three minutes. Shifted or halved histogram bins change the picture. Kernel estimates have 12, 3, 2 and 1 modes at h = 0.05, 0.1, 0.25 and 1. Silverman's critical bandwidths are h₁ = 0.831, h₂ = 0.127 and h₃ = 0.086. His smoothed-bootstrap test (500 resamples):

H₀ Critical h p-value Verdict
at most 1 mode 0.831 0.002 (0/500 exceedances) rejected by raw bootstrap
at most 2 modes 0.127 0.50 not rejected
at most 3 modes 0.086 0.93 not rejected

Two broad humps, short and long eruptions, without compelling evidence for a third. Non-rejection does not establish the exact mode count. These are finite-grid, raw Silverman smoothed-bootstrap calculations with a +1 Monte Carlo correction; they are not a calibrated finite-sample level guarantee.

From there the part covers:

  • Histograms.

    • The upgrade of Part 1's bin rules: exact MISE from bin probabilities; AMISE = 1/(nh) + h²R(f′)/12; h* = (6/(nR(f′)))^{1/3}, Scott's 3.49σn^{−1/3}.
    • The truth is a two-humped stand-in for Old Faithful, 0.35 N(2, 0.27²) + 0.65 N(4.3, 0.42²). Its exact MISE is minimized at h = 0.339, 0.153 and 0.071 for n = 100, 1,000 and 10,000 (the formula gives 0.329, 0.153, 0.071).
    • The best MISE falls with slope −0.647 in log n (theory −2/3).
  • Kernel estimates.

    • Bias ½h²μ₂f″ and variance f R(K)/(nh), derived. AMISE, h* ∝ n^{−1/5}, rate n^{−4/5}.
    • Marron & Wand's exact MISE: best h = 0.179, 0.106 and 0.066 (AMISE formula 0.162, 0.102, 0.065).
    • The best MISE falls with slope −0.759, on its way to −4/5. It is 2.5, 3.2 and 4.2 times smaller than the best histogram at n = 100, 1,000 and 10,000.
    • Epanechnikov's kernel by the calculus of variations. Efficiencies: biweight 0.994, triangular 0.986, Gaussian 0.951, uniform 0.930.
  • Bandwidths.

    • On Old Faithful: normal reference 0.394, Silverman 0.335, Sheather–Jones 0.166 (2 modes), LSCV 0.103 (3 modes).

    • 300 samples of n = 200 from the stand-in (h_MISE = 0.154):

      Selector ĥ/h_MISE: median (10%–90%) Mean ISE
      normal reference 2.77 (2.66–2.87) 0.0511
      Silverman 2.35 (2.26–2.44) 0.0359
      LSCV 1.05 (0.72–1.20) 0.0115
      Sheather–Jones 1.23 (1.17–1.30) 0.0107

      The best possible MISE is 0.0099.

  • The curse of dimensionality.

    • The rate n^{−4/(4+d)}. Silverman's table, reproduced exactly: the sample size for relative MSE 0.1 at the centre of a d-variate standard normal.

      d 1 2 3 4 5 6 7 8 9 10
      n 4 19 67 223 768 2,789 10,731 43,736 187,503 841,616
    • The inscribed ball holds 78.5% of the square, 52.4% of the cube and 0.25% of the 10-cube.

    • For 1,000 uniform points, the nearest neighbour is at median distance 0.0004 in 1-D, 0.48 in 10-D and 2.12 in 50-D; the nearest-to-farthest ratio reaches 0.59 at 50-D.

    • Norms concentrate: ‖X‖ ≈ √d ± 0.7.

  • Local polynomials.

    • Nadaraya–Watson vs local linear (Fan 1992): the equivalent kernels at the boundary.
    • On the noise-free line y = 2x, NW gives 0.15 at 0 and 1.85 at 1.
    • Old Faithful's waiting time after an eruption: about 33.5 + 10.7 × length.
    • The motorcycle crash (133 readings): NW and local linear differ by up to 14 g on the steep descent.
    • LOESS and its robustness iterations (Cleveland 1979).
  • Smoothing splines.

    • The Reinsch–Schoenberg theorem for square-integrable weak second derivatives, proved; the Reinsch form (I + λK)⁻¹y. The dense teaching implementation is checked against SciPy’s make_smoothing_spline; an efficient banded Reinsch implementation has linear fixed-penalty solve cost.
    • Motorcycle fits at 4, 8, 12 and 25 df.
    • The Demmler–Reinsch spectrum (eigenvalues growing roughly like the fourth power of the index); ridge regression in that basis.
  • Choosing λ.

    • GCV (Craven & Wahba 1979); splines as mixed models; REML (Wahba 1985); Wahba's Bayesian bands (Nychka 1988).

    • Motorcycle: GCV chooses df 12.4, REML df 14.1 (all 133 observations, including within-time replicate contrasts); residual SD 22.6 g.

    • 300 simulated data sets (n = 100, noise SD 0.3):

      Criterion Chosen df: 10% / median / 90% Mean error Worst 5%
      oracle 9.6 / 11.0 / 12.7 0.0082 0.0178
      GCV 9.6 / 11.0 / 14.6 0.0098 0.0220
      REML 10.3 / 11.0 / 12.3 0.0089 0.0187
  • Kernels.

    • RKHS, the reproducing property, the representer theorem (Kimeldorf & Wahba 1970), proved; kernel ridge regression.
    • Motorcycle fits with Gaussian kernels: 7.4 df at ℓ = 6.5 ms; 17.8 df at 2.0 ms (the GP band, σ̂ = 22.9 g); 56 df at 0.65 ms with small λ.
    • The Gaussian-process reading: the posterior mean equals the kernel ridge fit.
  • Wavelets.

    • Haar and Daubechies-4 by Mallat's pyramid; the MAD noise estimate assuming sparse signal at the finest scale; VisuShrink σ√(2 log n); SureShrink.

    • The maximum of n normals against √(2 log n): medians 1.83 / 2.66 / 3.40 / 3.99 / 4.52 for n = 10 … 100,000.

    • Donoho–Johnstone signals, n = 1,024, SNR 7, MSE per point:

      Signal Noisy VisuShrink SureShrink GCV spline
      blocks 0.99 1.32 0.40 0.71 (356 df)
      doppler 0.96 1.21 0.43 0.35
      heavisine 1.01 0.40 0.10 0.11
      bumps 1.01 2.01 0.62 0.72
  • Additive models.

    • Backfitting (Friedman & Stuetzle 1981; Buja, Hastie & Tibshirani 1989); concurvity.
    • New York's ozone in 1973 (cube root, 111 days), with 4 df each for temperature, wind and solar radiation. The fit converges in 17 sweeps and gives R² 0.759 against 0.681 for the linear model. 10-fold CV error is 0.243 vs 0.270, about 10% lower in this split. Four-df smoothing choices are recomputed on each training fold, and prediction evaluates the natural splines, including linear extrapolation. The paired case-loss difference is −0.0269 ± 0.0191 SE; this does not include variation from rerunning the whole CV procedure.
  • Inference for curves.

    • Bias/SE does not vanish at h* ∝ n^{−1/5}. At the stand-in's long-eruption mode (x = 4.3, n = 300, pointwise MSE-optimal h = 0.137), the estimates average 0.587 against the truth 0.617. That bias of −0.031 (theory −0.033) is 0.58 SD.
    • Undersmoothing; Hall (1992); robust bias correction (Calonico, Cattaneo & Farrell 2018) with the fourth-order kernel M = K − ½K″.
    • Simultaneous bands (Bickel & Rosenblatt 1973).
  • Shape constraints.

    • Isotonic regression by PAVA (18 steps for 60 readings); Grenander's estimator.
    • At x = 1 for exponential data, SD × n^{1/3} = 0.37, 0.41 and 0.39 for n = 100, 1,000 and 10,000. Chernoff's limit is 0.42. The kernel estimate's SD × n^{2/5} = 0.20, 0.26 and 0.28.
    • Log-concave MLEs.

Data:

  • Old Faithful (Azzalini & Bowman 1990; Härdle 1991), the motorcycle crash test (Schmidt, Mattern & Schüler 1981; Silverman 1985) and New York's 1973 air quality (Chambers, Cleveland, Kleiner & Tukey 1983) are the Museum's, via R's datasets and MASS;
  • the rest are seeded simulations.

Built in this part:

  • statkit.smooth (explainer/stats/kit/smooth.py), checked in tests/test_stats_kit_smooth.py:
    • Kernels and histograms:
      • kernels with R(K), μ₂ and efficiencies;
      • the histogram's exact MISE;
      • NormalMixture, with exact R(f^{(r)}) and Marron–Wand MISE.
    • Bandwidths: normal reference, Silverman, closed-form LSCV, the Sheather–Jones plug-in.
    • Modes and dimension: Silverman's critical bandwidths and mode test; Silverman's table.
    • Regression smoothers: local polynomials and LOESS (with robustness); SmoothingSpline (Reinsch form, weights and ties, the smoother matrix, df, GCV, REML, the Demmler–Reinsch basis, evaluation); kernel ridge.
    • Wavelets: Haar and D4 DWT/IDWT, the MAD σ, VisuShrink and SureShrink, Donoho–Johnstone test signals.
    • The rest: backfitting; conventional and robust bias-corrected KDE intervals; the Grenander estimator.
  • The Museum gains faithful(), mcycle() and airquality().
  • The spline spectrum (SplineSpectrum in explainer/stats/viz.py): the first k Demmler–Reinsch basis curves and their shrinkage bars; bars(lam) turns the dial.

The Coverage Board gains three rows. Pointwise 95% intervals for f(4.3), at the stand-in's long-eruption mode, over 2,000 samples of n = 300:

Method Reps Achieved Mean width Verdict
conventional, at the MSE-optimal h 2,000 91.0% 0.214 broken
undersmoothed, h·n^{−1/10} 2,000 95.1% 0.309 kept
robust bias-corrected 2,000 95.4% 0.298 kept
Chapter notes
# Chapter Numbers
0 Old Faithful h₁ 0.83, h₂ 0.13; raw bootstrap p = 0.002 / 0.501 / 0.930
1 Histograms as estimators h* 0.34 / 0.15 / 0.07; slope −0.65
2 Kernel density estimates slope −0.76; Gaussian efficiency 0.951
3 Choosing the bandwidth SJ 0.166, LSCV 0.103; NR 2.8× too wide
4 The curse of dimensionality 4 → 841,616 points from 1-D to 10-D
5 Local polynomials NW 0.15 at the boundary; 14 g apart on the crash
6 Smoothing splines df 4 / 8 / 12 / 25; the spectrum
7 Choosing λ GCV df 12.4, REML 14.1; REML's worst 5% 0.0187 vs 0.0220
8 Kernels and the representer theorem df 7 / 18 / 56; GP band
9 Wavelets SureShrink 0.40 vs spline 0.71 on blocks
10 Additive models R² 0.76 vs 0.68; CV −10% (one split)
11 Inference for curves 91.0% vs 95.4% (RBC)
12 Shape constraints SD·n^{1/3} ≈ 0.39 vs Chernoff 0.42
13 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Old Faithful. Silverman's (1981) mode test.
  2. Histograms as estimators. h ∝ n^{−1/3}, derived (completing Part 1).
  3. KDE. Bias and variance; h ∝ n^{−1/5}; the rate n^{−4/5}; Epanechnikov's kernel by the calculus of variations.
  4. Bandwidths. Silverman; LSCV; Sheather–Jones.
  5. The curse of dimensionality. n^{−4/(4+d)}; Silverman's table.
  6. Local polynomials (Fan & Gijbels 1996). Boundary and design bias; LOESS.
  7. Smoothing splines. The Reinsch–Schoenberg theorem, derived; the smoother matrix and its eigenbasis.
  8. Choosing λ. GCV; REML (Part 25: splines as mixed models).
  9. RKHS and the representer theorem (Kimeldorf & Wahba 1970); kernel ridge; GPs (Part 39).
  10. Wavelets. Sparsity; VisuShrink's σ√(2 log n); SureShrink.
  11. GAMs (Hastie & Tibshirani 1990; Wood 2017); backfitting.
  12. Inference for curves. Bias in pointwise intervals; robust bias correction (Calonico, Cattaneo & Farrell 2018) (Board).
  13. Shape constraints. Isotonic regression and PAVA; Grenander's cube-root rate.
  14. Outro. Upgrade card for Part 50.

Built: statkit.smooth. Data: Old Faithful (license checked).

Build the film

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

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

Build it
python -m videos.stats.stats29.compute         # once (about two minutes)
python tools/build.py stats29 -q l             # fast 480p preview
python tools/build.py stats29                  # 1080p30 -> renders/stats29.mp4
python tools/qa_scene.py stats29 Splines
python tools/lecture_length.py stats29 --floor 50