SStatistics, Built

Stage III · Master's

Part 39 of 65

Space

Master'sstarts at this level55 min of film16 chaptersprerequisites: Part 25, Part 29

How do you predict where nobody measured?

In 1951 Krige values blocks of ore from boreholes with weights that account for how grades covary with each other and with the block. The part builds that predictor on the World's pollution field, hidden but for 300 stations, and on the Meuse flood plain's zinc. A random field has a covariance, Bochner says which functions qualify, and the variogram estimates it. Kriging is the best linear unbiased predictor, derived with a Lagrange multiplier, and it is the posterior mean of a Gaussian process. The Matérn family sets the smoothness, and here the part turns: under infill the variance and the range cannot both be learned, only a ridge of them, though predictions along the ridge barely change. Likelihood costs n cubed, so Vecchia's approximation and sparse precision matrices from the SPDE carry it to 100,000 locations. Areal data, point patterns on Snow's map, spatial confounding and Bayesian optimization follow, and the part ends by cross-validating in spatial blocks, where the error is honest.

What you need. Mixed models and REML (Part 25), smoothing (Part 29), and the multivariate normal's conditioning formula.

Hook
Krige's gold, 1951
Mathematics
variograms, kriging, Matérn, Vecchia, GMRF and SPDE, areal models, point processes, GPs
Built
statkit.spatial

What you will be able to do

Bachelor's

  • Explain Tobler's first law and why 300 correlated stations carry far fewer than 300 observations' worth of information about a mean.
  • Read a kriged map together with its standard-error map.

Master's

  • Estimate and fit a variogram, and read its nugget, sill and range.
  • Derive the kriging weights and show that simple kriging is Gaussian conditioning.
  • Fit a Matérn covariance by REML and approximate the likelihood by Vecchia's method.

PhD

  • State Zhang's result on what is identifiable under infill asymptotics and explain why predictions are nearly constant along the ridge.
  • Explain how the SPDE turns a Matérn field into a Gaussian Markov random field with a sparse precision matrix.

Practice

  • Validate a spatial predictor with blocked cross-validation and standardized errors, not random folds alone.
  • Recognize spatial confounding: a spatial random effect does not remove bias from an unmeasured confounder that varies at the exposure's scale.

Contents

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

  1. 0Krige's boreholesBachelor's2 min
  2. 1Spatial dataBachelor's3 min
  3. 2Random fieldsMaster's3 min
  4. 3VariogramsMaster's4 min
  5. 4KrigingMaster's3 min
  6. 5Matérn and what cannot be learnedPhD5 min
  7. 6Likelihood estimationMaster's3 min
  8. 7Scaling upMaster's4 min
  9. 8GMRFs and the SPDEPhD3 min
  10. 9Areal dataMaster's5 min
  11. 10Point processesMaster's3 min
  12. 11Spatial confoundingPractice3 min
  13. 12Space and timeMaster's3 min
  14. 13Gaussian processes in machine learningMaster's4 min
  15. 14Honest predictionPractice3 min
  16. Recap, problems, and the road aheadAll tracks3 min

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

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Krige's boreholesBachelor's2 min

In 1951 Danie Krige, a young mining engineer on South Africa's Witwatersrand gold fields, published a master's thesis about a very practical question. Mines drilled boreholes and assayed the cores, a few centimetres across, and then had to decide which blocks of ore, many metres across, were worth mining. Naively treating selected rich or poor samples as representative of a whole block misses regression toward the mean and differences in sampling support. The real question was the value of the ground where nobody had drilled. Krige's answer was to weight the samples using how gold grades covary with distance: with each other, and with the block.

The same problem in the World. Here is the pollution field over the island, which in real life nobody ever sees. We see it only at a scattering of measuring stations. And we want its value at a place nobody measured: a new school, a hospital, a home. What should we predict there, and how sure can we be? That is the question of this part.

Georges Matheron, at the Paris School of Mines, turned Krige's idea into a theory in 1962 and 1963, called it geostatistics, and named the method kriging, after Krige. In the Soviet Union, Lev Gandin developed the same method at the same time, for weather maps. It is the same mathematics as Wiener and Kolmogorov's prediction of stationary processes, and as the Gaussian processes of modern machine learning. It is now used for mining, air pollution, climate, epidemiology and ecology, and, chapter thirteen, for tuning neural networks.

Part thirty-eight's dependence ran in one direction, from the past. In space it runs in every direction at once, and there is no natural order to filter along. How do values covary with distance? How should we predict from them? And what can, and cannot, be learned from one realization of a field? We'll also meet counts in areas, points in a window, and fields that change in time.

Numbers: 1951

1Spatial dataBachelor's3 min

Waldo Tobler, a geographer, wrote in 1970: everything is related to everything else, but near things are more related than distant things. He called it the first law of geography. It is the reason spatial data break the independence that most of statistics assumes, and the reason prediction at unmeasured places is possible at all.

Noel Cressie's textbook sorts spatial data into three kinds. Geostatistical data: a field that exists everywhere, measured at chosen sites, such as zinc in soil or pollution in air. Areal or lattice data: one value for each of a fixed set of regions, such as disease rates by district. And point patterns, where the locations themselves are the random part: where the cases occurred, where the trees grow.

A real field. In 1993 Mathieu Rikken and Ruud van Rijn sampled the topsoil at a hundred and fifty-five places in a flood plain of the river Meuse, near the Dutch village of Stein, and measured heavy metals. Here is zinc, with bigger, brighter dots for higher concentrations, on a log scale. The river, in blue, deposits contaminated sediment when it floods. So zinc is high near the river and low inland: a trend, plus deviations that are themselves correlated between neighbouring samples.

And the World's field, which we will keep using because, unlike Meuse, its truth is known everywhere. Fine-particle pollution is twenty units, plus three times a traffic index that is high around the big towns, plus a smooth random field. It is highest in the cities, and varies smoothly between them. Three hundred stations measure it, each with a small measurement error.

The standard model writes the value at location s as three parts. A trend, a regression on covariates such as distance to the river or traffic. A random field with mean zero, whose covariance between two places depends on how far apart they are. And independent noise, which geostatisticians call the nugget, after the nuggets of gold that make two samples a few centimetres apart differ.

Why does dependence matter? The variance of an average is a sum over every pair of observations of their covariance, not just the n variances. Divide the variance of one value by it, and we get the effective sample size: the number of independent values the average is worth. For the World's three hundred stations, with the true covariance, it is . On an island only a few ranges wide, the stations give limited independent information about a trend-removed ensemble mean level under the specified covariance model. This calculation is not the prediction-error standard deviation for this realized island's spatial average. The model-based standard error of the trend-removed station mean is , seven times the textbook formula's . Prediction at a place is a different matter: there, nearby stations are exactly what we want.

Numbers: n_eff = 5.7 of 300

2Random fieldsMaster's3 min

A random field assigns a random variable to every point of a region. It is stationary if its mean is constant and the covariance between two points depends only on the displacement between them. It is isotropic if only the distance matters, not the direction. And it is Gaussian if every finite collection of its values is jointly normal, so that the covariance function says everything. As in Part thirty-eight, we usually see only one realization: one island, one field. Learning from a single field needs assumptions about the sampling regime. Expanding-domain ergodic arguments and fixed-domain infill results give different possibilities.

Not every function can be a covariance. Every linear combination of the field's values must have a non-negative variance, so the covariance must be positive definite. Salomon For continuous covariance functions on Euclidean space, Bochner's theorem of 1933 gives the characterization: exactly the Fourier transforms of non-negative measures, the spectra. It is Part thirty-eight's Herglotz theorem, in any number of dimensions. A consequence that surprises people: whether a function is a valid covariance can depend on the dimension. A triangle is a valid covariance on a line but not in space. So geostatistics works with families known to be valid.

Four seeded fields with different covariances, using positive-semidefinite checked circulant embeddings. With an exponential covariance, the field is continuous but rough, like a random walk in every direction. With the Matérn covariance of smoothness three halves, it is once mean-square differentiable. With five halves, twice: smoother still. And with the same smoothness but a range a third as long, the same kind of surface, but its hills and valleys are three times closer together. Smoothness and range are different properties, and the covariance must describe both.

The standard families. The exponential, rough. The Gaussian, which makes the field infinitely differentiable, an exceptionally strong smoothness assumption that can be inappropriate for physical interpolation, as Michael Stein warned should rarely be used. The spherical, which drops to exactly zero beyond its range, and was Matheron's favourite. And the Matérn family, which contains the exponential and the Gaussian as special cases and has a parameter for smoothness: the subject of chapter five.

Numbers: Bochner

3VariogramsMaster's4 min

Geostatisticians usually describe dependence by the semivariogram: half the expected squared difference between values a distance h apart. For a stationary field it is the variance minus the covariance: the covariance turned upside down. Matheron's estimate averages half the squared differences of all pairs whose separation falls in each distance bin. It needs no estimate of the mean, and it exists for fields with stationary increments even when the covariance does not, like the random walk of Part thirty-eight.

The empirical semivariogram of log zinc at Meuse, in fifteen distance bins, each dot sized by the number of pairs behind it. It rises with distance, as Tobler's law says it should, the fitted spherical model then levels off: beyond its range it assigns zero residual covariance, as if comparing two random ones. A spherical model, fitted by Noel Cressie's weighted least squares of 1985, has a nugget of , a partial sill of , and a range of kilometres.

