neighbayes.models.NegBinFlow¶
-
class neighbayes.models.NegBinFlow(y, X, W, *, pair_effects=
None, time_effects=False, dynamic=False, separable=False, mundlak=None, T=1, col_names=None, k=None, priors=None, logdet_method=None, nonnegative_dependence=True, robust=False, shared_od_covariates=None, logdet_decomp='auto')[source]¶ Aspatial negative binomial (NB2) origin-destination gravity model.
log μ_t = X_t β.fit()runs Pólya–Gamma Gibbs on NumPy (with a panel’s pair effects integrated out);sampler="nuts"runs PyMC.A panel (
T) takespair_effects="random"andtime_effects=True. The within transform of the Gaussian panels does not carry to a log link, so the effects are parameters,η_t = X_tβ + C + τ_t: pair effects (one per origin–destination pair), drawn jointly with β and held as a pair index rather thann²dummy columns.Pair effects are partially pooled:
C_ij ~ N(μ, σ²)with σ learned (half-t(3,pair_effect_sd_scale) prior, default scale 1). A pair seen in few periods is shrunk toward the common mean in proportion to how little its data say. Pair effects absorb nothing: the intercept and time-invariant columns (intra indicator, log distance) stay in the design and anchor the level.mundlak=Trueadds the pair means of the time-varying columns, absorbing a correlation between the pair effects andX.Period effects join the coefficient block under a fixed prior (
time_effect_mu, default 0 beside pair effects andlog mean ywithout;time_effect_sigma, default 2.5):T − 1of them (first period the baseline) beside pair effects, allTwithout (the intercept is then absorbed).alpha_fixedholds α at a value; a large one (10-20 times the typical mean count) makes the model an essentially Poisson one that keeps the exact Pólya–Gamma sampler (seeneighbayes.models._base._nb).fit(store_effects=None)keeps every draw of the pair effects when they fit in about 500 MB and otherwise only their posterior mean and sd (idata["pair_effect_summary"]);posterior_predictiveneeds the draws. Effects run on the NumPy Gibbs backend.-
__init__(y, X, W, *, pair_effects=
None, time_effects=False, dynamic=False, separable=False, **kwargs)[source]¶
Methods
__init__(y, X, W, *[, pair_effects, ...])fit([draws, tune, chains, random_seed, ...])Sample the posterior: Gibbs (default, ρ fixed at 0, on NumPy) or
"nuts"(backendas inSARNegBinFlow.fit()).Return fitted values at posterior mean parameters.
impacts([draws, return_posterior_samples, ...])Summarize posterior origin/destination/intra/network/total effects.
posterior_predictive([n_draws, random_seed])Draw posterior-predictive flow counts, time-first stacked.
Return residuals
y - fitted_values.Run Bayesian LM specification tests and return a summary table.
spatial_diagnostics_decision([alpha, format])Return a model-selection decision from Bayesian LM test results.
summary([var_names])Return posterior summary table.
Attributes
Return the ArviZ DataTree from the most recent fit.
Return the PyMC model object built for the most recent fit.
-
fit(draws=
2000, tune=1000, chains=4, random_seed=None, *, sampler='gibbs', backend=None, progressbar=True, n_jobs=-1, idata_kwargs=None, store_effects=None, **sample_kwargs)[source]¶ Sample the posterior: Gibbs (default, ρ fixed at 0, on NumPy) or
"nuts"(backendas inSARNegBinFlow.fit()).
-
impacts(draws=
None, return_posterior_samples=False, ci=0.95, mode='auto')[source]¶ Summarize posterior origin/destination/intra/network/total effects.
Wraps
_compute_impacts_posterior()to produce a tidy DataFrame indexed by predictor with posterior means, credible-interval bounds, and Bayesian p-values for each effect type (origin, destination, intra, network, total). Following Thomas-Agnan & LeSage (2014, §83.5.2), when destination and origin design blocks differ the decomposition is reported separately for shocks applied to each side.- Parameters:¶
- draws : int, optional¶
Maximum number of posterior draws to use. Defaults to all.
- return_posterior_samples : bool, default False¶
If True, also return the underlying posterior-draw arrays.
- ci : float, default 0.95¶
Credible-interval coverage.
- mode : {"auto", "combined", "separate"}, default "auto"¶
Controls whether destination- and origin-side effects are summed or reported separately.
"auto"collapses to combined when the destination and origin design blocks are identical (self._shared_od_covariates) and reports both sides otherwise."combined"always sums;"separate"always reports both.
- Returns:¶
Long-format summary indexed by
(predictor, side, effect)wheresideis one of"combined","dest","orig".- Return type:¶
pandas.DataFrame, or (DataFrame, dict)
-
posterior_predictive(n_draws=
None, random_seed=None)[source]¶ Draw posterior-predictive flow counts, time-first stacked.
Returns an array of shape
(n_draws, n² · T).
- property pymc_model[source]¶
Return the PyMC model object built for the most recent fit.
For a Gibbs-fitted cross-section the PyMC model is not constructed during sampling; it is built lazily on first access so that downstream consumers (e.g. bridge sampling for marginal likelihoods) can evaluate
logpand the prior under the same model definition used by the NUTS path.
- residuals()[source]¶
Return residuals
y - fitted_values.- Returns:¶
Residual vector
y - fitted_valueson the same scale asfitted_values().- Return type:¶
np.ndarray
- spatial_diagnostics()[source]¶
Run Bayesian LM specification tests and return a summary table.
Looks up the diagnostic suite registered for this model class and calls each test function on this fitted model, collecting the results into a tidy DataFrame. The set of tests depends on the model type — for example, an OLS model runs LM-Lag, LM-Error, LM-SDM-Joint, and LM-SLX-Error-Joint, while an SAR model runs LM-Error, LM-WX, and Robust-LM-WX. Panel models run the
Panel--prefixed analogues (e.g. Panel-LM-Lag).Requires the model to have been fit (
.fit()called) and a spatial weights matrixWto have been supplied at construction time.- Returns:¶
DataFrame indexed by test name with columns:
Column
Description
statistic
Posterior mean of the LM statistic
median
Posterior median of the LM statistic
df
Degrees of freedom for the \(\chi^2\) reference
p_value
Bayesian p-value:
1 - chi2.cdf(mean, df)ci_lower
Lower bound of 95% credible interval (2.5%)
ci_upper
Upper bound of 95% credible interval (97.5%)
The DataFrame has
attrs["model_type"](class name) andattrs["n_draws"](total posterior draws) metadata.- Return type:¶
pandas.DataFrame
- Raises:¶
RuntimeError – If the model has not been fit yet.
ValueError – If no spatial weights matrix
Wwas supplied.
See also
spatial_diagnostics_decisionModel-selection decision based on the test results.
impactsPosterior inference for direct/indirect/total impacts.
Examples
>>> ols = OLS(formula="price ~ income + crime", data=df, W=w) >>> ols.fit() >>> ols.spatial_diagnostics() statistic median df p_value ci_lower ci_upper LM-Lag 3.21 2.98 1 0.073 0.12 8.54 LM-Error 5.67 5.34 1 0.017 0.34 12.10 LM-SDM-Joint 7.89 7.12 4 0.096 1.23 18.32 LM-SLX-Error-Joint 6.45 5.98 4 0.168 0.89 15.67
-
spatial_diagnostics_decision(alpha=
0.05, format='graphviz')[source]¶ Return a model-selection decision from Bayesian LM test results.
Walks the flow decision tree using Bayesian p-values from
spatial_diagnostics()and recommends either the OLS flow baseline (no spatial dependence detected) or the SAR flow model (at least one direction is significant).- Parameters:¶
- alpha : float, default 0.05¶
Significance level for the Bayesian p-values.
- format : {"graphviz", "ascii", "model"}, default "graphviz"¶
Output format.
"model"returns the recommended model name string."ascii"returns an indented box-drawing tree."graphviz"returns agraphviz.Digraph(with ASCII fallback if graphviz is not installed).
- Return type:¶
str or graphviz.Digraph
-
__init__(y, X, W, *, pair_effects=