slm: spatial regression (spreg)¶
The user guide of this module: slm.
- apatools.slm.fit_model(model, Y, X, w, **kwargs)[source]¶
Generator that fits one or several spreg models and yields the fitted results.
- Parameters:
model (str, spreg model class, or list/tuple of them) –
"ols"(spreg.OLS),"slm"(spatial lag, maximum likelihood,spreg.ML_Lag) or"sem"(spatial error, maximum likelihood,spreg.ML_Error), the classes themselves, or a list/tuple (one result per entry, in order). Other strings raiseNotImplementedError. An unknown class is called asmodel(Y, X, w, **kwargs)with themodel_-prefixed keywords.Y (array-like) – Dependent variable (
norn x 1).X (array-like or pandas.DataFrame) – Predictors without constant; spreg adds the constant itself.
w (libpysal.weights.W or None) – Spatial weights aligned with the rows (
Noneonly for"ols"without spatial diagnostics).**kwargs –
verbose(bool, default False) prints the model name and the arguments passed on. Arguments for spreg are named<model>_model_<argument>with<model>inols/slm/sem(the first prefix is dropped, thenmodel_), e.g.ols_model_spat_diag=Trueorslm_model_method="LU". Other keywords are ignored.
- Yields:
spreg model object –
model(Y, X, w, **model_kwargs)(spreg models are fitted on construction).
- apatools.slm.base_metrics(results)[source]¶
Collect fit metrics (R²/pseudo R², adjusted R², F-test, AIC/BIC/LL, MAE, MAD) from a spreg results object.
spreg.OLS:r2,ar2and the F test (f_stat) of spreg.spreg.ML_Lag/spreg.ML_Error:r_sqis spreg’s pseudo R² (pr2, the squared correlation between observedyand the predictedpredy);r_sq_adj = 1 - (1 - R²)(n - 1) / df_residand the F statistic(R² / df_model) / ((1 - R²) / df_resid)with its F-distribution p-value are computed here (a rough, descriptive analogue; there is no exact F test for ML models). The parameter countkof spreg includesrhofor the lag model but notlambdaof the error model, which is added here.
- Parameters:
results (spreg model object) – Fitted
OLS,ML_LagorML_Error.- Returns:
dict –
r_sq,r_sq_adj,df_model(number of parameters minus the constant, so includingrho/lambda),df_resid(n - k),f_stat,f_pvalue,n_obs,n_params(including the constant andrho/lambda),mae(mean absolute residualy - predy),mad(median absolute deviation of the residuals,median(|e - median(e)|), not rescaled),aic,bic(Schwarz criterion; like spreg’s, but countinglambdaof the error model as a parameter) andllf(log-likelihood; spreg’slogll).
References
Anselin, L. (1988). Spatial econometrics: Methods and models. Kluwer Academic. https://doi.org/10.1007/978-94-015-7799-1
- apatools.slm.pred_metrics(results, model, Y, X, w, exclude_neighbors=False, **kwargs)[source]¶
Leave-one-out prediction metrics (R²pred, MAEpred, MADpred) for spreg models.
Every observation
iis held out in turn, the model is refitted on the remaining observations (with the spatial weights restricted to them, seew_subset_rows()) andy_iis predicted. The prediction depends on the model:olsandsem(spatial error):x_i·β(the trend; the error process is not used for prediction, which is also what spreg’spredyis);slm(spatial lag):ρ·(Wy)_i + x_i·β, i.e. the observedyvalues of the neighbours ofiare used through the original weights row ofi. This predictor uses more information than the one for ols/sem, so the R²pred values of the models are not strictly comparable.
Warning
Spatial data are autocorrelated. In plain leave-one-out the neighbours of the held-out observation stay in the training sample, and their (correlated) values leak into the fit, so R²pred is optimistic with respect to predicting a new, unseen region. Use
exclude_neighbors=Truefor a more honest estimate: the neighbours ofi(according tow) are removed from the training sample as well (iis still the only observation that is predicted). Because the refit has fewer rows this variant is slightly pessimistic for small samples and may create islands in the training weights.Cost: one model fit per observation and model (
nfits). For ML lag/error models each fit computes the log-determinant ofW; pass e.g.slm_model_method="LU"/sem_model_method="LU"or"ord"for largen.- Parameters:
results (list) – Fitted spreg models returned by the full-sample fit, one per entry of
model(used for the design matrix, so that a constant added by spreg is handled).model (str or list of str) – The models that were fitted (
"ols","slm","sem").Y (array-like) – Data used for the full-sample fit;
wmust be aligned with the rows.X (array-like) – Data used for the full-sample fit;
wmust be aligned with the rows.w (libpysal.weights.W or None) – Spatial weights.
Noneis only possible for plainols.exclude_neighbors (bool) – Also remove the neighbours of the held-out observation from the training sample.
**kwargs – The same model arguments as passed to
slm(). Diagnostics of OLS are switched off inside the loop for speed.
- Returns:
list of dict – One dict per model with
pred_loo_r_sq(clipped to [-1, 1], as inapatools.lm.pred_metrics()),pred_loo_maeandpred_loo_mad(median absolute deviation of the prediction errors).nanif every refit failed. Failed refits are skipped with a warning.
Notes
This is a cross-validation-style metric. With
e_i = y_i - ŷ_ithe prediction errors of the successfully refitted observations,pred_loo_r_sq = 1 - Σ e_i² / Σ (y_i - ȳ)²(ȳis the mean of all observations, the sums run over the predicted observations), clipped to [-1, 1];pred_loo_mae = mean(|e_i|);pred_loo_mad = median(|e_i - median(e)|). AUserWarningis issued if refits failed or if the training weights of some refits contain islands (observations without neighbours). Thewmust have as many observations as the data (ValueErrorotherwise).References
Roberts, D. R., Bahn, V., Ciuti, S., Boyce, M. S., Elith, J., Guillera-Arroita, G., Hauenstein, S., Lahoz-Monfort, J. J., Schröder, B., Thuiller, W., Warton, D. I., Wintle, B. A., Hartig, F., & Dormann, C. F. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography, 40(8), 913-929. https://doi.org/10.1111/ecog.02881
Anselin, L. (1988). Spatial econometrics: Methods and models. Kluwer Academic. https://doi.org/10.1007/978-94-015-7799-1
- apatools.slm.slm(data, y=None, x=None, w=None, model='ols', formula=None, **kwargs)[source]¶
Fit OLS, spatial lag (SLM,
ML_Lag) and spatial error (SEM,ML_Error) models with spreg.The spatial lag model is
y = ρWy + Xβ + εand the spatial error model isy = Xβ + u,u = λWu + ε(Anselin, 1988), both estimated by maximum likelihood. Requires the optional dependenciesspregandlibpysal(forw).- Parameters:
data (pandas.DataFrame) – The data; its rows must be in the order of
w.id_order.y (str) – Dependent variable; ignored if
formulais given.w (libpysal.weights.W) – Spatial weights (required for SLM/SEM and for OLS spatial diagnostics).
model (str or list of str) –
"ols","slm","sem"or a list of them.formula (str, optional) – patsy formula; overrides
y/x.**kwargs – Function options (below) and spreg arguments named
<model>_model_<argument>with<model>in ols/slm/sem, e.g.ols_model_spat_diag=True.verbose (bool, default True) – Print the sample size, the formula and the model summaries.
dropna (bool, default True) – Drop rows with NAs (not with
formula: patsy always drops them), with aUserWarning.wis restricted to the remaining rows automatically (formula: needs a uniquedataindex).intercept (bool, default False) – Has no effect on the estimates: spreg always includes a constant (a constant column that is already present is not duplicated, so True and False give the same model). It only changes the printed formula. A model without intercept is not possible with spreg.
standardize (False, True/
"z"or callable, default False) – z-transform (or apply a callable to) the numeric/boolean columns; other columns are dropped. AUserWarningis issued for z-transformation, because it sets the intercept estimate to zero.base_metrics (bool, default True) – Compute
base_metrics()for every model.pred_metrics (bool, default False) – Add leave-one-out prediction metrics, which needs one refit per observation. Leave-one-out is optimistic for spatially autocorrelated data, see
pred_metrics().pred_exclude_neighbors (bool, default False) – With
pred_metrics: also remove the neighbours of the held-out observation from the training sample (less optimistic; needsw).
- Returns:
results (list of spreg model objects) – One fitted
spreg.OLS/spreg.ML_Lag/spreg.ML_Errorper model.metrics (list of dict) – One dict per model (see
base_metrics()):r_sq(pseudo R² for SLM/SEM),r_sq_adj,f_stat,f_pvalue,df_model,df_resid(n - k),n_params,aic,bic,llf,mae,mad(median absolute deviation of residuals),n_obs. Withpred_metrics=Truealsopred_loo_r_sq,pred_loo_mae,pred_loo_mad(seepred_metrics()for how the predictions are made and for the caveat on spatial autocorrelation). Empty if neitherbase_metricsnorpred_metricsis requested. There is no VIF for spreg models.
- Raises:
ValueError – If neither
formulanor non-emptyxtogether withyis given.
References
Anselin, L. (1988). Spatial econometrics: Methods and models. Kluwer Academic. https://doi.org/10.1007/978-94-015-7799-1
Examples
>>> results, metrics = slm( ... test_data, Y, X, w, model=["ols", "slm"], ... verbose=True, ... dropna=True, ... intercept=False, # keep False, spreg adds the constant by default ... standardize="z", # keeps np.number or bool columns only ... base_metrics=True, ... pred_metrics=True, # leave-one-out R²pred, MAEpred, MADpred ... pred_exclude_neighbors=False, ... ols_model_spat_diag=True, ... ols_model_nonspat_diag=True, ... )
- apatools.slm.slm_report(results, metrics=None, format_pval=True, add_stars=True, decimal=3, add_ftest=True, add_aic=True, add_bic=True, add_llf=True, add_mae=True, add_mad=True, add_pred_loo_mae=True, add_pred_loo_mad=True, add_n_obs=True, add_n_groups=False, add_vif=False, intercept_name='Intercept')[source]¶
Build one APA-style coefficient table per model from
slm()output.- Parameters:
results (list) – Fitted spreg models (first value returned by
slm()).metrics (list of dict, optional) – Metrics (second value returned by
slm()), matched withresultsby position; without them the tables have nomodelcolumn.format_pval (bool or callable, default True) –
Falsekeeps the numeric p-values.Truereplaces them by APA strings without thep =prefix (".009","<.001";apatools.format.format_p()). A callable is applied to every p-value and its return value is used. The stars are always computed from the numeric p-values.add_stars (bool or callable, default True) –
False: nosigcolumn.True: add asigcolumn with significance stars (***p < .001,**p < .01,*p < .05,⁺p < .10, otherwise an empty string;apatools.format.get_stars()). A callable maps one p-value to the marker.decimal (int or None, default 3) – Round the columns
coef,se,cilandcirto this many decimals (the statistic and the p-values are not rounded here).Noneor 0: no rounding.add_ftest (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available (the pred_* metrics only exist ifslm()was run withpred_metrics=True). R², R²adj and R²pred are always shown when available.add_aic (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available (the pred_* metrics only exist ifslm()was run withpred_metrics=True). R², R²adj and R²pred are always shown when available.add_bic (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available (the pred_* metrics only exist ifslm()was run withpred_metrics=True). R², R²adj and R²pred are always shown when available.add_llf (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available (the pred_* metrics only exist ifslm()was run withpred_metrics=True). R², R²adj and R²pred are always shown when available.add_mae (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available (the pred_* metrics only exist ifslm()was run withpred_metrics=True). R², R²adj and R²pred are always shown when available.add_mad (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available (the pred_* metrics only exist ifslm()was run withpred_metrics=True). R², R²adj and R²pred are always shown when available.add_pred_loo_mae (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available (the pred_* metrics only exist ifslm()was run withpred_metrics=True). R², R²adj and R²pred are always shown when available.add_pred_loo_mad (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available (the pred_* metrics only exist ifslm()was run withpred_metrics=True). R², R²adj and R²pred are always shown when available.add_n_obs (bool, default True) – Include the corresponding part (F test, AIC, BIC,
LL,MAE,MAD,MAEpred,MADpred,N) in the fit summary string if the metric is available (the pred_* metrics only exist ifslm()was run withpred_metrics=True). R², R²adj and R²pred are always shown when available.add_n_groups (bool, default False) – Include
G = ...if the metrics haven_groups(never the case for spreg models; kept for symmetry withapatools.lm.lm_report()).add_vif (bool, default False) – Join a
vifcolumn if the metrics contain one (spreg models do not).intercept_name (str, default "Intercept") – Row label of the constant (spreg’s
CONSTANT); other labels are unchanged.
- Returns:
list of pandas.DataFrame – One table per model, indexed by the variable names of spreg (the spatial parameter
W_<y>(rho) orlambdaappear as rows), with the columnscoef: estimate;se: standard error;z: the test statistic (spreg’szt_stat; it is a t statistic for OLS but is labelledzfor all models);p-value: p-value (formatted, seeformat_pval);cil,cir: limits of the 95% confidence interval,coef ∓ z_0.975 · sewith the normal quantile 1.96 (confidence level 0.95; also for OLS);sig: significance stars (ifadd_stars);model: filled in the first row only (if metrics are given): the fit summary, e.g.R² = .35, R²adj = .31, R²pred = .22, F(3, 45) = 8.06, p < .001, AIC = ..., N = 49. R²pred, MAEpred and MADpred appear only ifslm()was run withpred_metrics=True(leave-one-out, seepred_metrics()).
- apatools.slm.slm_tests(results, w=None, format_pval=False, add_stars=False, decimal=None, n_perm=999, seed=13)[source]¶
Diagnostic tests of the models fitted with
slm(), as a tidy DataFrame.They check the assumptions of the models and the need for a spatial term; they are not measures of the quality of the fit (see
base_metrics/pred_metricsfor those). Computed per model ofresults(a list as returned byslm()):OLS (
"ols"): Moran’s I of the residuals (ztest; Cliff & Ord, 1972), the Lagrange multiplier tests for a missing spatial lag (LM-lag) and for spatial error dependence (LM-error), their robust versions (robust to the other alternative) andLM-SARMAfor both together (Anselin et al., 1996; Burridge, 1980; Bera & Yoon, 1993), and the tests of normality (Jarque-Bera) and heteroskedasticity (Breusch-Pagan, Koenker-Bassett with the regressors of the model as in R’sbptest, White) of the residuals. The spatial tests needw. Null hypotheses: no spatial autocorrelation of the residuals / no spatial lag / no spatial error dependence / neither; normally distributed residuals; homoskedastic residuals.Spatial lag (
"slm") and spatial error ("sem") models: the z test of the spatial parameter (rho/lambda, null: 0), the likelihood-ratio test of the same null against the OLS model (needs an OLS model fitted to the same data amongresults; 1 df), Jarque-Bera test of the residuals and Moran’s I of the residuals with a permutation p-value (n_permreorderings; needsw). The residuals are those of the model: for the lag modely - rho Wy - Xb, for the error model the filtered ones,(I - lambda W)(y - Xb). A significant Moran’s I means that spatial dependence is left in the model.
A common way to use the OLS tests (Anselin & Rey, 2014): if LM-lag and LM-error are both insignificant, OLS is fine; otherwise fit the model of the more significant one, and if both are significant, decide by the robust versions. This function does not make that decision.
- Parameters:
results (list of spreg models) – As returned by
slm()(spreg.OLS,spreg.ML_Lagandspreg.ML_Errorobjects). Other models are skipped with a warning.w (libpysal.weights.W, optional) – The spatial weights the models were fitted with (the results do not keep them). Without it only the tests that do not need weights are computed (with a warning).
format_pval (bool or callable, default False) – Format the p-values as strings (True: APA style without the
p,"<.001"; a callable receives one p-value); False keeps the numbers.add_stars (bool or callable, default False) – Add a
sigcolumn with significance stars (True:apatools.format.get_stars(); or a callable). They are computed from the unformatted p-values.decimal (int, optional) – Round
statisticto this many decimals (None: no rounding).n_perm (int, default 999) – Number of permutations for the p-value of Moran’s I of the residuals of the ML models (0 leaves that test out).
seed (int, default 13) – Seed of the random generator for the permutations (a local generator).
- Returns:
pandas.DataFrame – One row per test with the columns
test,model(ols,slm,sem; a repeated model gets the suffix_2, …),statistic(chi-square,z, Moran’s I for the permutation test),df(NaN where not applicable),p-value, optionallysig, and an APA-style stringreport. Useformat_pval=False, add_stars=False, decimal=Nonefor the raw numbers.
Notes
With many observations nearly every test becomes significant, and among many tests some are by chance; judge the size of the departure (e.g. Moran’s I, the spatial parameter), not only the p-value. The permutation test of Moran’s I treats the residuals as exchangeable, an approximation for model residuals.
References
Anselin, L. (1988). Spatial Econometrics: Methods and Models. Kluwer. https://doi.org/10.1007/978-94-015-7799-1
Anselin, L., Bera, A. K., Florax, R., & Yoon, M. J. (1996). Simple diagnostic tests for spatial dependence. Regional Science and Urban Economics, 26(1), 77-104. https://doi.org/10.1016/0166-0462(95)02111-6
Anselin, L., & Rey, S. J. (2014). Modern Spatial Econometrics in Practice: A Guide to GeoDa, GeoDaSpace and PySAL. GeoDa Press.
Bera, A. K., & Yoon, M. J. (1993). Specification testing with locally misspecified alternatives. Econometric Theory, 9(4), 649-658. https://doi.org/10.1017/S0266466600008021
Breusch, T. S., & Pagan, A. R. (1979). A simple test for heteroscedasticity and random coefficient variation. Econometrica, 47(5), 1287-1294. https://doi.org/10.2307/1911963
Burridge, P. (1980). On the Cliff-Ord test for spatial correlation. Journal of the Royal Statistical Society Series B: Statistical Methodology, 42(1), 107-108. https://doi.org/10.1111/j.2517-6161.1980.tb01108.x
Cliff, A., & Ord, K. (1972). Testing for spatial autocorrelation among regression residuals. Geographical Analysis, 4(3), 267-284. https://doi.org/10.1111/j.1538-4632.1972.tb00475.x
Jarque, C. M., & Bera, A. K. (1980). Efficient tests for normality, homoscedasticity and serial independence of regression residuals. Economics Letters, 6(3), 255-259. https://doi.org/10.1016/0165-1765(80)90024-5
Koenker, R., & Bassett, G. (1982). Robust tests for heteroscedasticity based on regression quantiles. Econometrica, 50(1), 43-61. https://doi.org/10.2307/1912528
White, H. (1980). A heteroskedasticity-consistent covariance matrix estimator and a direct test for heteroskedasticity. Econometrica, 48(4), 817-838. https://doi.org/10.2307/1912934
Examples
>>> results, metrics = slm(df, "y", ["x1", "x2"], w, model=["ols", "slm"]) >>> slm_tests(results, w, format_pval=True, add_stars=True, decimal=3)
- apatools.slm.slm_effects(results, w, inference='simulation', n_draws=1000, seed=13, conf_level=0.95, traces='auto', n_probes=50, format_pval=False, add_stars=False, decimal=None)[source]¶
Direct, indirect and total effects of the regressors of the spatial lag models fitted with
slm().In the spatial lag model
y = ρWy + Xβ + εthe coefficientβ_kis not the effect of regressork: a change in one location also changes its neighbours throughρWy, and their neighbours in turn. LeSage & Pace (2009) summarize the effect matrix(I - ρW)⁻¹ β_kby three averages: the direct effect (the diagonal: the change of a location caused by a change of its own regressor, including the feedback through its neighbours), the total effect (the row sums: the change of a location caused by a unit change of the regressor in all locations) and the indirect effect, their difference (the spillover). The averages are computed from the traces of the powers ofW(a series inρ), without invertingI - ρW.- Parameters:
results (list) – Fitted models as returned by
slm(). Only the spatial lag models (ML_Lag) have these effects: for OLS there are no spillovers, and in the spatial error model the coefficients already are the direct and total effects. Other models are skipped with a warning.w (libpysal.weights.W) – The spatial weights the models were fitted with (the results do not keep them).
inference ({"simulation", "analytic"}, default "simulation") – How the standard errors, z values, p-values and confidence intervals are obtained.
"simulation": LeSage & Pace’s simulation,n_drawsdraws of(β, ρ)from their estimated joint normal distribution; the standard error is the standard deviation of the effects of the draws and the confidence interval is made of their percentiles (so it can be asymmetric)."analytic": the delta method with the gradient of the trace series (the interval is estimate ± z · se). The two agree whenρis estimated precisely.n_draws (int, default 1000) – Number of draws of the simulation. The standard errors of the indirect and total effects need many more when
ρis large and imprecise (see the notes).seed (int, default 13) – Seed of the generator of the draws (and of the random vectors of
traces="mc").conf_level (float, default 0.95) – Confidence level of the intervals (not a significance level).
traces ({"auto", "exact", "mc"}, default "auto") – How the traces of the powers of
Ware computed:"exact"from the eigenvalues of the dense matrix (costn³),"mc"with Hutchinson’s estimator (n_probesrandom vectors; for largen),"auto"exact for up to 2000 units.n_probes (int, default 50) – Number of random vectors of
traces="mc".format_pval (bool or callable, default False) –
Trueformats the p-values as APA strings (".033","<.001"); a callable formats each p-value.add_stars (bool or callable, default False) –
Trueadds asigcolumn with significance stars (computed from the numeric p-values).decimal (int, optional) – Round
estimate,se,cilandcirto this many decimals (None: no rounding).
- Returns:
pandas.DataFrame – One row per model, regressor and effect: the columns
model("slm"; a repeated model gets the suffix_2, …),variable,effect("Direct","Indirect","Total"),estimate,se,z,p-value,cil,cirand optionallysig.pivotit for a wide table.
Notes
The constant has no effect and is left out. The standard errors use the covariance matrix of
(β, ρ)that spreg reports (the information matrix, including the covariance between the coefficients andρ). The effects are average effects: they do not say how the effect differs between locations. The indirect effect is usually much less precise than the direct one.The delta method (
inference="analytic") treats the effects as linear in the estimates. That holds whenρis estimated precisely; with few units and a largeρthe standard errors of the indirect and total effects can be far too small (in a 64-unit example with ρ = 0.6 the analytic standard error of an indirect effect was 0.44, against 1.48 by simulation with 100,000 draws and 1.43 in R’simpacts), so prefer the simulation then. The direct effect is much less sensitive. The simulated standard errors of the indirect and total effects are noisy in the same situation, because a few draws ofρnear its bound give huge effects: in that example the standard error of the indirect effect was 1.03 with 5000 draws and 1.48 with 100,000 (R’s own simulation behaves the same way). Raisen_drawsand check that the result is stable with anotherseed.References
LeSage, J., & Pace, R. K. (2009). Introduction to spatial econometrics. CRC Press. https://doi.org/10.1201/9781420064254 https://doi.org/10.1201/9781420064254
Elhorst, J. P. (2014). Spatial econometrics: From cross-sectional data to spatial panels. Springer. https://doi.org/10.1007/978-3-642-40340-8 https://doi.org/10.1007/978-3-642-40340-8
Examples
>>> results, metrics = slm(df, "y", ["x1", "x2"], w, model=["ols", "slm"]) >>> slm_effects(results, w, inference="analytic", decimal=3)