Its three features have names. The nugget is the jump at the origin: two samples a hair apart still differ, because of measurement error and variation at scales smaller than the sampling. The sill is the plateau, the total variance of the field. And the range is the distance at which the plateau is reached, where correlation ends.

Squared differences are sensitive: one outlying sample enters every pair it belongs to, and can dominate a bin. Noel Cressie and Douglas Hawkins proposed in 1980 to average the square roots of the absolute differences instead, then raise the average to the fourth power and correct its bias, Part thirty's robustness applied to variograms. On log zinc the two estimates are close, consistent with the logs reducing the influence of large concentrations; agreement does not establish that no outliers remain.

Isotropy is an assumption, and it can be checked. Group the pairs of samples by the direction between them, and compute a variogram for each direction. North to south and east to west lie in between. Along the north-east diagonal, the direction the river runs, values change most slowly: across the river they change fastest, because moving away from the bank changes how often the soil was flooded. These raw directional differences can reflect the river-distance trend as well as anisotropic residual covariance. Genuine geometric anisotropy can be modelled by stretching the coordinates before using an isotropic model, and universal kriging's river-distance trend absorbs much of it here.

The World's stations, after subtracting the traffic trend. The true variogram, in gold, levels off at total sill six point eight nine, including the nugget. The World uses a very fine numerical approximation to the Matérn grid covariance. The empirical one tracks it at short distances, then keeps rising. The island is only a few ranges wide, and at large distances the bins rest on pairs that are all part of one realization, so they are noisy and dependent. Variograms are best trusted at the distances that matter for prediction: short ones.

Numbers: nugget 0.054, partial sill 0.585 (total sill 0.639), range 0.90 km

4KrigingMaster's3 min

Kriging predicts the value at a new site as a weighted average of the observations. For the prediction to be unbiased whatever the unknown constant mean, the weights must add to one. Among such weights, choose the ones that minimize the variance of the prediction error. That variance involves K, the covariances among the observations, and k nought, their covariances with the new site. A Lagrange multiplier turns the problem into one linear system. With the specified covariance, its solution often gives nearby sites more weight and discounts samples that cluster together. Weights depend on the full covariance and may be negative; proximity alone does not determine them.

Three versions. Simple kriging assumes the mean is known. Ordinary kriging, the one just derived, assumes only that it is constant. Universal kriging allows a trend in covariates, estimated by the generalized least squares of Part twenty-three, and then kriges the residuals. Each comes with a prediction variance: zero at an observed site when there is no nugget, rising to the sill far from all data, plus the uncertainty of the estimated trend.

Universal kriging of log zinc over Meuse's prediction grid, with the square root of the distance to the river as the trend. Zinc falls with distance from the river, as the trend coefficient says, and the kriged residuals add the local detail the trend misses. On the right, the kriging standard error: smallest right beside the samples, in white, largest in the gaps between them and at the edges.

How much does it help? Leave out each sample in turn, fit the variogram and trend using only the other samples, then predict it. Covariance fitting is inside every fold. The overall mean misses by on the log scale. Inverse-distance weighting, the usual ad hoc interpolator, by . Ordinary kriging by , and universal kriging with the river's distance by : almost half the error of the mean.

The World lets us check against the truth. On the left, the true field; on the right, universal kriging with the traffic index, from the three hundred stations. The darkening marks the kriging standard error: largest in the empty interior and at the coasts. Over the whole island, kriging misses by , against for the traffic trend alone. Its ninety percent intervals cover percent of the island in this one field. With one realization, coverage over space is itself noisy; chapter fourteen averages over many fields.

Kriging has a Bayesian reading. Treat the field as a Gaussian process: a prior over functions. Conditioning on the observations, by Part five's conditional normal, gives a posterior mean and variance that are exactly simple kriging's, and with known covariance, full-rank trend design and a proper resulting posterior, universal kriging is what an improper flat prior on the trend coefficients gives. Statisticians, geologists and machine-learning researchers found the same object three times.

Numbers: LOO RMSE 0.724 → 0.376

5Matérn and what cannot be learnedPhD5 min

Bertil Matérn, a Swedish forester, wrote down this family in his 1960 thesis on the spatial variation of forests. It has a variance sigma squared, a range rho, and a smoothness nu, with K nu a modified Bessel function. At half-integers it has closed forms: the exponential at one half, and at three halves an exponential times a linear term. The point of nu: the field is k times mean-square differentiable exactly when nu exceeds k. As nu grows without bound, the Matérn becomes the Gaussian covariance, infinitely smooth.

The correlation curves, with range one. The exponential leaves zero with a corner: a linear drop, the signature of a rough field. At three halves and five halves the curve leaves zero flat, and at nu equal twenty it is nearly the Gaussian curve. The shape near zero is what determines the smoothness; the tail determines how far dependence reaches. Prediction depends mostly on the first.

By Bochner's theorem, the Matérn has a spectrum, and it is simple: an inverse power of a constant plus the squared frequency. At high frequency it decays like a power law, and nu sets the exponent: a smooth field has little power at high frequencies. Peter Whittle noticed in 1954 that the Matérn field solves a stochastic partial differential equation driven by white noise, which will make it fast in chapter eight.

Michael Stein's book of 1999 has a famous summary: use the Matérn model. His argument uses infill asymptotics, where data accumulate in a fixed region, which is the honest picture for one island or one mine. Under infill, kriging with a wrong covariance is still asymptotically efficient, provided the wrong covariance has the right high-frequency behaviour. So the smoothness matters, and the range much less. And the Gaussian covariance, which forces infinite smoothness, gets exactly the important thing wrong.

An experiment. Eighty fields, each observed at three hundred random points in the unit square, with an exponential covariance of range point three and variance one. Fit each by maximum likelihood, and plot the estimated range against the estimated variance. The estimates do not cluster around the truth; they scatter along a ridge, each varying by and percent. The ridge is the green line, along which the ratio of variance to range stays at its true value.

Hao Zhang proved in 2004 that this is not a failure of the method. For Gaussian Matérn fields of known smoothness in dimensions at most three on a fixed bounded domain, certain different variances and ranges give equivalent Gaussian measures, so no estimator consistently gets both right as sampling becomes denser in that domain. Equivalent measures are not identical finite-sample distributions, and growing the spatial domain changes the problem. What can be estimated is the combination sigma squared over rho to the two nu, called the microergodic parameter. In the experiment its estimate varies by only percent. The combination supports asymptotically efficient local prediction under additional regularity; finite predictions and uncertainty still depend on variance and range separately. A parameter that fixed-domain infill cannot consistently separate can still matter in a finite study.

The World shows why it does not matter. Krige its field with the true covariance: the error over the island is , and the intervals cover percent. Now double the range and multiply the variance by eight, which keeps the microergodic parameter fixed. The predictions, their standard errors and the coverage barely move. The same on the other side of the ridge. But double the range alone, leaving the ridge, and the standard errors shrink and coverage falls to percent; halve it, and the intervals become too wide. This one-field comparison shows similar predictions along the ridge; it does not establish that finite data distributions or predictions are identical.

Numbers: CV 38% vs 9%

6Likelihood estimationMaster's3 min

Variogram fitting by eye or by least squares was the geostatistician's way. Statisticians prefer the likelihood. For a Gaussian field, the whole data vector is a single draw from a multivariate normal, with mean X beta and a covariance built from the field and the nugget. The log-likelihood has a log-determinant and a quadratic form. For fixed covariance parameters the best beta is generalized least squares, so we can profile it out and maximize over the few covariance parameters numerically. Kanti Mardia and Roger Marshall gave the asymptotics in 1984.

With a known correlation shape, maximum likelihood for the scale is biased downward because it treats the estimated trend as if it were known: the familiar n against n minus p. With jointly estimated covariance shapes the bias comparison is more complicated, and REML is not universally unbiased. Restricted maximum likelihood uses only the error contrasts, linear combinations of the data whose distribution does not involve beta at all. The result is the profile likelihood with one extra term, a log-determinant that penalizes the trend, and for independent data it gives back the familiar residual variance with n minus p in the denominator.

Both fits on the World's stations, with smoothness three halves. Restricted likelihood gives a range of and a variance of , against the truth of one point five and six point two five; in this fit maximum likelihood gives smaller values of both, which is not a universal ordering theorem. Both overshoot the range and the variance together, along chapter five's ridge: one island cannot separate them. The trend coefficients, which matter most for the predictions, are close to the truth.

Can the data choose the smoothness? Fit the World with nu of one half, three halves and five halves. The true value wins, by log-likelihood units over the nearest rival: a modest margin, but the data lean the right way, because smoothness governs the behaviour at short distances, where three hundred stations give many close pairs. The estimated range moves to compensate. In practice one compares a few half-integers by likelihood or cross-validation, or lets the optimizer estimate nu along with the rest.

The catch is the cost. Every evaluation of the likelihood needs the Cholesky factor of an n by n covariance matrix. That is n squared memory and n cubed time; the gold line has slope three. Two thousand locations take seconds per evaluation, and the optimizer needs hundreds of evaluations. A hundred thousand locations, a modest satellite image, under a simple cubic extrapolation from this machine and load would take about hours for each one. Chapter seven is about getting around this.

