This folder is Part 3 of Module 04. Ordinary least squares treats counties as independent draws. These seven notebooks ask what to do when the neighbours of a county help explain its diabetes rate. The data are 666 Atlantic-seaboard counties in diabetes_atlantic.shp.
Spatial Regression. This notebook. Says why ordinary least squares fails here, separates a real spillover from a nuisance in the errors, and sets up the data.
OLS Baseline and Diagnostics. Fits that model anyway, then checks the residuals for spatial autocorrelation.
Model Selection: Spatial Dependence Diagnostics. Uses Lagrange multiplier tests and Anselin’s rule to choose among the spatial models, and checks how much the weights change that choice.
Spatial Regression Model Families. Fits the spatial lag, spatial error, and spatial Durbin models, and reads what each coefficient means.
Comparison, Reporting and Diagnostics. Sets the models side by side, tests them with a likelihood ratio, and keeps a model only when the residual Moran statistic is acceptable.
Limits and Connections. Tests the shared assumption that one coefficient applies to the whole region, by splitting the seaboard into a northern half and a southern half.
Code Skeleton and Exercises. Collects the workflow and works five problems that use every chapter in this part.
Part 2 established that Dia_pct is spatially autocorrelated across counties. This chapter asks the natural next question: what does that mean for a regression model that explains diabetes prevalence from covariates like obesity and physical inactivity? The short answer: plain OLS is no longer safe, in one of two distinct ways: sets up everything that follows in Part 3.
Step
What we do
Diagnosis
Show concretely why spatially dependent residuals break OLS’s standard-error and, in one case, coefficient guarantees
Two mechanisms
Distinguish substantive dependence (real spillovers between counties) from nuisance dependence (an unmodelled spatially structured omitted variable)
Taxonomy
Place OLS, SLX, SAR (SLM), SEM, SARAR, SDM, and SDEM on one map, and note which this library implements
Data
Prepare the regression dataset used throughout Part 3: Dia_pct on six health/access covariates plus an urban/rural indicator, over 666 Atlantic-seaboard counties
By the end, Chapter 3.2 fits the OLS baseline on this exact dataset and starts accumulating the diagnostic evidence that Chapters 3.3-3.5 use to choose a model.
API overview
- Queen
- Moran
- OLS
Setup
Locate the repository root, import the spatial-statistics helpers, and point DATA at the example files.
Installation. This notebook needs installation option 3 (core, spatial analysis and spatial statistics): pip install "geolattice[statistics]". See “Installation options” in the GeoLattice README.
Code
import sysfrom pathlib import Pathimport numpy as npimport pandas as pdimport geopandas as gpdimport matplotlib.pyplot as pltROOT = Path.cwd().resolve()for candidate in [ROOT, *ROOT.parents]:if (candidate /"pyproject.toml").is_file() and (candidate /"Data").is_dir(): ROOT = candidatebreakelse:raiseFileNotFoundError("Could not find the GeoLattice repository root.")sys.path.insert(0, str(ROOT))DATA = ROOT /"Data"/"00_shared"/"data_spatial_stat"import geolattice.spatial_statisticsfrom geolattice.viz import apply_map_stylefrom geolattice.spatial_statistics.weights import Queenfrom geolattice.spatial_statistics.esda import Moranfrom geolattice.spatial_statistics.regression import OLSapply_map_style()C = {"blue": "#2b6cb0", "red": "#c0392b", "green": "#2f855a", "orange": "#dd6b20","grey": "#718096", "purple": "#6b46c1", "teal": "#2c7a7b"}print(f"geolattice.spatial_statistics : version {geolattice.spatial_statistics.__version__}")print(f"data folder : {DATA.relative_to(ROOT)}/")
geolattice.spatial_statistics : version 0.3.49
data folder : Data/00_shared/data_spatial_stat/
Why OLS Fails on Spatial Data
OLS assumes each observation’s error term is drawn independently. Part 2’s whole apparatus: Moran’s I, LISA, exists because that assumption routinely fails for areal data: neighbouring counties share climate, policy, infrastructure, and demographics, so their unexplained variation is correlated too. Two distinct failure modes follow, depending on where the dependence actually lives:
If the dependence is in the errors (an omitted spatially structured variable, or measurement error that clusters geographically), OLS coefficients remain unbiased, but the reported standard errors are wrong : usually too small, because the effective sample size is less than \(n\) independent observations would give. Confidence intervals are too narrow and p-values overstate significance.
If the dependence reflects a genuine spillover: one county’s outcome directly depends on its neighbours’ outcomes, not just on shared covariates: then the true model has \(y\) on both sides implicitly (through a term like \(\rho W y\)), and omitting that term biases every coefficient, not just the standard errors, because \(Wy\) is correlated with the included regressors whenever they are themselves spatially patterned.
Chapter 3.2 puts numbers on the first failure mode directly, and Chapter 3.3’s Lagrange Multiplier tests are built specifically to tell the two apart.
Two Mechanisms: Substantive vs. Nuisance Dependence
Substantive dependence
Nuisance dependence
Interpretation
A real causal channel: outcomes in one place influence outcomes in neighbouring places
An artefact of the model: some spatially structured driver is missing from \(X\), so its influence shows up in the residuals instead
Formal structure
\(y = \rho W y + X\beta + \varepsilon\), the spatial lag (SAR/SLM) model
\(y = X\beta + u,\ u = \lambda W u + \varepsilon\), the spatial error (SEM) model
What \(\beta\) means
Not a marginal effect: a change in \(x_k\) anywhere propagates through \(\rho\) to every other county (Chapter 3.4’s impacts())
Retains its ordinary OLS interpretation; \(\lambda \ne 0\) says “something spatially structured is missing”, not “your \(\beta\)’s are wrong”
Correct response
Model the spillover explicitly (spatial lag or Durbin model)
Add the missing covariate if you can identify it, or model the nuisance directly (spatial error model)
This is Part 2, Chapter 2.1’s dependence-vs-heterogeneity distinction, made operational: a regression’s LM tests (Chapter 3.3) are a formal, data-driven way to ask which of the two, if either, is present, rather than guessing from theory alone.
OLS (Ordinary Least Squares): The basic, familiar regression model. It assumes each area’s outcome is independent of its neighbors, except for shared covariates. No special spatial effects are included. Use this as a baseline.
SLX (Spatial Lag of X): Like OLS, but also includes “neighbor averages” of each predictor as extra inputs. For example, it doesn’t just use a county’s own obesity rate, but also its neighbors’ average obesity rate. Helps capture the effect of neighboring conditions.
SAR / SLM (Spatial Lag Model): Adds the outcome values of neighboring areas (“Wy”) directly into the regression. Here, a change in one county can ripple through to others, outcomes actually influence each other, beyond the covariates.
SEM (Spatial Error Model): Instead of outcomes influencing each other, this model assumes that some unmeasured, spatially-patterned factor is affecting the residuals (“leftover errors”). Neighboring counties’ errors are correlated, but outcomes themselves don’t cause each other.
SARAR: Combines SAR/SLM and SEM in one model, meaning both outcome spillovers and spatially-patterned residuals are present. Not implemented here.
SDM (Spatial Durbin Model): Combines SAR/SLM and SLX, outcomes and predictors can both spill over to neighbors. Good when both direct and indirect neighborhood effects may matter.
SDEM: Combines SEM and SLX, neighboring effects come through the predictors and the residuals, but not the outcome itself.
\(y = X\beta + WX\theta + u,\ u = \lambda Wu + \varepsilon\) (SEM + lagged covariates)
✅ SpatialError(slx=True)
Every model but SARAR is available; Chapter 3.4 works through SLM, SEM, and the Durbin variants (SDM, SDEM) in detail, and Chapter 3.5 shows the “common factor” relationship that connects SDM back to SEM.
Data Preparation
The running example for the rest of Part 3: diagnosed diabetes prevalence (Dia_pct) explained by obesity, physical inactivity, exercise access, primary-care access, food-environment quality, social vulnerability, and an urban/rural indicator, across 666 counties along the Atlantic seaboard: a larger, more geographically extensive dataset than Part 2’s 217-county Northeast subset, chosen here so the regression has more power and a genuinely non-trivial spatial footprint.
Code
counties = gpd.read_file(DATA /"diabetes_atlantic.shp")print(f"diabetes_atlantic.shp: {counties.shape[0]} counties across {counties['STATE'].nunique()} states/DC")print(counties["STATE"].value_counts())
diabetes_atlantic.shp: 666 counties across 11 states/DC
STATE
Georgia 159
Virginia 128
North Carolina 100
Pennsylvania 67
New York 62
West Virginia 55
South Carolina 46
Maryland 24
New Jersey 21
Delaware 3
District of Columbia 1
Name: count, dtype: int64
UrbRural is a string column (“Urban”/“Rural”) and must be coded numerically before it can enter a regression.
Spatial weights are needed from the first model onward (Chapter 3.2’s residual diagnostics already require w), so we build them once here: Queen contiguity, row-standardised: the same default used throughout Part 2.
Code
w = Queen(counties)print(w.summary())
Spatial Weights (W)
===================
Observations 666
Transform row
Min neighbors 1
Mean neighbors 5.423
Max neighbors 11
Islands 0
Components 1
Nonzero weights 3612
No islands on this larger, more contiguous dataset: unlike Part 2’s Northeast subset (which had Nantucket as an isolated county), every Atlantic county has at least one Queen neighbour, so none of Part 2’s island-handling caveats apply here. This matters for Part 3 specifically: every model below needs \(W\) to represent a fully row-stochastic, invertible system (via \((I - \rho W)^{-1}\) for the lag model), which an island would complicate.
Code
global_moran = Moran(y, w, permutations=999, seed=1)print(f"Moran's I of raw Dia_pct: {global_moran.I:.4f} (p_sim={global_moran['p_sim']:.4f})")
Moran's I of raw Dia_pct: 0.3707 (p_sim=0.0010)
Diabetes prevalence is itself strongly autocorrelated, exactly as in Part 2: but that alone does not tell us why a regression of Dia_pct on these covariates would need a spatial model: if the covariates themselves fully explain the spatial pattern, plain OLS residuals could still be independent. Chapter 3.2 checks this directly, on the residuals rather than the raw outcome.
Summary and Conclusions
This chapter set up the conceptual and data foundation for spatial regression.
What we did
Explained the two distinct ways OLS can fail on spatial data: nuisance dependence (wrong standard errors, unbiased coefficients) and substantive dependence (biased coefficients from an omitted spatial-lag term).
Mapped that distinction onto the spatial error (SEM) and spatial lag (SAR/SLM) models respectively.
Placed every model in this library’s taxonomy, OLS, SLX, SAR, SEM, SDM, SDEM, noting that SARAR alone is not implemented.
Prepared the Part 3 regression dataset: Dia_pct on six covariates plus a coded Urban indicator, across 666 Atlantic-seaboard counties, with a row-standardised, island-free Queen W.
Confirmed the outcome variable is itself strongly spatially autocorrelated (Moran’s I = 0.371, \(p_\text{sim}=0.001\)), a stronger raw signal than Part 2’s 217-county Northeast subset (I = 0.240), before any covariate has even been considered.
Practical takeaways
Do not assume which mechanism (substantive vs. nuisance) is at work from theory alone: Chapter 3.3’s LM tests exist because the two are formally distinguishable from the same OLS residuals.
A string categorical column silently breaks a regression if not coded numerically first; always check X.dtypes before fitting.
Confirming zero islands in \(W\) up front avoids a class of failures (a non-invertible \((I-\rho W)\)) that would otherwise surface confusingly deep inside Chapter 3.4’s maximum-likelihood fitting.
Next steps
Chapter 3.2 (OLS Baseline and Diagnostics) fits the OLS model on exactly this data and runs the classical and spatial diagnostics, condition number, normality, heteroskedasticity, and residual Moran’s I, that Chapter 3.3 builds on.