besag
A spatial model for areas on a map: each area is pulled towards the mean of its neighbours, by the same amount everywhere.
Idea
Disease rates in small areas are noisy. The besag model (Besag et al., 1991) smooths them: each area borrows strength from its neighbours, with one precision $\tau$ for the whole map. It has no noise term of its own; bym2 adds one, and fbesag lets the precision differ between parts of the map.
Model
where $n_i$ is the number of neighbours of area $i$ and $j \sim i$ means that $j$ is a neighbour of $i$. Together, $\mathbf x$ has precision matrix $Q = \tau R$, with $R_{ii} = n_i$, $R_{ij} = -1$ for neighbours and $0$ otherwise.
$R$ is singular, so $\mathbf x$ sums to zero in each connected part of two or more areas. With scale.model=True, $R$ is scaled so that the geometric mean of the marginal variances is 1 (Sørbye and Rue, 2014); then $1/\sqrt\tau$ is a typical sd of $x_i$, whatever the map. pyinla reports $\tau$ as Precision for idx.
Prior
The prior is on $\theta = \log\tau$, set with hyper.
hyper | meaning | |
|---|---|---|
| default | [{'prior': 'loggamma', 'param': [1, 0.00005]}] | $\tau \sim \text{Gamma}(1,\ 0.00005)$ (shape, rate) |
| PC prior | [{'prior': 'pc.prec', 'param': [1, 0.01]}] | $P(1/\sqrt\tau > 1) = 0.01$ (Simpson et al., 2017); use with scale.model=True |
Example: dengue in Brazil
Dengue cases $y_i$ and expected cases $E_i$ in April in the 558 microregions of Brazil (Lowe et al., 2021):
Data: brazil_558_microregions.csv, brazil_558_microregions.graph, brazil_558_microregions.geojson.
import numpy as np
import pandas as pd
from pyinla import pyinla
areas = pd.read_csv("brazil_558_microregions.csv") # idx, region, Y and E of April
graph = "brazil_558_microregions.graph"
besag = {"id": "idx", "model": "besag", "graph": graph, "scale.model": True,
"hyper": [{"prior": "pc.prec", "param": [1, 0.01]}]} # P(sd > 1) = 0.01
fit = pyinla(model={"response": "Y", "fixed": ["1"], "random": [besag]},
family="poisson", data=areas, E=areas["E"].to_numpy())
print(fit.summary_hyperpar[["mean", "0.025quant", "0.975quant"]].round(2))
mean 0.025quant 0.975quant
Precision for idx 0.26 0.23 0.3
$1/\sqrt\tau \approx 2$: neighbouring areas can differ a lot on this map.
import geopandas as gpd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
map_df = gpd.read_file("brazil_558_microregions.geojson").sort_values("idx").reset_index(drop=True)
brks = [0, 0.2, 0.5, 1, 2, 5, np.inf]
labels = ["< 0.2", "0.2-0.5", "0.5-1", "1-2", "2-5", "> 5"]
cols = ListedColormap(["#2c7bb6", "#abd9e9", "#e0f3f8", "#fee090", "#fdae61", "#d7191c"])
def binned_map(ax, values, title):
v = pd.Categorical(pd.cut(values, brks, right=False, labels=labels), categories=labels)
map_df.assign(v=v).plot("v", ax=ax, cmap=cols, linewidth=0, legend=True,
legend_kwds={"loc": "lower left", "fontsize": 8, "frameon": False})
ax.set_title(title)
ax.set_axis_off()
# observed over expected, and the fitted relative risk e^{beta_0 + x_i} (posterior means),
# both relative to the whole country
overall = areas["Y"].sum() / areas["E"].sum()
beta0 = fit.summary_fixed["mean"].iloc[0]
x = fit.summary_random["idx"]["mean"].to_numpy()
smr = areas["Y"] / areas["E"] / overall
rr = np.exp(beta0 + x) / overall
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
binned_map(ax[0], smr, "observed / expected")
binned_map(ax[1], rr, "besag: relative risk")
# how much besag moves each area away from observed / expected, by quarter of E
pos = areas["Y"] > 0 # areas with cases
change = np.abs(np.log(rr[pos]) - np.log(smr[pos]))
print(change.groupby(pd.qcut(areas["E"][pos], 4, labels=["smallest E", "2nd", "3rd", "largest E"]),
observed=True).mean().round(3).to_string())
E
smallest E 0.080
2nd 0.097
3rd 0.079
largest E 0.044