Numbers: ν = 3/2 wins; cubic timing extrapolation 12.3 hours

7Scaling upMaster's4 min

Any joint density factors exactly, by the chain rule, into a product of conditionals: each value given all the earlier ones. Aldo Vecchia's idea of 1988: condition each value only on its m nearest earlier neighbours. Each factor then needs only an m by m matrix, so the cost grows linearly in n. It can work well through approximate screening under suitable covariance and observation conditions: once you know values close to a point, distant ones add almost nothing, This is not exact conditional independence for a general Matérn field. Our fast implementation searches among four m nearest overall candidates and may retain fewer than m earlier points.

In a picture. Put the locations in some order. When we reach point forty-six, the exact conditional would involve all forty-five earlier points. Vecchia keeps only its five nearest earlier neighbours. Each factor is a small regression on a few neighbours, and they can all be computed in parallel.

How good is it? Two thousand points from a smooth Matérn field with a nugget. With one neighbour, the log-likelihood is off by units; with ten, by ; with thirty, by . The nugget slows the convergence: neighbours measured with noise screen off the rest less well. Modern versions condition on the noise-free field instead, and get much closer with few neighbours.

For estimation, what matters is the shape. The exact log-likelihood as a function of the range, and Vecchia's with ten neighbours, each shifted to peak at zero. Here their maxima on the displayed grid are close to the generating range. This is one realization, not a guarantee that the estimates coincide. In this example Vecchia's curve is flatter, so intervals read off this curve would be wider. Curvature and uncertainty calibration can be distorted in either direction, and the approximation can move an estimate; it needs validation.

Now a timing benchmark with a hundred thousand jittered land-node locations on the World's island. The field values are reused from the nearest selected grid nodes, so this is a speed illustration rather than an exact covariance-model simulation at the jittered sites. The exact likelihood would need about hours and eighty gigabytes of memory for the matrix alone. Vecchia with ten neighbours takes seconds on one core. Abhirup Datta and colleagues turned the idea into a prior, the nearest-neighbour Gaussian process of 2016, so that Bayesian spatial models with millions of locations can be fitted by MCMC.

Other ways to scale. Tapering multiplies the covariance by a function that is exactly zero beyond some distance, so the matrix becomes sparse. Low-rank methods represent the field through a few hundred knots, but they smooth away the short-range detail. Vecchia makes the inverse Cholesky factor sparse. And Markov random fields make the precision matrix sparse, the subject of chapter eight. A 2019 competition led by Matthew Heaton put all of them on the same large data set; the Vecchia-type and SPDE methods did best.

Numbers: 100,000 sites in 4.3 s (this machine/load)

8GMRFs and the SPDEPhD3 min

A different route to speed works with the precision matrix, the inverse covariance, rather than the covariance. As in Part thirty-one's graphical models, a zero in the precision means two values are conditionally independent given all the others. The conditional mean of each value is then a weighted average of its neighbours alone. Julian Besag showed in 1974 how to build a valid joint distribution on a lattice from such local conditionals: a Gaussian Markov random field.

Here is a lattice of sixty by forty, two thousand four hundred values. On the left, the whole precision matrix of a small twelve by eight version: a few diagonal bands, for the neighbours in the same row of the lattice and in the rows above and below. Of the entries, only are nonzero, because each value interacts only with the twelve closest. Sparse Cholesky factorization on a two-dimensional lattice costs about n to the three halves, instead of n cubed.

The bridge from Matérn fields to sparse precisions is Whittle's equation from chapter five. On the whole Euclidean domain, under the stationary construction, its solutions have Matérn covariance. Kappa determines the range; finite grids and boundaries introduce approximation. Discretize the operator on a grid, and the precision is a square of a sparse matrix built from the graph Laplacian: this is what made the sparsity pattern we just saw. Finn Lindgren, Håvard Rue and Johan Lindström showed in 2011 how to do this with finite elements on any triangulated mesh, including irregular regions and the sphere. A continuous Matérn field, with the speed of a Markov field.

On the left, a sample from this Markov field. This small teaching implementation uses dense Cholesky for sampling; the conditioning solve is sparse. On the right, its conditional mean given a hundred and fifty noisy observations, in white. The conditioning is one sparse linear solve: the precision of the posterior is the prior precision plus a diagonal term at the observed sites. The reconstruction misses by standard deviations: the large features are recovered, the small ones between observations are not, and could not be.

Håvard Rue, Sara Martino and Nicolas Chopin built on the Markov structure an approximation method called INLA, the integrated nested Laplace approximation of 2009. It handles latent Gaussian models: a Markov random field, or the SPDE field, inside a generalized linear model, for counts, rates or binary outcomes. It gives posterior marginals in seconds or minutes where MCMC, Part twenty-seven, takes hours. The price is that it is an approximation, and only for models whose latent layer is Gaussian. For spatial epidemiology, it became the standard tool.

Numbers: 30,204 of 5.76M

9Areal dataMaster's5 min

Areal data come as one value per region, and dependence is described by a graph: which regions are neighbours. Patrick Moran's statistic of 1950 is a correlation between each region's value and its neighbours' values. Under random permutation of exchangeable values its expectation is close to zero. To diagnose departure from that exchangeable-values reference, permute the values over the map, as in Part sixteen, and see how often a random arrangement looks as clustered.

The World's two hundred towns, each with a count of new cases of a respiratory disease over a year, and its expected count from its population. Call two towns neighbours if either is among the other's five nearest. The plotted curve is a normal approximation using the permutation mean and standard deviation. The actual p-value uses the permutations; their reference distribution is centred near zero. The observed value is , with a p-value of . The simulator makes neighbouring risks similar through shared pollution. Unequal expected counts make these raw log rates heteroskedastic, so exchangeability is not the null of independent equal-risk Poisson counts. This permutation result is exploratory and does not establish a pollution effect from real data. Here the towns breathe the same air: the pollution field of the earlier chapters.

The usual map shows the standardized morbidity ratio: observed over expected cases. Its variance is roughly the risk over the expected count, so for a small town it is huge. Among the smallest quarter of the World's towns, the ratios run from zero to . The highest and lowest rates on the map are the smallest towns, Part twenty-five's kidney cancer map once more.

Julian Besag, Jeremy York and Annie Mollié proposed in 1991 a model that became the standard for disease maps. The counts are Poisson, with a log relative risk made of two random effects. One is spatial: given its neighbours, each town's effect is normal around their average, the intrinsic conditional autoregression, a Markov random field. The other is independent noise for each town. The result is Part twenty-five's partial pooling, but local: each town is pulled toward its neighbours rather than toward the overall mean, and the smaller the town, the harder the pull.

Two classical models for areas. The conditional autoregression, Besag's CAR, specifies each region's distribution given its neighbours: normal, around a multiple rho of their weighted sum. Compatible Gaussian conditionals give precision T inverse times I minus rho W, which must be symmetric positive definite. Not every choice of neighbour weights and conditional variances is compatible. This defines a Markov random field on the map's graph. The simultaneous autoregression, from Whittle and the econometricians, writes all the regions at once, as a regression on their neighbours plus noise. Its precision is a product, so it is less sparse, and the two models imply different correlations for the same W. For the row-standardized neighbour-average specification, rho one gives the intrinsic CAR. It needs centering or other identifiability constraints and a proper resulting posterior; it is not automatically a proper prior on unconstrained levels.

The three maps, with dot size showing population. The raw ratios: a speckle, with the brightest and darkest dots mostly small towns. The teaching fit uses fixed precision parameters and a small proper ridge approximation to the intrinsic CAR, and reports posterior modes rather than integrated posterior means. In these smoothed risks the speckle is gone, and a pattern appears, higher in the towns near the busy centres. And the true risks, which only the World knows: the smoothed map is much closer to them.

Against the truth, town by town. The raw ratios scatter widely, with a root mean squared error of . The smoothed risks hug the diagonal, with , about a third. They are a little too flat: the highest risks are underestimated and the lowest overestimated, the bias that buys the variance reduction, exactly as with James and Stein.

Numbers: I = 0.085; RMSE 0.58 → 0.18

10Point processesMaster's3 min

In late August 1854 cholera killed hundreds of people in a few streets of Soho, in London. John Snow, whose natural experiment we met in Part thirty-seven, mapped every death, by house. He also marked the public water pumps, and the deaths crowded around one: the pump on Broad Street. These are his points, as digitized by Waldo Tobler, of the first law of geography.

Assign each digitized death to the nearest pump by straight-line distance. This is not a reconstruction of Snow's walking-distance boundaries. of the deaths, percent, are nearest the Broad Street pump; the next pump has . Snow persuaded the parish to remove the pump's handle on the eighth of September. The epidemic was already declining, so the removal proved little by itself; the map, and the brewery and workhouse whose workers drank other water and were spared, made the case.

For points, the null model is complete spatial randomness: a Poisson process with constant intensity, where points neither attract nor repel. Brian Ripley's K function of 1976 counts the expected number of other points within a distance r of a typical point, divided by the intensity. Under complete randomness it is the area of a disc, so its square-root version, Besag's L, is a straight line. L minus r above zero means clustering at that scale, below zero means regularity, like trees competing for light.

