负二项式在科学中的替代参数化

spo*_*234 5 python numpy distribution scipy

在科学中,负二项式分布定义为:

nbinom.pmf(k) = choose(k+n-1, n-1) * p**n * (1-p)**k
Run Code Online (Sandbox Code Playgroud)

这是常见的定义,另请参见维基百科:https : //en.wikipedia.org/wiki/Negative_binomial_distribution

但是,存在另一个参数化,其中负二项式由均值mu和色散参数定义。

在R中,这很容易,因为可以通过两个参数来定义负数:

dnbinom(x, size, prob, mu, log = FALSE)
Run Code Online (Sandbox Code Playgroud)

如何在scipy中使用均值/色散参数化?

编辑:

直接从R帮助:

大小= n和概率= p的负二项分布具有密度

?(x + n)/(?(n)x!)p ^ n(1-p)^ x

另一种参数化(通常在生态学中使用)是通过均值mu(请参见上文)和大小,分散参数确定的,其中prob =大小/(size + mu)。在该参数化中,方差为mu + mu ^ 2 / size。

这里也有更详细的描述:

https://zh.wikipedia.org/wiki/Negative_binomial_distribution#Alternative_formulations

ega*_*fni 5

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))
Run Code Online (Sandbox Code Playgroud)

  • 快速评论:如果 `convert_params` 使用与 scipy 相同的表示法(使用 `n` 和 `p`),那么它会更清晰一些。维基百科页面使用“r”和“p”。但是 `r`_wikipedia = `n`_scipy 和 `p`_wikipedia = `1-p`_scipy。因此,“r”的使用让我担心它是其他参数化(维基百科使用的)。 (2认同)

ev-*_*-br 2

您链接的维基百科页面给出了以 mu 和 sigma 表示的 p 和 r 的精确公式,请参阅替代参数化部分中的最后一个项目符号项目,https://en.m.wikipedia.org/wiki/Negative_binomial_distribution#Alternative_formulations