spreg
raw JSON → 1.9.0 verified Sat May 09 auth: no python
PySAL Spatial Econometric Regression in Python. Provides spatial regression models (OLS, ML, GM, Panel) and diagnostics. Current version: 1.9.0. Released approximately every 3-6 months.
pip install spreg Common errors
error ImportError: cannot import name 'OLS' from 'spreg.ols' ↓
cause Incorrect import path for OLS class.
fix
Use: from spreg import OLS
error ValueError: The weights matrix must be a W object. ↓
cause Passed a raw scipy sparse matrix or numpy array instead of a libpysal W object.
fix
Convert your weights using libpysal.weights.W(weights_matrix) or use libpysal.weights to read shapefiles.
error TypeError: regimes must be a pandas Categorical or a list of strings with length equal to the number of observations. ↓
cause Regimes argument is not properly formatted.
fix
Ensure regimes is either a pandas Categorical or a list of strings of length n. Example: regimes = pd.Categorical(['a','b']*50)
Warnings
breaking In v1.8+, spreg automatically converts sparse and full weights matrices to libpysal W objects. If you relied on passing raw scipy sparse matrices, they will be converted, which may change behavior. ↓
fix Ensure your weights are passed as libpysal W objects or accept automatic conversion. If you need the old behavior, convert to W yourself.
deprecated check_spat_diag was deprecated in v1.6.1 and removed in later versions. Use spat_diag=True in model constructors instead. ↓
fix Replace check_spat_diag(y, x, w) with OLS(y, x, w, spat_diag=True) or equivalent.
gotcha When using regime models (e.g., OLS_Regimes), the regimes argument must be a pandas Categorical or a list of strings with length equal to number of observations. Mixing types can cause silent errors. ↓
fix Convert regimes to a pandas Categorical: regimes = pd.Categorical(regimes). Then pass to the model.
Imports
- OLS wrong
from spreg.ols import OLScorrectfrom spreg import OLS - GM_Lag wrong
from spreg.GM import GM_Lagcorrectfrom spreg import GM_Lag - ML_Error wrong
from spreg.ML import ML_Errorcorrectfrom spreg import ML_Error - spsearch
from spreg import spsearch
Quickstart
import numpy as np
import libpysal
from spreg import OLS
# Generate random data
np.random.seed(123)
n = 100
x = np.random.randn(n, 2)
y = 1 + 2*x[:,0] + 3*x[:,1] + np.random.randn(n)*0.5
# Create spatial weights (Queen contiguity from random points)
pts = np.random.rand(n, 2)
w = libpysal.weights.DistanceBand.from_array(pts, threshold=0.5, binary=True)
w.transform = 'r'
# Fit OLS
m1 = OLS(y, x, w=w, spat_diag=True)
print(m1.summary)