Simulate a hundred and ninety-nine random patterns of the same size in the same window, At each distance separately, their two point five and ninety-seven point five percent quantiles give the band. It is a pointwise reference, not a simultaneous ninety-five percent band for the whole curve. The window was chosen using the deaths, so this is exploratory rather than a calibrated global test. Snow's deaths lie far above it, at every scale: the deaths are strongly clustered.

But this test answers the wrong question. People do not live at random, so deaths would cluster wherever the houses are, with or without a contaminated pump. The right comparison is a process whose intensity follows the population at risk. Adrian Baddeley, Jesper Møller and Rasmus Waagepetersen's inhomogeneous K function does that, and epidemiologists compare the cases with controls drawn from the same population, as Snow in effect did by counting who drank from which pump.

Models for points start from the Poisson process, whose counts in disjoint regions are independent Poisson variables with mean the integral of the intensity. David Cox in 1955 made the intensity itself random. In the log-Gaussian Cox process, the log intensity is a regression plus a Gaussian process: clustering comes from the hills of the hidden field. Approximating the intensity integral on a fine grid and using an SPDE approximation gives a Poisson latent Gaussian model, so chapter eight's tools fit it.

Numbers: 359 of 578

11Spatial confoundingPractice3 min

A common situation in environmental epidemiology: regress a health outcome on an exposure, such as pollution, across places. There is almost always an unmeasured spatial variable, income or smoking, that varies smoothly over the map and affects both. A widespread hope is that adding a spatial random effect to the regression will soak up the unmeasured confounder and adjust the exposure's coefficient. A test: sixty seeded fields, where the exposure and the confounder are smooth fields of the same range with correlation point eight, and the true coefficient is one.

The gold dashed line is the truth. Ordinary least squares, which ignores the confounder, averages : the true one plus the point eight that the confounder contributes. The spatial model, generalized least squares with a Matérn random effect fitted by REML, averages . It is just as biased, and more precise about its wrong answer. When the spatial variable is independent of the exposure, both are unbiased, and the spatial model is far more precise, with a standard deviation of against . The random effect buys efficiency, not adjustment.

Why not? Generalized least squares estimates beta from whatever variation in the exposure the covariance treats as informative. When the exposure is a smooth field, its variation lies in the same large-scale patterns as the confounder's, as James Hodges and Brian Reich showed in 2010. The random effect and the exposure then compete for the same patterns, and nothing in the data says which deserves the credit: collinearity in disguise. Christopher Paciorek showed the same year that under his model assumptions, additional exposure variation at finer scales than the confounder can reduce bias. Fine-scale variation is useful only when it is sufficiently unconfounded; a difference in smoothness alone is not causal identification.

A once-popular fix, restricted spatial regression, makes the random effect orthogonal to the exposure, so the two no longer compete. But that simply hands every shared pattern to the exposure: in the standard Gaussian linear formulation with a flat coefficient prior it can return the ordinary least squares estimate, confounding and all, and intervals can be too narrow. Later work, by Ephraim Hanks and colleagues and by Kori Khan and Catherine Calder, recommends against it. Newer methods, such as Emiko Dupont's spatial plus, first remove the smooth part of the exposure, so that only its fine-scale variation is used, which is Paciorek's idea made into a method under further assumptions; this does not automatically identify a causal effect.

The lesson. A correctly specified spatial error model can improve standard errors for dependence; estimated covariance uncertainty still matters, which matters a great deal, as chapter fourteen's Board will show. It does not remove confounding. That still requires measuring the confounder, or a design that makes it irrelevant, the tools of Parts thirty-five to thirty-seven. Spatial structure in the residuals is a warning, not a remedy.

Numbers: 1.80 vs 1.81

12Space and timeMaster's3 min

When the field changes in time, the covariance depends on a spatial lag h and a time lag u. The easy choice is separable: a spatial covariance times a temporal one. On a full grid of sites and times the covariance matrix is then a Kronecker product, which is cheap to factor. But separability says the spatial pattern of correlation is the same at every time lag, only scaled down, which is physically odd: weather systems move, and what happens here today happens further away tomorrow.

The spatial shape at three time lags, normalized by the covariance at zero spatial lag for each time lag. This compares shapes rather than absolute cross-time correlations. Under separability the three curves are one curve: the spatial shape never changes. Under Tilmann Gneiting's non-separable family, the spatial correlation spreads out as the time lag grows: values far apart in space are related across a longer time gap.

Gneiting's family of 2002, valid for positive variance, a and c, alpha and gamma between zero and one, beta between zero and one, and nonnegative delta, in the displayed spatial dimension. The time lag enters through a function psi, here a power plus one, and a single parameter beta between zero and one sets the space-time interaction. At zero, the model is separable, so separability becomes a hypothesis the data can test. Proving such functions valid, positive definite in space and time together, is the hard part, and Gneiting did it through Bochner's theorem and mixtures.

The World's stations also report every day for a year. Each day's reading is the station's annual level, plus that day's weather, shared across the island, plus noise. The station-average daily reading has a lag-one autocorrelation of , which is the autoregressive weather of Part seventeen, with coefficient point seven.

Subtract each station's own mean, and correlate the daily anomalies of pairs of stations. The correlation is at every distance, approximately the model's weather share of daily variance, with finite-series variation. A signal shared by the whole region looks, in the spatial covariance like a component that does not decay with distance. It cancels from same-day spatial differences and is invisible to that variogram. It must be modelled first, as a time series, before any spatial structure in what remains can be seen.

In practice, space-time models are often dynamic: a spatial field that evolves by an autoregression, which is Part thirty-eight's Kalman filter with a field for a state. Or a stochastic partial differential equation with advection and diffusion, whose discretization is again sparse. Climate reanalyses, air-quality forecasts and maps of epidemic spread are built this way. Noel Cressie and Christopher Wikle's book of 2011 is the reference.

Numbers: 0.64 at every distance

13Gaussian processes in machine learningMaster's4 min

Machine learning rediscovered kriging in the 1990s, under other names. Kriging is Gaussian process regression. The covariance is the kernel. The range, sill and nugget are the length-scale, the signal variance and the noise. Fitting them by likelihood is maximizing the marginal likelihood, and the kriging variance is the predictive uncertainty. Carl Rasmussen and Christopher Williams's book of 2006 is the machine-learning reference.

Machine learning fits the kernel's hyperparameters by the log marginal likelihood, which is chapter six's likelihood with the field integrated out. Its first term rewards kernels under which the observed data are typical. Its second penalizes kernels that spread their probability over many possible data sets, such as a very short length-scale, which could fit almost anything. The quadratic data-fit and log-determinant terms must be assessed jointly; more wiggle does not invariably improve fit or make either term monotone. David MacKay called this the automatic Occam's razor of Bayesian evidence, the same balance as Part twenty-eight's model choice.

Before machine learning, statisticians had already moved kriging off the map. Jerome Sacks, William Welch, Toby Mitchell and Henry Wynn wrote in 1989 on the design and analysis of computer experiments. A simulator, a climate model or a crash test, may take hours for each run. Run it at a few well-chosen inputs and krige the outputs over the input space: an emulator, cheap to evaluate anywhere. For a deterministic simulator, a zero-noise GP with nonsingular covariance interpolates, and its variance shows where the emulator is unsure, and so where to run the simulator next.

That leads to Bayesian optimization. We want the minimum of an expensive function, and have evaluated it a few times. Donald Jones, Matthias Schonlau and William Welch's expected improvement of 1998 asks, for each candidate input, how much we expect to beat the best value so far, under the Gaussian process's predictive distribution. It has a closed form, and it balances two pulls: a low predicted mean, exploitation, and a high predictive spread, exploration. Evaluate next where it is largest, update, and repeat.

A one-dimensional example. A function with two dips, hidden from the optimizer, evaluated at three points. The Gaussian process's mean and band, and below, the expected improvement, which points first to the unexplored right side. Each new evaluation updates the process. The first tries probe the right, where the band was wide, and then the search moves left, into the deeper dip.

The true minimum is at . Bayesian optimization found within eight evaluations, counting the first three. This run makes eleven function evaluations in total; its best point is first reached at evaluation eight. Exhaustively evaluating the 401-point reference grid costs four hundred and one evaluations. That grid optimum is not a certified continuous global optimum. Jasper Snoek, Hugo Larochelle and Ryan Adams showed in 2012 that this beats experts at tuning the hyperparameters of neural networks, where each evaluation is a full training run. Krige's mine valuation, choosing learning rates.

The connections run further. Radford Neal showed in 1996 that the prior over functions of a single-hidden-layer network, with appropriately scaled independent weights and suitable activation moments, converges to a Gaussian process as width grows. This is not a statement that any trained network is a GP. Part twenty-nine's kernel ridge regression is the posterior mean of a Gaussian process, and George Kimeldorf and Grace Wahba showed in 1970 that smoothing splines are too. One mathematical object, found independently by miners, meteorologists, statisticians and computer scientists.

Numbers: best reached on evaluation 8; 11 overall; 401-point reference grid

14Honest predictionPractice3 min

