A compact, reusable workflow skeleton, and five solved exercises spanning every chapter in this Part. This notebook is Part 3. Spatial Regression (Chapter 3.7 of 7). The worked example uses diabetes_atlantic.shp (666 counties). The methods come from geolattice.spatial_statistics.regression, geolattice.spatial_statistics.weights.
Overview
This closing chapter has two parts: a minimal, reusable skeleton that reproduces the entire Chapters 3.2-3.5 workflow in about a dozen lines, and five solved exercises that revisit specific claims from earlier chapters with fresh checks: including one exercise whose answer complicates the textbook expectation in an honest, data-driven way (Section 4.1).
Step
What we do
Skeleton
The complete fit → diagnose → compare → interpret pipeline, condensed
Exercises
Five solved problems spanning Chapters 3.2 (OLS), 3.3 (LM tests), 3.4 (impacts), and 3.5 (comparison)
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 Queen, KNNfrom geolattice.spatial_statistics.regression import OLS, SpatialLag, SpatialError, SpatialDurbin, compare_models, lr_testapply_map_style()C = {"blue": "#2b6cb0", "red": "#c0392b", "green": "#2f855a", "orange": "#dd6b20","grey": "#718096", "purple": "#6b46c1", "teal": "#2c7a7b"}counties = gpd.read_file(DATA /"diabetes_atlantic.shp")print(f"geolattice.spatial_statistics : version {geolattice.spatial_statistics.__version__}")
geolattice.spatial_statistics : version 0.3.49
The Code Skeleton
Everything from Chapters 3.2-3.5, condensed to the essential calls:
Code
from geolattice.spatial_statistics.weights import Queenfrom geolattice.spatial_statistics.regression import OLS, SpatialLag, SpatialError, SpatialDurbin, compare_models, lr_testcovariates = ["Obesity", "PhysInact", "Acc_Exer", "PCP_rate", "FoodEnvIdx", "SVI"]X = counties[covariates].copy()X["Urban"] = (counties["UrbRural"] =="Urban").astype(int) # code categoricals before fittingy = counties["Dia_pct"]w = Queen(counties) # row-standardised by defaultols = OLS(y, X, w=w)print(ols.lm_tests().recommendation()) # 3.3: which spatial model does the data ask for?slm, sem = SpatialLag(y, X, w), SpatialError(y, X, w)sdm = SpatialDurbin(y, X, w)print(compare_models({"OLS": ols, "SLM": slm, "SEM": sem, "SDM": sdm})) # 3.5: side-by-sideprint(slm.impacts(seed=1)) # 3.4: direct / indirect / total, with intervalsprint(lr_test(ols, sem)) # 3.5: formal nested-model test
Running this cell reproduces every headline number from Chapters 3.2-3.5 in one place: a useful starting point to adapt for a new dataset or a new set of covariates.
Exercises
SEM vs. SLM: which stays close to OLS?
Theory (Chapter 3.4) predicts SEM coefficients should track OLS closely (spatial dependence is a nuisance, not a structural change), while SLM’s should differ more systematically (part of the covariates’ apparent effect is reattributed to \(\rho Wy\)). Check this claim coefficient by coefficient, not just by eyeballing the summary tables.
Answer: the textbook expectation only holds for part of the coefficient vector. For the two strongest, most significant predictors, Obesity and PhysInact, both with \(|t|>10\) in the OLS fit, SEM is dramatically closer to OLS than SLM is (about 6× closer: |SEM-OLS|\(\approx 0.002\) vs. |SLM-OLS|$\approx 0.010$ for both). But forFoodEnvIdx,SVI, and especiallyUrban` (already the least significant covariate in every model), the pattern reverses: SEM moves further from OLS than SLM does. The honest conclusion: SEM’s closeness to OLS is a tendency for well-identified coefficients, not a guarantee for every coefficient in the model, and a summary statistic averaged across all seven coefficients (mean \(|SLM-OLS|=0.015\) vs. mean \(|SEM-OLS|=0.025\)) would actually get the overall comparison backwards here. Always check coefficient by coefficient rather than trusting an aggregate summary or a single textbook rule of thumb.
LM tests vs. AIC: do they agree between SLM and SEM?
Chapter 3.3’s LM tests recommended the spatial error model. Does comparing SLM and SEM by AIC alone reach the same conclusion?
LM recommendation: Spatial error model (both robust tests significant; larger statistic chosen — consider SARMA/Durbin)
AIC: SLM=1553.58 SEM=1541.65 (lower is better)
BIC: SLM=1594.09 SEM=1582.16
AIC prefers: SEM
Answer: yes, they agree. SEM’s AIC (1541.65) is lower than SLM’s (1553.58), and its BIC is lower too (1582.16 vs. 1594.09): both criteria independently confirm the LM battery’s recommendation. This is the expected, reassuring case (contrast with Chapter 3.5, where AIC and BIC disagreed about SDM specifically, Section 4.5 below explains why that disagreement happens there and not here).
The impacts identity under a non-row-standardised W
Chapter 3.4 showed the exact identity total impact \(=\beta/(1-\rho)\) holds for row-standardised weights. Does it still hold for binary (non-row-standardised) weights?
Answer: no, the simple scalar identity breaks down. The total column (computed via the general trace-based impacts() formula) no longer matches beta / (1 - rho) once \(W\) is not row-standardised: every row shown differs, though only slightly here because \(\hat\rho\) happens to be very small (0.0046) for this particular binary-\(W\) fit. The reason: the shortcut \(\text{total}=\beta/(1-\rho)\) relies on the constant vector \(\mathbf{1}\) being an eigenvector of \(W\) with eigenvalue 1: true by construction for row-standardised weights (every row sums to exactly 1), but not for binary weights (row sums equal each county’s raw neighbour count, which varies). impacts()’s general formula: built from \(\text{tr}(A^{-1})\) and \(\mathbf{1}^\top A^{-1}
\mathbf{1}\) rather than the scalar shortcut: remains correct regardless; only the simplified identity is transform-specific.
Refitting with KNN(6): do conclusions change?
Chapter 3.3 and 3.5 already checked this piecemeal. Consolidate: under KNN(6) weights, does the model recommendation, the residual-Moran acceptance test, and the AIC/BIC pattern all still hold?
Answer: every conclusion is unchanged. LM tests still recommend the spatial error model; AIC still prefers SDM (1524.6) and BIC still prefers SEM (1572.4); SEM and SDM residuals still pass the near-zero acceptance test (SEM: \(I=-0.014\), \(p=0.57\)) while OLS and SLM do not. The specific numbers move somewhat (as they did throughout Part 3 whenever the weights definition changed) but the qualitative story built across Chapters 3.2-3.5 is robust to this particular alternative.
Why AIC and BIC disagree about the SDM
Chapter 3.5 found AIC prefers SDM while BIC prefers SEM. Explain the mechanism precisely, using the actual parameter counts and log-likelihoods.
Code
sdm = SpatialDurbin(y_ex, X_ex, w)n = sdm.ndelta_loglik = sdm.loglik - sem.loglikdelta_params = sdm.n_params - sem.n_paramsprint(f"n = {n}")print(f"SEM: n_params={sem.n_params}, loglik={sem.loglik:.3f}")print(f"SDM: n_params={sdm.n_params}, loglik={sdm.loglik:.3f}")print(f"extra log-likelihood from SDM's {delta_params} extra parameters: {delta_loglik:.3f}")print(f"\nAIC penalty per extra parameter : 2")print(f"BIC penalty per extra parameter : ln(n) = {np.log(n):.3f}")print(f"\nAIC: SDM wins by {2*(-delta_params) +2*delta_loglik:.2f} (negative = SDM lower/better)" )print(f"BIC: SEM wins by {np.log(n)*delta_params -2*delta_loglik:.2f} (positive = SDM's extra BIC cost exceeds its loglik gain)")
n = 666
SEM: n_params=9, loglik=-761.826
SDM: n_params=16, loglik=-753.109
extra log-likelihood from SDM's 7 extra parameters: 8.717
AIC penalty per extra parameter : 2
BIC penalty per extra parameter : ln(n) = 6.501
AIC: SDM wins by 3.43 (negative = SDM lower/better)
BIC: SEM wins by 28.07 (positive = SDM's extra BIC cost exceeds its loglik gain)
Answer: SDM’s 7 extra parameters buy a log-likelihood improvement of about 8.7 points (\(-753.1\) vs. \(-761.8\)). AIC charges only 2 points per extra parameter (\(2 \times 7 = 14\)), so a gain of \(2\times8.7\approx17.4\) in likelihood terms comfortably clears that charge, and AIC prefers SDM. BIC charges \(\ln(n) = \ln(666) \approx 6.5\) points per extra parameter (\(6.5\times7\approx45.6\)): far more than the ~17.4-point likelihood gain can justify, so BIC prefers the more parsimonious SEM. The disagreement is not a contradiction or a sign that either criterion is wrong; it is a direct, computable consequence of how much more heavily BIC penalises additional parameters as \(n\) grows (\(\ln(n)\) versus AIC’s constant 2), and it recurs in exactly the same form any time a richer model’s likelihood gain is real but modest relative to its added parameter count.
Summary and Conclusions
This chapter closed Part 3 with a reusable code skeleton and five exercises that stress-tested specific claims from Chapters 3.2-3.5.
What we did
Condensed the full Chapters 3.2-3.5 workflow into a compact, reusable skeleton.
Exercise 1 found the “SEM close to OLS” rule of thumb holds strongly for the two best-identified coefficients but reverses for three weaker ones: a genuine complication, not a clean confirmation.
Exercise 2 confirmed LM tests and AIC/BIC agree on SLM vs. SEM (unlike the AIC/BIC disagreement about SDM specifically).
Exercise 3 showed the impacts identity total\(=\beta/(1-\rho)\) is specific to row-standardised weights and breaks down, in general, for binary weights.
Exercise 4 consolidated every KNN(6) robustness check from earlier chapters: every qualitative conclusion in Part 3 survives the alternative weights definition.
Exercise 5 derived, with actual numbers, exactly why AIC prefers SDM while BIC prefers SEM: a direct consequence of BIC’s \(\ln(n)\) per-parameter penalty versus AIC’s constant 2.
Practical takeaways
Textbook rules of thumb (like “SEM tracks OLS”) are tendencies, not guarantees: verify them coefficient by coefficient on your own data before repeating them as a finding.
A convenient closed-form identity (impacts under row-standardisation) is often a special case; check whether the general formula is being used before assuming a shortcut applies.
AIC vs. BIC disagreements are fully explainable from the parameter count and sample size alone: compute the breakeven point rather than treating the disagreement as ambiguous.
Part 3 in review
Across seven chapters, Part 3 took a single diagnosed problem (Part 2’s confirmed spatial autocorrelation in diabetes prevalence) through a complete, validated workflow: diagnose the mechanism (Chapter 3.3), fit the recommended model and understand what its parameters mean (Chapter 3.4), confirm the fit actually solved the problem it was chosen for (Chapter 3.5), and stress-test the one assumption every model in the Part still shares (Chapter 3.6). Part 4 (Spatial Cluster Analysis) returns to the where question with a fuller toolkit than Part 2’s LISA; Part 6 (Geographically Weighted Models) is the direct continuation of Chapter 3.6’s finding that a single global \(\beta\) is not always enough.
Anselin, L. (1988). Spatial Econometrics: Methods and Models. Kluwer Academic.
The reference underlying every method used across Part 3
LeSage, J. & Pace, R. K. (2009). Introduction to Spatial Econometrics. CRC Press.
Impacts, model comparison, and practical estimation guidance
Key papers
Paper
Contribution
Burnham, K. P. & Anderson, D. R. (2004). Multimodel inference: understanding AIC and BIC in model selection. Sociological Methods & Research, 33, 261-304.
The AIC/BIC penalty comparison used in Exercise 4.5
In this library
Object
Role
geolattice.spatial_statistics.regression.*
Every object used across Part 3, summarised in the Section 3 skeleton
Part 4
geolattice.spatial_statistics.cluster: the fuller “where” toolkit continuing from Part 2’s LISA
Part 6
geolattice.spatial_statistics.gwmodel: the direct continuation of Chapter 3.6