With many cases in most areas, besag moves the observed ratios little: by 4% to 10% on average (on the log scale), least where the expected count is largest.
Reference
Options
| entry, for example | default | meaning |
|---|---|---|
'id': 'idx' | column with the area index, $1, \dots, n$ | |
'model': 'besag' | ||
'graph': graph | the neighbours (below) | |
'scale.model': True | False | scale $R$ (above) |
'constr': False | True | sum to zero in each connected part; with False, remove the intercept: 'fixed': ['0', ...] |
'adjust.for.con.comp': False | True | one constraint per connected part (below) |
'hyper': [...] | loggamma | prior of $\theta$ (examples below) |
'n': 558 | from the graph | number of areas |
'values': list(range(1, 559)) | from the graph | ids of the areas |
'extraconstr': {'A': A, 'e': e} | None | further constraints $A\mathbf x = \mathbf e$ |
'rankdef': 1 | from the graph | rank deficiency of $R$ |
'diagonal': 1e-4 | 0 | constant added to the diagonal of $Q$ |
'weights': w | None | weight of $x_i$ in each observation, one per observation |
In the examples, graph is the graph file of the example above, and A, e and w are arrays you make.
Hyperparameter
| prior | param | initial | fixed | |
|---|---|---|---|---|
| $\theta = \log\tau$ | 'loggamma' | [1, 0.00005] | 4 ($\tau \approx 54.6$) | False |
To fix $\tau$, for example at 10 (then summary_hyperpar is None):
'hyper': [{'initial': np.log(10), 'fixed': True}]
Priors tested with besag: loggamma, pc.prec, flat, logtnormal, normal (or gaussian), laplace, pc.mgamma, jeffreystdf, and your own as 'expression: ...' or 'table: ...'.
Graph
graph is a dense or sparse adjacency matrix, an InlaGraph, or a graph file: line 1 is the number of areas $n$, then one line per area, i k nb_1 ... nb_k (the area, its number of neighbours, the neighbours). A file that numbers the areas from 0 is detected.
Disconnected maps
scale.model | adjust.for.con.comp | constraints | scaling | area without neighbours |
|---|---|---|---|---|
False | False | one for the whole map | none | flat |
True | False | one for the whole map | whole map | standard normal |
False | True | one per connected part | none | flat |
True | True | one per connected part | per connected part | standard normal |
Constraints are sum-to-zero; a connected part has two or more areas, and areas without neighbours are left out of the scaling. With adjust.for.con.comp=True, rankdef is the number of connected parts.
INLA leaves $\frac{1}{2}\log|R|^*$ out of the log marginal likelihood ($|R|^*$: the product of the non-zero eigenvalues of $R$). To compare with bym2, see bym2.
References
- Besag, J., York, J. and Mollié, A. (1991). Bayesian image restoration, with two applications in spatial statistics. Annals of the Institute of Statistical Mathematics, 43, 1–20.
- Lowe, R., Lee, S. A., O’Reilly, K. M. et al. (2021). Combined effects of hydrometeorological hazards and urbanisation on dengue risk in Brazil: a spatiotemporal modelling study. The Lancet Planetary Health, 5, e209–e219.
- Simpson, D., Rue, H., Riebler, A., Martins, T. G. and Sørbye, S. H. (2017). Penalising model component complexity: a principled, practical approach to constructing priors. Statistical Science, 32, 1–28.
- Sørbye, S. H. and Rue, H. (2014). Scaling intrinsic Gaussian Markov random field priors in spatial modelling. Spatial Statistics, 8, 39–51.