The kriging variance is exact when the covariance is known. In practice we plug in estimated parameters and ignore their uncertainty, which tends to make intervals too short, as Dale Zimmerman and Noel Cressie showed. A Bayesian analysis integrates over the parameters; a parametric bootstrap can correct the variance. And if the covariance family is wrong, Stein's theory says the predictions can survive, but the variances need not. Only coverage, measured, can tell.

First, cross-validation. Fit the covariance and trend within each training fold, then predict held-out stations. With random ten-fold validation, kriging misses by . Hold out whole blocks of the island instead, and it misses by , because the held-out stations are farther from the training data, as the distance column shows. Random folds measure interpolation, blocks measure extrapolation. Kriging variance reflects distance under its fitted model, but this does not guarantee coverage. Read the empirical coverage separately for each design, allowing for dependent errors and estimated parameters. The lesson, from David Roberts and colleagues in ecology: choose the cross-validation that matches the distances at which you will actually predict.

Real data allow the same check. Predict each Meuse sample from the other hundred and fifty-four, by universal kriging, and divide the error by the kriging standard error. With known Gaussian covariance the standardized prediction errors are marginally normal. Here covariance is estimated, so a normal histogram is a diagnostic, not an exact conditional guarantee. Their mean square is , close to one, but the ninety percent intervals cover percent, a little short, because of a long right tail: a few samples much richer in zinc than anything near them, which a Gaussian field finds surprising. A heavier-tailed model or a new transformation might improve this, but must be fitted inside training folds and checked on fresh validation data.

A checklist for spatial data. Map the data, and look at the variogram of the residuals. Model the trend first, then the dependence. Use the Matérn family, check the smoothness, fit by REML, and do not read much into the range alone. Report prediction standard errors, and check their coverage with a cross-validation that matches the task. And remember that a spatial random effect is not an adjustment for confounding.

Numbers: 0.99 vs 1.34

Recap, problems, and the road aheadAll tracks3 min

Part thirty-nine in twelve lines. Krige weighted his boreholes by how gold grades covary with distance. Tobler's law says near things are more related, and spatial data come as fields, areas or points. Bochner's theorem says which functions can be covariances: those with non-negative spectra. The variogram describes dependence by its nugget, sill and range. Kriging is the best linear unbiased predictor, and the posterior mean of a Gaussian process. The Matérn family has a smoothness parameter, and under infill under its known-smoothness, low-dimensional Gaussian conditions, variance and range cannot both be estimated consistently; local prediction can still be asymptotically efficient. Likelihood and REML fit the covariance and the trend together, at a cubic cost. Vecchia's conditioning on a few neighbours handles a hundred thousand locations in seconds. Markov random fields and the SPDE make the precision sparse, and INLA fits them fast. Moran's I detects clustering in areas, and the BYM model smooths a speckled disease map. A modern Ripley K analysis describes the cluster in Snow's digitized map, and Cox processes model it. And a spatial random effect does not adjust for a confounder; separable covariances are a choice; Gaussian processes optimize expensive functions; and coverage must be checked with a cross-validation that matches the task.

A promise for later. This part handled dependence in space. Every value we used was observed in full: a concentration, a count, a location. Part forty turns to time measured until an event, where the study ends before many of the events happen. The survival curve of Kaplan and Meier, Cox's partial likelihood, and the traps of hazard ratios.

Where it comes back. Part forty uses shared random effects, frailties, for lifetimes. Part forty-one treats prediction at unmeasured places as imputation, and measurement error as a nugget. Part forty-four studies Brownian motion, the first Gaussian process. Part fifty-three asks how fast Gaussian process posteriors contract around the truth. And Part sixty treats predicting in a new region as a distribution shift.

Six problems, with full solutions in the README. The ordinary kriging variance; screening for the exponential covariance on a line; the variogram of Brownian motion; the mean of Moran's I; Ripley's K under complete randomness; and the closed form of expected improvement. Pause here if you want to try them.

The books this part follows: Cressie's Statistics for Spatial Data and Stein's Interpolation; Banerjee, Carlin and Gelfand on hierarchical spatial models; Rue and Held on Markov random fields, and Cressie and Wikle on space and time; Rasmussen and Williams on Gaussian processes, and Diggle on point patterns; with the papers from Krige to Katzfuss and Guinness.

Thirty-nine parts of sixty-five. Near things are more related, and that is what makes prediction at unmeasured places possible, and honest only when we check it. Next, lifetimes we have not finished watching: Part forty, time to event.

Where it goes next. Shared frailties are random effects for lifetimes in Part 40; prediction at unmeasured places is imputation in Part 41; Brownian motion, the first Gaussian process, is built in Part 44, Gaussian-process priors and their contraction rates are Part 53, and predicting in a new region is distribution shift in Part 60.

Key results

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

The variogram\(\displaystyle \gamma(h)=\tfrac12\operatorname{Var}\bigl(Z(s+h)-Z(s)\bigr)=C(0)-C(h)\)
Simple kriging\(\displaystyle \hat Z(s_0)=\mu+k_0^\top K^{-1}(z-\mu\mathbf 1),\qquad\allowbreak \operatorname{Var}=C(0)-k_0^\top K^{-1}k_0\)
The Matérn covariance\(\displaystyle C(d)=\sigma^2\,\frac{2^{1-\nu}}{\Gamma(\nu)}\Bigl(\frac{\sqrt{2\nu}\,d}{\rho}\Bigr)^{\nu}K_\nu\Bigl(\frac{\sqrt{2\nu}\,d}{\rho}\Bigr)\)
Zhang (2004)\(\displaystyle \text{under }\allowbreak \text{infill, } d\le 3:\ \text{only }\sigma^2/\rho^{2\nu}\text{ is }\allowbreak \text{consistently }\allowbreak \text{estimable}\)
Vecchia's approximation\(\displaystyle p(z)\approx\prod_{i=1}^{n}p\bigl(z_i\mid z_{N(i)}\bigr),\qquad\allowbreak N(i)\subseteq\{1,\dots,i-1\},\ |N(i)|\le m\)
Moran's I\(\displaystyle I=\frac{n}{\sum_{i,j}w_{ij}}\,\frac{\sum_{i,j}w_{ij}(z_i-\bar z)(z_j-\bar z)}{\sum_i(z_i-\bar z)^2}\)

Try it

Lab 39 · Kriging along the ridge: what need not be learned

Simulate 60 exponential (Matérn, nu = 1/2) fields at 200 sites in the unit square, krige 50 held-back sites with the true variance and range, with both doubled (the same sigma^2 / rho), and with the range alone wrong, and compare the RMSE and the coverage of the 90% prediction intervals.

Figure produced by Lab 39: Kriging along the ridge: what need not be learned
Produced by the lab below, seed 0, in 2.5 s.
python -m videos.stats.labs 39 needs numpy, scipy, matplotlib · download lab39.py · source on GitHub
the truth                    RMSE 0.386   90% intervals cover 89.3%   (sigma^2/rho = 3.33)
ridge: rho x 2, sigma^2 x 2  RMSE 0.386   90% intervals cover 89.3%   (sigma^2/rho = 3.33)
off it: rho x 2 alone        RMSE 0.386   90% intervals cover 75.9%   (sigma^2/rho = 1.67)
off it: rho x 0.5 alone      RMSE 0.389   90% intervals cover 97.2%   (sigma^2/rho = 6.67)

The predictions hardly depend on the parameters at all, and the intervals depend only on sigma^2 / rho: doubling both changes nothing, which is why dense data in a fixed region cannot tell them apart, while the range alone wrong gives intervals too narrow or too wide.
The code (81 lines; it asserts its own result)
"""Lab 39: krige simulated fields with the right covariance, along the unidentifiable ridge, and off it."""

import numpy as np

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

TITLE = "Kriging along the ridge: what need not be learned"
GOAL = ("Simulate 60 exponential (Matérn, nu = 1/2) fields at 200 sites in the unit square, krige 50 held-back sites "
        "with the true variance and range, with both doubled (the same sigma^2 / rho), and with the range alone "
        "wrong, and compare the RMSE and the coverage of the 90% prediction intervals.")
TASKS = [
    "Move along the ridge the other way (rho x 0.5 with sigma^2 x 0.5), then further (x 8 with x 8). When does coverage finally move?",
    "Set nu = 1.5 in both the simulation and the kriging. The ridge is now sigma^2 / rho^3: check that rho x 2 needs sigma^2 x 8.",
    "Replace the simple kriging (mean=0.0) by ordinary kriging (drop the mean argument) and compare the variances it reports.",
]

NU, RHO, SIGMA2, NUGGET = 0.5, 0.3, 1.0, 0.01
SETTINGS = [  # (label, range multiplier, variance multiplier)
    ("the truth", 1.0, 1.0),
    ("ridge: rho x 2, sigma^2 x 2", 2.0, 2.0),
    ("off it: rho x 2 alone", 2.0, 1.0),
    ("off it: rho x 0.5 alone", 0.5, 1.0),
]


