mixle.stats.univariate.discrete.negative_binomial module¶
Create, estimate, enumerate, and sample from a negative binomial distribution.
The parameterization is the number of failures X before r successes, with success probability p:
P(X=x) = Gamma(x+r) / (Gamma(r) Gamma(x+1)) * p**r * (1-p)**x, x = 0, 1, 2, …
The dispersion r has no closed-form MLE; the estimator recovers it by a 1-D
numerical solve of the digamma score equation (with p profiled out), then p
follows in closed form. Pass estimate_r=False to hold r fixed instead.
Reference: Johnson, Kemp & Kotz, Univariate Discrete Distributions (3rd ed., Wiley, 2005).
- class NegativeBinomialDistribution(r, p, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionNegative binomial distribution over non-negative integer counts.
- classmethod compute_capabilities()[source]
- classmethod compute_declaration()[source]
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return per-row negative-binomial sufficient statistics in accumulator order.
The accumulator’s
NegativeBinomialAccumulator.value()returns(count, sum, histogram); the third row stat carries the per-row counts so the declaration’skind="histogram"reducer can fold them into the weighted count histogram the dispersion (r) solve needs.
- static exp_family_sufficient_statistics(x, engine)[source]
Return the NegativeBinomial sufficient statistic
T(x) = (x,)(rfixed).
- static exp_family_natural_parameters(params, engine)[source]
Return the NegativeBinomial natural parameter
eta = log(1 - p)(rfixed).
- static exp_family_log_partition(params, engine)[source]
Return the NegativeBinomial log partition
A = -r * log(p)(rfixed).
- static exp_family_base_measure_from_params(x, params, engine)[source]
Return the NegativeBinomial base measure
log h(x) = lgamma(x+r) - lgamma(r) - log(x!).The base measure carries the binomial-coefficient term and depends on the fixed shape
r; invalid (non-integer / negative) counts are mapped to-inf.
- density(x)[source]
Return the probability density or mass at a single observation.
- log_density(x)[source]
Return the log-density or log-mass at a single observation.
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- static backend_log_density_from_params(vals, log_fact, r, p, engine)[source]
Engine-neutral negative-binomial log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked negative-binomial parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of negative-binomial log densities.
- to_fisher(**kwargs)[source]
Return the NegativeBinomial’s count-family Fisher view.
- cdf(x)[source]
Cumulative distribution function P(X <= x) = I_p(r, floor(x)+1).
- quantile(q)[source]
Inverse CDF F^{-1}(q) (via scipy nbinom).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
NegativeBinomialSampler
- estimator(pseudo_count=None)[source]
Return an estimator for fitting this distribution from data.
- Parameters:
pseudo_count (float | None)
- Return type:
NegativeBinomialEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
NegativeBinomialDataEncoder
- enumerator()[source]
Return an enumerator over the distribution support when available.
- Return type:
NegativeBinomialEnumerator
- class NegativeBinomialEnumerator(dist)[source]
Bases:
DistributionEnumeratorEnumerate the infinite support in descending probability order.
- Parameters:
dist (NegativeBinomialDistribution)
- class NegativeBinomialSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid negative binomial observations.
- Parameters:
dist (NegativeBinomialDistribution)
seed (int | None)
- sample(size=None)[source]
Draw observations.
Combinator samplers (mixture/sequence/…) accept
batched. Withbatched=True(the default) each child stream is drawn in one vectorized call instead of a per-draw Python loop – far faster. Because every child sampler owns an independentRandomState, batching consumes each stream in the same order as the loop, so the draws are identical to the legacy path.batched=Falseforces that legacy per-draw loop as a guaranteed- stable reference. Leaf samplers are already vectorized and ignore the flag.
- class NegativeBinomialAccumulator(name=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorAccumulate weighted count and sum statistics plus the count histogram.
The dispersion
rhas no finite-dimensional sufficient statistic: its MLE needssum_i w_i digamma(x_i + r), which cannot be reduced to count/sum. We therefore accumulate the weighted histogram{x: weight}soNegativeBinomialEstimator.estimate()can solve the score equation forr.- update(x, weight, estimate)[source]
- initialize(x, weight, rng)[source]
- Parameters:
x (int)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
- seq_initialize(x, weights, rng)[source]
- Parameters:
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
- from_value(x)[source]
- key_merge(stats_dict)[source]
Pool this accumulator’s statistics into
stats_dictunder its merge key.The structural default implements the common single-key pattern: store the accumulator under
self.keysthe first time the key is seen, elsecombineinto the one already there. Accumulators with several named keys (e.g. an HMM’s init/trans/state keys) or a non-accumulator stats payload override this. AkeysofNone(the default) is a no-op.
- key_replace(stats_dict)[source]
Replace this accumulator’s statistics from the pooled
stats_dictentry (see key_merge).
- acc_to_encoder()[source]
- Return type:
NegativeBinomialDataEncoder
- class NegativeBinomialAccumulatorFactory(name=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryFactory for NegativeBinomialAccumulator.
- make()[source]
- Return type:
NegativeBinomialAccumulator
- class NegativeBinomialEstimator(r=1.0, pseudo_count=None, suff_stat=None, estimate_r=True, threshold=1.0e-8, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate
randpfor a negative binomial distribution.By default the dispersion
ris recovered by a 1-D solve of the digamma score equation (pprofiled out), thenpfollows in closed form. Passestimate_r=Falseto holdrfixed at the constructor value (the historical geometric/fixed-shape M-step). Therargument is the initial value / fallback whenestimate_r=True.- Parameters:
- accumulator_factory()[source]
- Return type:
NegativeBinomialAccumulatorFactory
- resident_accumulation_supported()[source]
Dispersion estimation needs the full count histogram, not fixed-width resident stats.
- Return type:
- static estimate_dispersion(histogram, r_init, threshold)[source]
Solve the negative-binomial dispersion MLE from a weighted count histogram.
With
pprofiled to its MLEp = r / (r + xbar), the score forrisg(r) = sum_k h(k) [digamma(k + r) - digamma(r)] - N * log(1 + xbar / r),
which is strictly decreasing and crosses zero exactly when the data are over-dispersed (sample variance > mean). Under equi/under-dispersion the MLE runs off to the Poisson limit, so
ris capped at_MAX_NB_SHAPE.