neighbayes.models.SARHurdleNegBinFlow¶
-
class neighbayes.models.SARHurdleNegBinFlow(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]¶ Reduced-form SAR hurdle negative binomial flow model (separable).
\[\eta_{z,t} = (L_{z,o} \otimes L_{z,d})^{-1} X_{z,t}\beta_z + \tau_{z,t} + C_z, \qquad \eta^{\mathrm{c}}_t = (L_o^{\rho} \otimes L_d^{\rho})^{-1} X_t\beta + \tau_t + C,\]P(y > 0) = logit⁻¹(η_z)andy | y > 0a zero-truncated NB2 with log-meanη^c, for each ofTperiods (T=1the cross-section). Implemented as the separable flow only: passseparable=True.pair_effects="random"andtime_effects=Trueset pair and period effects on both parts: in the zero part a pair effect absorbs the pair’s baseline chance of any flow, soβ_zis identified from the weeks in which a pair switches between zero and positive; in the count part it absorbs the pair’s usual volume. The parts share no parameters.ρ_{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.hurdle._flow_structured), on NumPy orbackend="jax";sampler="nuts"fits the same model in PyMC.- 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.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 flow impacts are available).- W_zero : libpysal.graph.Graph or scipy.sparse matrix, optional¶
n × nzero-part weights. Default:W.- priors : dict, optional¶
See
FlowPanelHurdlePriors; the count priors are centred on the positive flows.
-
__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.
positive_mean([draws])Posterior mean of
E[y | y > 0] = μ / (1 − p₀)for every cell.posterior_predictive([n_draws, random_seed])Posterior-predictive counts:
d ~ Bern(π),y | d = 1 ~ tNB(μ, α).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.
-
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 both halves’ pair effects (default: when they fit in about 500 MB).idata_kwargs= {"log_likelihood": True}stores the pointwise hurdle 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 zero part’s log-odds of any flow 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 = 1 ~ tNB(μ, α).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