def run(seed=0):
    rng = np.random.default_rng(seed)
    n, m, reps = 200, 50, 60
    cover = {s[0]: [] for s in SETTINGS}
    mse = {s[0]: [] for s in SETTINGS}
    sds = {}
    for _ in range(reps):
        xy = rng.random((n + m, 2))
        K = spatial.matern(spatial.dists(xy), SIGMA2, RHO, NU)
        field = np.linalg.cholesky(K + 1e-10 * np.eye(n + m)) @ rng.standard_normal(n + m)
        z = field[:n] + np.sqrt(NUGGET) * rng.standard_normal(n)
        for name, a, b in SETTINGS:
            out = spatial.krige(xy[:n], z, xy[n:], lambda d: spatial.matern(d, SIGMA2 * b, RHO * a, NU),
                                nugget=NUGGET, mean=0.0)
            err = field[n:] - out["pred"]
            sd = np.sqrt(out["var"])
            cover[name].append(np.mean(np.abs(err) < 1.645 * sd))
            mse[name].append(np.mean(err ** 2))
            sds[name] = sd  # the last field's, for the figure
    cov = {k: float(np.mean(v)) for k, v in cover.items()}
    rmse = {k: float(np.sqrt(np.mean(v))) for k, v in mse.items()}

    lab = labs.Lab()
    for name, a, b in SETTINGS:
        lab.row(name, f"RMSE {rmse[name]:.3f}   90% intervals cover {cov[name]:.1%}   (sigma^2/rho = {SIGMA2 * b / (RHO * a):.2f})")
    lab.note = ("The predictions hardly depend on the parameters at all, and the intervals depend only on "
                "sigma^2 / rho: doubling both changes nothing, which is why dense data in a fixed region cannot "
                "tell them apart, while the range alone wrong gives intervals too narrow or too wide.")
    truth, ridge, long_, short = (s[0] for s in SETTINGS)
    assert abs(cov[truth] - 0.90) < 0.03, "the true covariance gives calibrated intervals"
    assert abs(cov[ridge] - cov[truth]) < 0.02 and abs(rmse[ridge] / rmse[truth] - 1) < 0.02, "the ridge changes nothing"
    assert cov[long_] < 0.82 and cov[short] > 0.95, "off the ridge the intervals are wrong in each direction"
    assert max(rmse.values()) / min(rmse.values()) < 1.05, "the point predictions barely move"

    fig, ax = labs.figure(2, size=(11, 4.2))
    names = [s[0] for s in SETTINGS]
    colors = [labs.GREY, labs.GREEN, labs.RED, labs.ORANGE]
    ax[0].barh(range(4), [100 * cov[k] for k in names], color=colors, height=0.6)
    ax[0].axvline(90, color=labs.INK, ls="--", lw=1)
    for i, k in enumerate(names):
        ax[0].text(100 * cov[k] - 1.5, i, f"{cov[k]:.1%}", ha="right", va="center", color=labs.BG, fontsize=9, fontweight="bold")
    ax[0].set_axisbelow(True)
    ax[0].set_yticks(range(4))
    ax[0].set_yticklabels(["the truth", "ridge: both x 2", "rho x 2 alone", "rho x 0.5 alone"])
    ax[0].invert_yaxis()
    ax[0].set(title="Coverage of 90% kriging intervals (dashed: 90%)", xlabel="coverage over 60 fields (%)", xlim=(50, 100))
    top = 1.05 * max(v.max() for v in sds.values())
    ax[1].plot([0, top], [0, top], color=labs.MUTED, ls="--", lw=1)
    for k, color in zip(names[1:], colors[1:]):
        ax[1].scatter(sds[truth], sds[k], s=14, color=color, alpha=0.85, label=k)
    ax[1].set(title="Kriging sd at 50 sites of one field", xlabel="sd under the true parameters",
              ylabel="sd under the wrong parameters", xlim=(0, top), ylim=(0, top))
    ax[1].legend(loc="upper left")
    lab.fig = fig
    return lab

Now change it

  1. Move along the ridge the other way (rho x 0.5 with sigma^2 x 0.5), then further (x 8 with x 8). When does coverage finally move?
  2. Set nu = 1.5 in both the simulation and the kriging. The ridge is now sigma^2 / rho^3: check that rho x 2 needs sigma^2 x 8.
  3. Replace the simple kriging (mean=0.0) by ordinary kriging (drop the mean argument) and compare the variances it reports.

Problems, with solutions

Try each problem before opening its solution.

  1. The ordinary kriging variance. Ordinary kriging: minimize \(\text{Var}(\lambda^\top Z - Z_0)\) subject to \(\mathbf 1^\top\lambda = 1\); show the variance is \(C(0) - \lambda^\top k_0 - m\).

    Solution

    Minimize λᵀKλ − 2λᵀk₀ + C(0) + 2m(1ᵀλ − 1). Setting the gradient to zero gives Kλ + m1 = k₀, which with 1ᵀλ = 1 is the system in chapter four. Substituting λᵀKλ = λᵀk₀ − m gives σ²_OK = C(0) − λᵀk₀ − m.

  2. Screening on a line. On a line with \(C(h) = e^{-|h|}\), show simple kriging at \(s_1 < s_0 < s_2\) ignores every point beyond \(s_1\) and \(s_2\).

    Solution

    With C(h) = e^{−|h|}, the process is Markov (it is the stationary Ornstein–Uhlenbeck process). Given Z(s₁) and Z(s₂), Z(s₀) is independent of every value outside [s₁, s₂]. So the conditional mean, which is simple kriging, has zero weight on them.

  3. Brownian motion's variogram. For Brownian motion with \(\text{Var}\,W(t) = \sigma^2 t\), find \(\gamma(h)\), and show it has no sill.

    Solution

    γ(h) = ½E[W(t + h) − W(t)]² = σ²h/2, which grows without bound: no sill. It is a valid variogram (intrinsically stationary) without a covariance function, the reason geostatistics prefers γ.

  4. Moran's mean. Show that Moran's \(I\) has mean \(-1/(n-1)\) under random permutation of the values.

    Solution

    Under random permutation, E[e_i e_j] for i ≠ j is −Σe_k²/(n(n − 1)), since Σ_{i≠j} e_i e_j = −Σe_k². So E[eᵀWe] = −S₀ Σe_k²/(n(n − 1)) when W has a zero diagonal, and E[I] = (n/S₀)(−S₀/(n(n − 1))) = −1/(n − 1).

  5. K under CSR. For a homogeneous Poisson process in the plane, show \(K(r) = \pi r^2\) (ignore edges).

    Solution

    For a homogeneous Poisson process of intensity λ, by Slivnyak's theorem the other points seen from a typical point are again Poisson(λ). The expected number within r is λπr², so K(r) = πr² and L(r) = r.

  6. Expected improvement. Derive \(\text{EI} = (f^* - \mu)\Phi(z) + s\,\phi(z)\) for \(f \sim N(\mu, s^2)\), \(z = (f^* - \mu)/s\).

    Solution

    With f = μ + sZ, (f* − f)₊ = s(z − Z)₊ where z = (f* − μ)/s. Then E(z − Z)₊ = ∫_{−∞}^{z} (z − u)φ(u) du = zΦ(z) + φ(z). Multiplying by s gives (f* − μ)Φ(z) + sφ(z).

Notes and sources

Where it comes back

  • Part 40: shared frailties, random effects for lifetimes.
  • Part 41: prediction at unmeasured places as imputation; measurement error as a nugget.
  • Part 44: Brownian motion, the first Gaussian process.
  • Part 53: Gaussian-process priors and how fast posteriors contract.
  • Part 60: predicting in a new region as distribution shift.

Glossary

  • Random field; stationary; isotropic: random values over a region; a constant mean and a covariance depending on displacement only; on distance only.
  • Bochner's theorem: covariances are the Fourier transforms of non-negative measures.
  • Variogram; nugget, sill, range: half the expected squared difference at lag h; the jump at zero, the plateau, the distance where it is reached.
  • Anisotropy: dependence that differs by direction.
  • Kriging (simple, ordinary, universal): the BLUP with a known mean, an unknown constant, an unknown trend.
  • Matérn; smoothness ν: the covariance family with a differentiability parameter.
  • Infill asymptotics; microergodic parameter: more data in a fixed region; the combination σ²/ρ^{2ν} it can learn.
  • REML: likelihood of error contrasts that removes fixed-trend parameters; a scale correction for known correlation shape does not imply unbiased estimation of every covariance parameter.
  • Vecchia approximation; NNGP; screening: conditioning on a few nearest earlier neighbours; its use as a prior; why it works.
  • GMRF; SPDE; INLA: a Gaussian field with sparse precision; Matérn fields as solutions of a stochastic PDE; nested Laplace approximations.
  • Moran's I; CAR; SAR; BYM: spatial correlation for areas; conditional and simultaneous autoregressions; the disease-mapping model.
  • CSR; Ripley's K; Besag's L; Cox process; LGCP: complete spatial randomness; neighbour counts by distance; the linearized K; a Poisson process with random intensity; a log-Gaussian one.
  • Spatial confounding; restricted spatial regression: a random effect competing with a smooth covariate; forcing it orthogonal.
  • Separable; Gneiting covariance: space–time covariance as a product; a family with interaction.
  • Emulator; expected improvement; Bayesian optimization: a GP surrogate for a simulator; the acquisition rule; the loop.
  • Spatial block cross-validation: holding out regions, to test extrapolation.

