Scipy中负二项分布的另一种参数化方式

9
在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中,这很容易实现,因为负二项分布可以通过两种参数化方式来定义。
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


你能给我们提供一个概率密度函数或分布函数吗? - Bill Bell
我刚在这里发布了一个与此帖子相关的问题。 - Louiz Zanjroz
2个回答

10
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))

优秀的实现应该得到本地支持。干杯 - Fierce82
2
快速评论:如果convert_params使用与scipy相同的符号,即使用np,那么它会更清晰一些。维基百科页面使用rp。但是,r_wikipedia = n_scipy和p_wikipedia = 1-p_scipy。因此,使用r使我担心它是另一种参数化方式(维基百科使用的方式)。 - Joel

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接