在 scipy 中,负二项分布定义为:
nbinom.pmf(k) = choose(k+n-1, n-1) * p**n * (1-p)**k
这是常见的定义,另见维基百科: https://en.wikipedia.org/wiki/Negative_binomial_distribution
但是,存在不同的参数化,其中负二项式由均值 mu
和色散参数定义。
在 R 中这很容易,因为 negbin 可以通过两个参数化定义:
dnbinom(x, size, prob, mu, log = FALSE)
如何在 scipy 中使用均值/离散参数化?
编辑:
直接来自 R 帮助:
大小为 n 且概率为 p 的负二项分布具有密度
Γ(x+n)/(Γ(n) x!) p^n (1-p)^x
另一种参数化(常用于生态学)是平均 mu(见上文)和大小,分散参数,其中 prob = size/(size+mu)。此参数化中的方差为 mu + mu^2/size。
这里也有更详细的描述:
https://en.wikipedia.org/wiki/Negative_binomial_distribution#Alternative_formulations
最佳答案
from scipy.stats import nbinom
def convert_params(mu, theta):
"""
Convert mean/dispersion parameterization of a negative binomial to the ones scipy supports
See https://en.wikipedia.org/wiki/Negative_binomial_distribution#Alternative_formulations
"""
r = theta
var = mu + 1 / r * mu ** 2
p = (var - mu) / var
return r, 1 - p
def pmf(counts, mu, theta):
"""
>>> import numpy as np
>>> from scipy.stats import poisson
>>> np.isclose(pmf(10, 10, 10000), poisson.pmf(10, 10), atol=1e-3)
True
"""
return nbinom.pmf(counts, *convert_params(mu, theta))
def logpmf(counts, mu, theta):
return nbinom.logpmf(counts, *convert_params(mu, theta))
def cdf(counts, mu, theta):
return nbinom.cdf(counts, *convert_params(mu, theta))
def sf(counts, mu, theta):
return nbinom.sf(counts, *convert_params(mu, theta))
关于python - scipy中负二项式的替代参数化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40846992/