Sources

  • Geostatistics.
    • D. Krige, J. Chem. Metall. Min. Soc. S. Afr. 52 (1951); G. Matheron, Traité de géostatistique appliquée (1962–63), Econ. Geol. 58 (1963); L. Gandin (1963).
    • W. Tobler, Econ. Geogr. 46 (1970); N. Cressie, Statistics for Spatial Data (rev. ed. 1993); N. Cressie, Math. Geol. 17 (1985); N. Cressie & D. Hawkins, Math. Geol. 12 (1980).
    • S. Bochner (1933); B. Matérn, Spatial Variation (1960); P. Whittle, Biometrika 41 (1954).
    • M. Stein, Interpolation of Spatial Data (1999); H. Zhang, JASA 99 (2004).
    • K. Mardia & R. Marshall, Biometrika 71 (1984); H. Patterson & R. Thompson, Biometrika 58 (1971); D. Zimmerman & N. Cressie, Ann. Inst. Stat. Math. 44 (1992).
    • M. Rikken & R. van Rijn (1993); E. Pebesma, Comput. Geosci. 30 (2004) (gstat).
  • Scaling.
    • A. Vecchia, JRSS B 50 (1988); M. Stein, Ann. Stat. 30 (2002) (screening); A. Datta, S. Banerjee, A. Finley & A. Gelfand, JASA 111 (2016); M. Katzfuss & J. Guinness, Stat. Sci. 36 (2021).
    • M. Heaton et al., JABES 24 (2019).
    • J. Besag, JRSS B 36 (1974); H. Rue & L. Held, Gaussian Markov Random Fields (2005); F. Lindgren, H. Rue & J. Lindström, JRSS B 73 (2011); H. Rue, S. Martino & N. Chopin, JRSS B 71 (2009).
  • Areas and points.
    • P. Moran, Biometrika 37 (1950); J. Besag, J. York & A. Mollié, Ann. Inst. Stat. Math. 43 (1991).
    • B. Ripley, J. Appl. Prob. 13 (1976); D. Cox, JRSS B 17 (1955); J. Møller, A. Syversveen & R. Waagepetersen, Scand. J. Stat. 25 (1998); A. Baddeley, J. Møller & R. Waagepetersen, Stat. Neerl. 54 (2000).
    • J. Snow, On the Mode of Communication of Cholera (2nd ed. 1855); P. Diggle (2013).
  • Confounding.
    • J. Hodges & B. Reich, Am. Stat. 64 (2010); C. Paciorek, Stat. Sci. 25 (2010); E. Hanks et al., Environmetrics 26 (2015); K. Khan & C. Calder, JASA 117 (2022); E. Dupont, S. Wood & N. Augustin, Biometrics 78 (2022).
  • Space–time.
    • T. Gneiting, JASA 97 (2002); N. Cressie & C. Wikle, Statistics for Spatio-Temporal Data (2011).
  • Gaussian processes.
    • J. Sacks, W. Welch, T. Mitchell & H. Wynn, Stat. Sci. 4 (1989); D. Jones, M. Schonlau & W. Welch, J. Global Optim. 13 (1998); J. Snoek, H. Larochelle & R. Adams, NeurIPS (2012).
    • C. Rasmussen & C. Williams (2006); R. Neal, Bayesian Learning for Neural Networks (1996); D. MacKay, Neural Comput. 4 (1992); G. Kimeldorf & G. Wahba, Ann. Math. Stat. 41 (1970); A. O'Hagan, JRSS B 40 (1978).
  • Honest prediction.
    • D. Roberts et al., Ecography 40 (2017).
About this partfrom its README

Part 39 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the nineteenth part of Stage III, Master's. Part 38's dependence ran in one direction, from the past. In space it runs in every direction, with no natural order to filter along. This part covers:

  • random fields, Bochner's theorem and variograms;
  • kriging as the best linear unbiased predictor, and as a Gaussian-process posterior;
  • the Matérn family, and the parameter that cannot be learned;
  • ML and REML, and scaling to a hundred thousand locations (Vecchia, NNGP, GMRFs and the SPDE);
  • areal data and disease maps; point patterns and Snow's map;
  • spatial confounding; space–time covariances; Gaussian processes in machine learning;
  • honest prediction.

The part builds statkit.spatial and an instrument, the field surface (FieldSurface): a kriging or GP surface on a grid, with its standard error as a darkening overlay and the data as dots in the same coordinates. Its real data are:

  • the Meuse flood plain's 155 topsoil samples of heavy metals, and the 3,103-node prediction grid (Rikken & van Rijn 1993, as distributed with R's sp package, GPL ≥ 2);
  • John Snow's 1854 cholera deaths and pumps, as digitized by Waldo Tobler (from R's HistData, GPL-2).

It opens with Krige (1951): valuing blocks of ore from boreholes by weights that account for how grades covary with each other and with the block. Then the World's pollution field, hidden but for 300 stations.

