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 = 0 when z = 0), for each of T periods (T=1 the cross-section). pair_effects="random" and time_effects=True set pair and period effects on the count part only. Implemented as the separable flow only: pass separable=True. ρ_{z,d}, ρ_{z,o}, β_z are the posterior’s rho_d_zero, rho_o_zero, beta_zero.

Sampling: fit() runs the structured n × n Pólya–Gamma sweep (neighbayes.samplers.zinb._flow_structured), on NumPy or backend="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_zero and rho_o_zero against their priors and the zero part’s R-hat, or use a panel with pair effects, or SARHurdleNegBinFlow.

Parameters:
y

As SARNegBinFlow with separable=True.

X

As SARNegBinFlow with separable=True.

W

As SARNegBinFlow with separable=True.

T=1

As SARNegBinFlow with separable=True.

pair_effects=None

As SARNegBinFlow with separable=True.

time_effects=False

As SARNegBinFlow with separable=True.

col_names=None

As SARNegBinFlow with separable=True.

k=None

As SARNegBinFlow with separable=True.

priors : dict, optional

As SARNegBinFlow with separable=True.

shared_od_covariates=None

As SARNegBinFlow with separable=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 × n zero-part weights. Default: W.

priors=None

Count keys as SARNegBinFlow (incl. alpha_fixed) plus beta_mu_zero, beta_sigma_zero, rho_lower_zero and rho_upper_zero for 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".

fitted_values()

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(μ, α).

residuals()

Return residuals y - fitted_values.

spatial_diagnostics()

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

inference_data

Return the ArviZ DataTree from the most recent fit.

pymc_model

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 over draws posterior draws (all when None).

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_effects keeps 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.

fitted_values()[source]

Return fitted values at posterior mean parameters.

Returns:

Posterior-mean fitted values (on the model’s native scale; fixed-effects-transformed for panel models).

Return type:

np.ndarray

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 through rho_zero and beta_zero, available when the zero part’s design is the flow design (X_zero=None). Other arguments as FlowModel.impacts().

property inference_data[source]

Return the ArviZ DataTree from the most recent fit.

Returns:

The inference data object, or None if the model has not been fit yet.

Return type:

xarray.DataTree or None

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 logp and the prior under the same model definition used by the NUTS path.

Returns:

The model object used by fit(), or None if the instance has not been fit yet.

Return type:

pymc.Model or None

residuals()[source]

Return residuals y - fitted_values.

Returns:

Residual vector y - fitted_values on the same scale as fitted_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 matrix W to 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) and attrs["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 W was supplied.

See also

spatial_diagnostics_decision

Model-selection decision based on the test results.

impacts

Posterior 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 a graphviz.Digraph (with ASCII fallback if graphviz is not installed).

Return type:

str or graphviz.Digraph

summary(var_names=None, **kwargs)[source]

Return posterior summary table.

Parameters:
var_names : list, optional

Variable names to include in the summary.

**kwargs

Additional arguments passed to arviz.summary().

Returns:

Posterior summary statistics.

Return type:

pandas.DataFrame

zero_attribution(draws=200)[source]

Posterior split of each observed zero into structural and sampling.

For y = 0, P(structural | y = 0) = (1−π) / ((1−π) + π·NB(0)). Returned as posterior means and sds over draws draws (all when None).

Returns:

structural_prob, structural_prob_sd, sampling_prob (1 − structural_prob) and zero_indices.

Return type:

dict