neighbayes.models.SARZINBFlow¶
-
class neighbayes.models.SARZINBFlow(y, X, W, *, pair_effects=
None, time_effects=False, dynamic=False, separable=False, mundlak=None, X_zero=None, W_zero=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]¶ Zero-inflated negative binomial SAR flow model (separable).
\[\begin{split}\eta_{z,t} &= (L_{z,o} \otimes L_{z,d})^{-1} X_{z,t}\beta_z, \qquad z \sim \mathrm{Bernoulli}(\mathrm{logit}^{-1}(\eta_z)), \\ \eta^{\mathrm{cnt}}_t &= (L_o^{\rho} \otimes L_d^{\rho})^{-1} X_t\beta + \tau_t + C, \qquad y \mid z = 1 \sim \mathrm{NB2}(e^{\eta^{\mathrm{cnt}}}, \alpha),\end{split}\]with \(L_{z,k} = I - \rho_{z,k} W_z\), \(L_k^{\rho} = I - \rho_k W\) and per-cell structural zeros (
y = 0whenz = 0), for each ofTperiods (T=1the cross-section).pair_effects="random"andtime_effects=Trueset pair and period effects on the count part only. Implemented as the separable flow only: passseparable=True.ρ_{z,d},ρ_{z,o},β_zare the posterior’srho_d_zero,rho_o_zero,beta_zero.Sampling:
fit()runs the structuredn × nPólya–Gamma sweep (neighbayes.samplers.zinb._flow_structured), on NumPy orbackend="jax";sampler="nuts"fits the same model in PyMC.On sparse flows (active pairs averaging about one count) the zero part is weakly identified in a cross-section: only the shape of the count distribution separates structural from sampling zeros, and NB with a smaller α explains the zeros nearly as well. Check
rho_d_zeroandrho_o_zeroagainst their priors and the zero part’s R-hat, or use a panel with pair effects, orSARHurdleNegBinFlow.- Parameters:¶
- y¶
As
SARNegBinFlowwithseparable=True.- X¶
As
SARNegBinFlowwithseparable=True.- W¶
As
SARNegBinFlowwithseparable=True.- T=
1¶ As
SARNegBinFlowwithseparable=True.- pair_effects=
None¶ As
SARNegBinFlowwithseparable=True.- time_effects=
False¶ As
SARNegBinFlowwithseparable=True.- col_names=
None¶ As
SARNegBinFlowwithseparable=True.- k=
None¶ As
SARNegBinFlowwithseparable=True.- priors : dict, optional¶
As
SARNegBinFlowwithseparable=True.As
SARNegBinFlowwithseparable=True.- X_zero : array-like or pandas.DataFrame, optional¶
Zero-part design, time-first stacked
(n²·T, p). Default:X(then the zero part’s impacts are available).- W_zero : libpysal.graph.Graph or scipy.sparse matrix, optional¶
n × nzero-part weights. Default:W.- priors=
None¶ Count keys as
SARNegBinFlow(incl.alpha_fixed) plusbeta_mu_zero,beta_sigma_zero,rho_lower_zeroandrho_upper_zerofor the zero part.
-
__init__(y, X, W, *, pair_effects=
None, time_effects=False, dynamic=False, separable=False, **kwargs)[source]¶
Methods
__init__(y, X, W, *[, pair_effects, ...])activation_probabilities([draws])Posterior mean of each binary probability
π = logit⁻¹(η_sel).fit([draws, tune, chains, random_seed, ...])Sample the posterior: structured Gibbs (default) or
sampler="nuts".Return fitted values at posterior mean parameters.
impacts([equation, draws, ...])Origin, destination, intraunit and network impacts for one part.
posterior_predictive([n_draws, random_seed])Posterior-predictive counts:
d ~ Bern(π),y = d · NB(μ, α).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.
zero_attribution([draws])Posterior split of each observed zero into structural and sampling.
Attributes
Return the ArviZ DataTree from the most recent fit.
Return the PyMC model object built for the most recent fit.
-
activation_probabilities(draws=
200)[source]¶ Posterior mean of each binary probability
π = logit⁻¹(η_sel).The activation probability for ZINB,
P(y > 0)for a hurdle. Averaged overdrawsposterior draws (all whenNone).
-
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: structured Gibbs (default) or
sampler="nuts".backend="auto"(default) takes JAX when it is installed, else NumPy;"numpy"or"jax"pins one, and NUTS takes"pymc"(its default),"nutpie","numpyro"or"blackjax".store_effectskeeps every draw of the pair effects (default: when they fit in about 500 MB).idata_kwargs={"log_likelihood": True}stores the marginal ZINB pointwise log-likelihood.
-
impacts(equation=
'count', draws=None, return_posterior_samples=False, ci=0.95, mode='auto')[source]¶ Origin, destination, intraunit and network impacts for one part.
equation="count"(default) on the count part’s log-mean throughρ;"zero"on the activation log-odds throughrho_zeroandbeta_zero, available when the zero part’s design is the flow design (X_zero=None). Other arguments asFlowModel.impacts().
-
posterior_predictive(n_draws=
None, random_seed=None)[source]¶ Posterior-predictive counts:
d ~ Bern(π),y = d · NB(μ, α).Returns an array of shape
(n_draws, n_obs).
- 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