From there the part covers:

  • Spatial data.
    • Tobler's first law; Cressie's three kinds of data.
    • Meuse's log zinc, high by the river; the World's field, 20 + 3 × traffic + a Matérn field (σ² = 6.25, ρ = 1.5, ν = 3/2) with a nugget of 0.64.
    • Under the nominal known covariance, the trend-removed station average estimates an ensemble mean level with effective sample size 5.7: model-based SE 1.10, not σ/√n = 0.15. This is not the prediction error for the realized island's spatial average; that requires covariances with the target area average.
  • Random fields. Stationarity, isotropy, Gaussianity; Bochner's theorem; four seeded fields of different smoothness and range; the standard families.
  • Variograms.
    • Matheron's estimator. Meuse's log zinc, spherical fit by Cressie's WLS: nugget 0.054, partial sill 0.585 (total sill 0.639), range 0.90 km.
    • Robust (Cressie–Hawkins) estimates are close, consistent with the logs reducing large-value influence; agreement is not proof that no outliers remain.
    • Raw directional variograms: lowest along the river (north-east), highest across it. A river-distance trend can mimic anisotropy; these alone do not identify geometric residual anisotropy.
    • The World's empirical variogram tracks the truth at short lags and keeps rising beyond.
  • Kriging.
    • The BLUP derived with a Lagrange multiplier; simple, ordinary and universal.
    • Universal kriging of Meuse with √(river distance): β̂ = 7.01 − 2.61 √d; the standard-error map.
    • Leave-one-out RMSE of log zinc: overall mean 0.724, inverse-distance weighting 0.514, ordinary kriging 0.394, universal 0.376.
    • The World: RMSE 0.54 over the island against 2.64 for the traffic trend alone; the REML plug-in's 90% intervals cover 83% of the island in this one field.
    • Known-covariance simple kriging equals Gaussian conditioning. Universal kriging corresponds to a flat trend prior when the design and resulting posterior are proper. BLUP moment properties and Gaussian interval coverage are distinct. Latent-field prediction excludes a new measurement nugget; observed-value validation includes it.
  • Matérn and identifiability.
    • The family, its closed forms, its spectrum and Whittle's SPDE; Stein's "use the Matérn".
    • 80 seeded fields (n = 300, exponential, ρ = 0.3, σ² = 1): ML estimates of ρ and σ² vary by 38% and 34% along a ridge, while σ²/ρ varies by 9% (Zhang 2004). This fixed-n experiment illustrates variability, not a proof of consistency. For Gaussian Matérn fields of known ν in dimensions at most three on a fixed bounded domain, variance and range cannot both be consistently estimated under infill. Equivalent Gaussian measures are not identical finite-dimensional distributions; increasing the domain changes the result. Finite predictions still depend on both parameters.
    • Kriging the World along the ridge (ρ × 2 with σ² × 8, or ρ × 0.7 with σ² × 0.34) leaves the RMSE at 0.51–0.53 and coverage at 87–90%. Off it, ρ × 2 alone gives 63% and ρ × 0.5 alone 98%.
  • Likelihood.
    • ML and REML (Patterson & Thompson). On the World with ν = 3/2: REML ρ̂ = 2.09, σ̂² = 8.30, τ̂² = 0.72, β̂ = (19.35, 2.83); ML ρ̂ = 1.96, σ̂² = 7.11.
    • Choosing ν: REML log-likelihoods −457.68 (ν = 1/2), −455.69 (3/2, the truth), −457.11 (5/2).
    • The cubic wall: likelihood time and the n = 100,000 cubic extrapolation are machine- and load-dependent measurements, not an actual exact 100,000-site fit. The covariance matrix alone would require 80 GB. REML need not always give larger covariance parameters or eliminate all variance bias.
  • Scaling.
    • Vecchia's approximation. On 2,000 points (ν = 3/2, with a nugget), the log-likelihood error is 523 with m = 1, 35 with m = 10 and 2.8 with m = 30. The displayed range profiles have nearby grid maxima in this realization. Approximation can move estimates and distort curvature in either direction. The fast candidate search selects earlier points among 4m nearest overall and can use fewer than m, rather than always finding the exact m nearest predecessors.
    • 100,000 jittered land-node locations provide a timing benchmark with m = 10. Values reuse selected grid-node latent values, so this is not an exact Matérn simulation at the jittered coordinates; timing depends on the machine and load.
    • NNGP; tapering, low rank, and Heaton et al.'s competition.
  • GMRFs and the SPDE.
    • Precision zeros as conditional independence (Besag 1974).
    • A 60 × 40 SPDE lattice: 30,204 nonzeros of 5.76 million. Conditioning on 150 noisy values by one sparse solve gives a reconstruction RMSE of 0.612. Its deterministic scale gives unit average marginal prior variance; the realized sample is not divided by its random spatial SD. This small teaching sampler uses dense Cholesky, while conditioning is sparse. The free-boundary grid approximates a whole-space Matérn/SPDE construction. Practical range √(8ν)/κ is twice the scale ρ used in this part's Matérn definition.
    • Lindgren, Rue & Lindström; INLA.
  • Areal data.
    • Moran's I for the World's 200 towns' log case rates: 0.085, permutation p = 0.018 under an exchangeable-value reference. Unequal expected counts imply unequal raw-rate variance, so that reference is not the null of independent equal-risk Poisson counts. This is exploratory. The plotted curve is a normal approximation to permutation moments, not the actual permutation distribution.
    • SMRs: the smallest quarter of towns range from 0 to 3.16; 20 towns have no cases.
    • Compatible CAR conditionals require a symmetric positive precision T⁻¹(I−ρW); intrinsic normalized CAR needs constraints and a proper posterior. The teaching BYM-style fit uses fixed precisions, a small proper ridge and posterior modes, rather than integrated posterior means. CAR, SAR and their parameter restrictions are distinct. The smoothed relative risks have RMSE 0.18 against the truth, against 0.58 for the raw SMRs, and are too flat (slope 0.56): shrinkage's bias.
  • Point patterns.
    • Snow's map: 359 of 578 digitized deaths (62%) are nearest the Broad Street pump by straight-line map distance; the next pump has 64. These are not reconstructed walking-distance catchments or all London deaths.
    • Ripley's K and Besag's L. Snow's deaths exceed the pointwise 95% reference from 199 fixed-count uniform patterns at the displayed scales. The case-derived window and many-distance comparison make this exploratory, not a calibrated simultaneous global test.
    • But CSR is the wrong null: the inhomogeneous K and case–control designs. Cox processes and the LGCP.
  • Spatial confounding. 60 seeded fields, n = 250, with an unmeasured spatial confounder correlated 0.8 with the exposure and the same range, β = 1.
    • OLS averages 1.80 (SD 0.21); spatial GLS with a Matérn random effect by REML averages 1.81 (SD 0.08): just as biased, and more confident.
    • With the spatial term independent of the exposure, both are unbiased (1.01 and 1.02), and GLS's SD is 0.13 against OLS's 0.37.
    • Hodges & Reich; Paciorek's scales; restricted spatial regression; spatial+. Fine-scale exposure variation needs identifying assumptions, and no random-effect model automatically removes confounding. RSR's OLS equivalence concerns the standard Gaussian linear formulation; interval undercoverage is a risk, not a universal identity.
  • Space and time.
    • Separable covariances; Gneiting's family, whose spatial correlation spreads with the time lag.
    • The World's daily readings: the daily station mean has a lag-1 ACF of 0.72 (AR(1) weather with φ = 0.7). Daily anomaly correlations are approximately distance-independent, with model value 0.64 = 4/(4 + 1.5²). A common weather effect contributes constant spatial covariance but cancels from same-day spatial differences and is invisible to that variogram. The daily station average is not a direct census of the island's spatial mean.
    • Dynamic models; advection–diffusion SPDEs.
  • Gaussian processes in machine learning.
    • The dictionary; the marginal likelihood's Occam factor; emulators (Sacks et al. 1989).
    • Expected improvement (Jones, Schonlau & Welch 1998): on a two-dip function it finds x = −0.48 (true −0.47) within eight evaluations counting the three initial observations; eleven evaluations are made overall. The 401-point grid is a reference at that resolution, not a proof of a continuous global optimum.
    • Snoek et al.; Neal's infinite networks; kernel ridge and splines.
  • Honest prediction.
    • The plug-in variance; Zimmerman & Cressie.
    • Kriging the World's stations: random 10-fold CV RMSE 0.99 against 1.34 for 3 × 3 spatial blocks, whose held-out stations are 2.8 times further from the training data. The covariance and trend are refitted inside each training fold. Empirical 90% coverage is 89.3% for random folds and 90.7% for spatial blocks in this realization; distance-aware variance does not guarantee calibration.
    • Meuse's LOO z-scores under universal kriging: mean z² 1.09, 90% coverage 86%, with a long right tail.
    • The Board; a checklist.

Data:

  • Meuse and Snow's map are the Museum's;
  • the pollution field, its stations, the daily readings and the towns' counts are the World's;
  • the rest are seeded simulations.

Built in this part:

  • statkit.spatial (explainer/stats/kit/spatial.py), checked in tests/test_stats_kit_spatial.py:
    • Covariances and variograms: Matérn; the classical and robust empirical variograms; exponential, spherical and Matérn models fitted by Cressie's WLS.
    • Kriging and likelihood: simple, ordinary and universal kriging with the GLS trend and its covariance (checked against Gaussian conditioning); the Gaussian log-likelihood; ML and REML fits; exact and Vecchia likelihoods (a k-d tree version for large n).
    • Lattices and areas: the SPDE precision on a grid, sampling by dense Cholesky in this small implementation and conditioning by a sparse solve; Moran's I with a permutation test; BYM-style smoothing of relative risks.
    • Points, space–time and design: Ripley's K and CSR envelopes; Gneiting's space–time covariance; expected improvement.
  • The World gains its pollution block (the field on a 0.1-unit grid by circulant embedding, 300 stations, a year of daily readings with AR(1) weather).
  • The Museum gains meuse(), meuse_grid(), meuse_river() and snow_map().
  • The field surface (FieldSurface in explainer/stats/viz.py).

The Coverage Board gains five rows:

Method Setting Achieved Verdict
kriging 90% PI, true covariance Matérn ν = 5/2 fields, n = 200 89.9% kept
kriging PI, REML plug-in same 88.9% broken (a small, systematic shortfall)
kriging PI, exponential fitted same 97.9% conservative
OLS 90% CI for a covariate spatially correlated errors, n = 200 28.0% broken
GLS (REML) CI for the covariate same 86.0% kept

The local field gallery now expands its circulant embedding until its eigenvalues are nonnegative to numerical tolerance, instead of truncating substantive negative modes. The existing World generator retains a very fine spectral approximation: at nominal variance 6.25 its maximum covariance perturbation from spectral truncation is about 0.000125. It is distinguished from the exact nominal Matérn model used in the independent-field Board simulations. Continuous Bochner covariance representations, mean-square smoothness, boundary approximations, Gneiting parameter ranges and fixed-domain assumptions are explicit.

Chapter notes
# Chapter Numbers
0 Krige's boreholes 1951
1 Spatial data n_eff = 5.7 of 300
2 Random fields Bochner
3 Variograms nugget 0.054, partial sill 0.585 (total sill 0.639), range 0.90 km
4 Kriging LOO RMSE 0.724 → 0.376
5 Matérn and identifiability CV 38% vs 9%
6 Likelihood ν = 3/2 wins; cubic timing extrapolation 12.3 hours
7 Scaling 100,000 sites in 4.3 s (this machine/load)
8 GMRFs and the SPDE 30,204 of 5.76M
9 Areal data I = 0.085; RMSE 0.58 → 0.18
10 Point processes 359 of 578
11 Spatial confounding 1.80 vs 1.81
12 Space and time 0.64 at every distance
13 GPs in machine learning best reached on evaluation 8; 11 overall; 401-point reference grid
14 Honest prediction 0.99 vs 1.34
15 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Krige (1951); Matheron (1963).
  2. Spatial data. Tobler (1970); the World's pollution field.
  3. Random fields. Bochner's theorem.
  4. Variograms. Nugget, sill, range; robust estimation.
  5. Kriging. The BLUP derived; ordinary and universal; kriging = GP posterior mean (FieldSurface).
  6. Matérn (1960). Smoothness; Stein (1999); only σ²/ρ^{2ν} is identifiable under infill (Zhang 2004).
  7. Likelihood estimation. ML and REML; O(n³).
  8. Scaling. Vecchia and NNGP; Built: 100,000 locations.
  9. GMRFs and SPDE (Lindgren, Rue & Lindström 2011); INLA.
  10. Areal data. Moran's I; CAR/SAR; BYM disease mapping.
  11. Point processes. Ripley's K; Cox processes; Snow's map.
  12. Spatial confounding (Hodges & Reich 2010).
  13. Space–time (Gneiting 2002).
  14. GPs in ML. Marginal likelihood; Bayesian optimization; emulators.
  15. Honest prediction (Board).
  16. Outro.

Built: statkit.spatial.

Build the film

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

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

Build it
OMP_NUM_THREADS=1 python -m videos.stats.stats39.compute   # once (about half an hour)
python tools/build.py stats39 -q l                         # fast 480p preview
python tools/build.py stats39                              # 1080p30 -> renders/stats39.mp4
python tools/qa_scene.py stats39 Kriging
python tools/lecture_length.py stats39 --floor 50