
Pillar 7 — Bayesian Hierarchical Spatial Models
Hugo Rodrigues
Source:vignettes/pillar7-bayesian-hierarchical.Rmd
pillar7-bayesian-hierarchical.RmdAbstract
A machine-learning soil map returns a number at every pixel. It rarely returns an honest interval around that number, because the residual spatial structure the model failed to explain is treated as noise rather than as a signal with a covariance. Pillar 7 takes the opposite route: it puts the spatial dependence inside the model, as a Gaussian process random effect, and returns a full posterior over every quantity of interest (Banerjee et al. 2014; Cressie and Wikle 2011).
This vignette derives the hierarchy, is explicit about the one
non-conjugate parameter and the concession edaphos makes
for it, and then spends most of its length on the part that is usually
skipped: the two diagnostics that decide whether the fitted spatial
field means anything at all.
1. The hierarchy
Write the observed soil property at site as a mean structure plus a spatially correlated random effect plus independent error:
The three layers are
with an exponential correlation function
Note the parameterisation carefully, because it is the source of most mistakes with this model: is a decay rate, not a range. Its units are 1/distance. Large means correlation dies off quickly; drives . The practical correlation range is roughly . If your coordinates are in degrees, a sensible is a very different number than if they are in metres.
is the nugget: variation below the shortest sampling distance, pooling laboratory error and micro-scale heterogeneity. is the partial sill, the variance of the structured field.
1.1 Why is the hard one
Collapse out of the likelihood:
Conditional on this is an ordinary Bayesian linear model with a known covariance: has a Gaussian full conditional and the variances have inverse-gamma full conditionals. Every update is closed-form.
But sits inside a matrix inverse and a determinant. It has no conjugate update, and a Metropolis step on it pays an Cholesky for every proposal, accepted or rejected.
edaphos avoids the Metropolis step. It
profiles
:
over the bracket phi_range it maximises the marginal
likelihood once, fixes
at
,
and runs a fully conjugate Gibbs sampler for everything else. This is
the concession INLA makes for its hyperparameters (Rue et al. 2009)
— treat the rate as estimated rather than sampled, buy exact fast
updates for the parameters you report.
The cost, stated plainly: the reported posterior for is conditional on and does not propagate uncertainty in the rate. It is a conditional posterior, not a joint one.
2. The Cerrado grid
br_cerrado is a 45 × 45 regular grid of synthesised
Cerrado observations bundled with the package, so this vignette runs
offline and identically everywhere.
data(br_cerrado)
str(br_cerrado)
#> 'data.frame': 2025 obs. of 8 variables:
#> $ x : num -48 -47.9 -47.9 -47.9 -47.9 ...
#> $ y : num -16 -16 -16 -16 -16 -16 -16 -16 -16 -16 ...
#> $ elev : num 904 928 900 912 934 ...
#> $ slope : num 2.59 9.9 14.19 6.23 11.89 ...
#> $ twi : num 10.32 11.23 11.47 11.28 8.12 ...
#> $ map_mm: num 1197 1239 1209 1160 1225 ...
#> $ ndvi : num 0.719 0.619 0.531 0.586 0.517 0.648 0.668 0.529 0.648 0.693 ...
#> $ soc : num 27.6 20.1 20.2 17.2 15.7 ...
set.seed(42)
idx <- sample(nrow(br_cerrado), 220)
train <- br_cerrado[idx, ]
test <- br_cerrado[-idx, ][sample(nrow(br_cerrado) - 220, 200), ]
c(n_train = nrow(train), n_test = nrow(test))
#> n_train n_test
#> 220 200The Gibbs sampler is per iteration through the Cholesky, so — not the iteration count — is what binds on a laptop.
3. Fit the full model, and read the warning
fit_full <- bhs_fit(
data = train,
formula = soc ~ elev + slope + twi + map_mm,
coords = c("x", "y"),
backend = "gibbs",
nmcmc = 1500L, burn = 500L, thin = 2L,
phi_range = c(0.05, 1000),
seed = 1L, verbose = FALSE
)
#> Warning: bhs_fit(): the profile-MLE of phi (1000) is at the upper end of
#> phi_range = c(0.05, 1000), supplied. Widen phi_range and refit; the spatial
#> variance fraction is not trustworthy until phi is interior. phi is a rate
#> (1/distance) in the units of `coords`.That warning is not noise to be silenced. It is the first diagnostic.
bhs_fit() warns when
lands on an endpoint of phi_range, because then the
bracket — not the data — determined the answer. Here the
likelihood is still climbing at the upper end: it wants
as large as it can get, which is the model’s way of saying there
is no residual spatial structure left to fit. Every driver of
soc in this synthesised grid is already in the formula, so
the residual is white.
Widening the bracket will not help; it will rail again, further out. The right conclusion is that a spatial random effect is not needed for this specification.
3.1 The diagnostic that works, and the one that does not
The number most often quoted from a fit like this is the spatial fraction . This section shows why, on its own, it tells you nothing.
The question a spatial model has to answer first is whether the fitted correlation is resolvable by the sampling design at all. The practical range is ; compare it to the shortest distance between two sampled sites:
d_min <- min(dist(train[, c("x", "y")]))
c(phi_hat = fit_full$phi_hat,
range_3_over = 3 / fit_full$phi_hat,
d_min = d_min,
range_per_dmin = (3 / fit_full$phi_hat) / d_min,
corr_nearest = exp(-fit_full$phi_hat * d_min))
#> phi_hat range_3_over d_min range_per_dmin corr_nearest
#> 9.999999e+02 3.000000e-03 6.818182e-03 4.400000e-01 1.093708e-03The fitted range is shorter than the gap between the two closest observations. Nothing in the design can see structure at that scale: even nearest neighbours are essentially uncorrelated, so is numerically the identity and . In that regime and enter the likelihood identically — they are aliased, and only their sum is a statement about the data.
Now look at the spatial fraction anyway:
fr_full <- fit_full$sigma2_draws /
(fit_full$sigma2_draws + fit_full$tau2_draws)
c(mean = mean(fr_full), sd = sd(fr_full))
#> mean sd
#> 0.96647675 0.02487572Near 1, with a tight posterior — which reads as “almost all residual variance is spatially structured” and is the opposite of the truth. The apparent precision is the trap: a narrow posterior on an aliased quantity is not evidence. Section 4 fits a model where the field is real and shows this same number barely moves, which is the point.
4. Omit a driver, and the field reappears
A GP random effect is, operationally, a surrogate for spatially
smooth predictors you do not have. We can demonstrate that directly
by dropping map_mm — a smooth climate driver — and
refitting.
fit_drop <- bhs_fit(
data = train,
formula = soc ~ elev + slope + twi,
coords = c("x", "y"),
backend = "gibbs",
nmcmc = 1500L, burn = 500L, thin = 2L,
phi_range = c(0.05, 1000),
seed = 1L, verbose = FALSE
)
c(phi_hat = fit_drop$phi_hat,
interior = fit_drop$phi_hat < 1000,
range_3_over = 3 / fit_drop$phi_hat,
range_per_dmin = (3 / fit_drop$phi_hat) / d_min,
corr_nearest = exp(-fit_drop$phi_hat * d_min))
#> phi_hat interior range_3_over range_per_dmin corr_nearest
#> 130.33663474 1.00000000 0.02301732 3.37587357 0.41120686No warning this time: is interior, so the data — not the bracket — chose it. And the range now spans several nearest-neighbour spacings, with immediate neighbours meaningfully correlated. This is a real, short-range field: the GP has taken over the job the omitted rainfall covariate was doing.
That is the honest interpretation of a spatial random effect in any applied fit — it is as much a statement about what is missing from your covariate stack as about pedogenesis.
Now the promised comparison. Here is the spatial fraction for this fit, where the field is genuine:
fr_drop <- fit_drop$sigma2_draws /
(fit_drop$sigma2_draws + fit_drop$tau2_draws)
rbind(`full (no resolvable field)` = c(mean = mean(fr_full), sd = sd(fr_full)),
`reduced (real field)` = c(mean = mean(fr_drop), sd = sd(fr_drop)))
#> mean sd
#> full (no resolvable field) 0.9664767 0.02487572
#> reduced (real field) 0.9661160 0.02463437The two are practically indistinguishable — same value, same tight posterior — yet one fit has a resolvable spatial field and the other has none. The spatial fraction did not detect the difference. What did was : interior versus railed, and its range measured against the sampling distance.
Report those together, or report neither.
round(t(apply(fit_drop$beta_draws, 2, function(b)
c(mean = mean(b), sd = sd(b),
q025 = quantile(b, 0.025, names = FALSE),
q975 = quantile(b, 0.975, names = FALSE)))), 4)
#> mean sd q025 q975
#> (Intercept) -9.6390 9.5736 -29.0979 7.3221
#> elev 0.0210 0.0078 0.0080 0.0375
#> slope -0.5838 0.0508 -0.6791 -0.4846
#> twi 1.8848 0.2537 1.4221 2.3367A coefficient whose 95% credible interval excludes zero is one the data resolve after the field has absorbed everything it can — a stricter bar than an OLS -value, because a covariate that merely happens to be smooth in space will have its apparent effect soaked up by .
5. Bayesian kriging, and whether the interval is earned
Prediction at a new site is not . Marginalising the field out of the hierarchy gives the exact Gaussian conditional
evaluated at every retained posterior draw of .
The second variance term is what makes the interval location-aware. It is largest — so the subtraction is largest, so the interval is narrowest — at sites surrounded by data, and it vanishes as , correctly relaxing the predictive variance to the full marginal far from any observation. You can watch both limits:
p_at <- predict(fit_drop, newdata = train, n_draws = 1000L) # on the data
far <- test[1:50, ]; far$x <- far$x + 500 # far outside
p_far <- predict(fit_drop, newdata = far, n_draws = 1000L)
s2 <- mean(fit_drop$sigma2_draws); t2 <- mean(fit_drop$tau2_draws)
c(sd_at_observed = mean(p_at$sd),
sd_far_away = mean(p_far$sd),
sqrt_marginal = sqrt(s2 + t2))
#> sd_at_observed sd_far_away sqrt_marginal
#> 1.242871 4.879549 4.850063sd_far_away should land on sqrt_marginal,
and sd_at_observed should sit well below it. An
implementation that adds only the nugget would return the same
small number in both columns — narrow intervals everywhere, including
where the model knows nothing.
5.1 Coverage
pred <- predict(fit_drop, newdata = test)
covered <- test$soc >= pred$q025 & test$soc <= pred$q975
c(picp_95 = mean(covered),
mean_width = mean(pred$q975 - pred$q025),
rmse = sqrt(mean((test$soc - pred$mean)^2)),
r2 = 1 - sum((test$soc - pred$mean)^2) /
sum((test$soc - mean(train$soc))^2))
#> picp_95 mean_width rmse r2
#> 0.9200000 18.0049470 4.5371664 0.5702749Read coverage and width together, never separately. An interval from to has perfect coverage; a degenerate one has perfect width. A model earns trust when coverage lands near nominal while the width stays narrow enough to inform a decision.
Note the denominator: the training mean, not the test-set mean. Scoring against the test mean measures the model against an oracle no deployed map has, and inflates for free.
6. Where this connects
bhs_fit() returns an object the package’s unified
uncertainty layer understands, so the same calibration diagnostic
applies here as to every other pillar:
post <- as_edaphos_posterior(fit_drop)
class(post)
#> [1] "edaphos_posterior"See vignette("uncertainty-unified") for the cross-pillar
comparison and vignette("capstone-cerrado-campaign") for
this model inside a full sampling-campaign decision.
7. Limitations
- is profiled, not sampled (§1.1); posteriors are conditional on . Always check the warning before reading the variance split (§3.1).
- The exponential correlation is isotropic. Anisotropic pedogenesis — a catena down a slope — is not represented.
- The Cholesky bounds practical to the low thousands. The RcppArmadillo backend runs the same linear algebra through R’s BLAS, so its speed follows that BLAS (an optimised one such as OpenBLAS or Accelerate helps both backends); it changes neither the exponent nor, with the reference BLAS, the constant.
-
br_cerradois synthesised. The numbers above demonstrate machinery, not a published finding about the Cerrado. For real WoSIS profiles seevignette("case-cerrado-end-to-end").