numpy.random.Generator.hypergeometric#

方法

random.Generator.hypergeometric(ngood, nbad, nsample, size=None)#

从超几何分布中抽取样本。

从具有指定参数的超几何分布中抽取样本,ngood(做好选择的方式),nbad(做坏选择的方式),以及nsample(抽样项目的数量,小于或等于总和 ngood + nbad)。

参数:
ngoodint 或 int 的 array_like

做好选择的方式数量。必须是非负的且小于 10**9。

nbadint 或 int 的 array_like

做坏选择的方式数量。必须是非负的且小于 10**9。

nsampleint 或 int 的 array_like

抽样的项目数量。必须是非负的且小于 ngood + nbad

sizeint 或 int 的元组,可选

输出形状。如果给定的形状是,例如,(m, n, k),那么将抽取 m * n * k 个样本。如果 size 是 None(默认),当 ngoodnbadnsample 都是标量时,将返回单个值。否则,将抽取 np.broadcast(ngood, nbad, nsample).size 个样本。

返回:
outndarray 或标量

从参数化的超几何分布中抽取的样本。每个样本是取自 ngood 个好项目和 nbad 个坏项目的集合中的大小为 nsample 的随机子集中好项目的数量。

另请参阅

multivariate_hypergeometric

从多元超几何分布中抽取样本。

scipy.stats.hypergeom

概率密度函数、分布或累积密度函数等。

备注

超几何分布的概率质量函数(PMF)为

\[P(x) = \frac{\binom{g}{x}\binom{b}{n-x}}{\binom{g+b}{n}},\]

其中 \(0 \le x \le n\)\(n-b \le x \le g\)

对于 P(x),即在抽取的样本中获得 x 个好结果的概率,g = ngood,b = nbad,n = nsample

考虑一个带有黑白大理石的瓮,其中 ngood 个是黑色的,nbad 个是白色的。如果你不放回地抽取 nsample 个球,那么超几何分布描述了抽样样本中黑色球的分布。

请注意,这个分布与二项分布非常相似,只是在这里,样本是无放回抽取的,而在二项分布情况下,样本是有放回抽取的(或样本空间是无限的)。随着样本空间的增大,这个分布接近二项分布。

ngoodnbad 的参数都必须小于 10**9。对于极其大的参数,用于计算样本的算法 [4] 会因为浮点计算中的精度损失而失效。对于这些非常大的值,如果 nsample 也不大,则可以用二项分布 binomial(n=nsample, p=ngood/(ngood + nbad)) 来近似。

参考

[1]

Lentner, Marvin,“Elementary Applied Statistics”,Bogden and Quigley, 1972。

[2]

Weisstein, Eric W. “Hypergeometric Distribution.” From MathWorld–A Wolfram Web Resource. https://mathworld.net.cn/HypergeometricDistribution.html

[3]

Wikipedia, “Hypergeometric distribution”, https://en.wikipedia.org/wiki/Hypergeometric_distribution

[4]

Stadlober, Ernst, “The ratio of uniforms approach for generating discrete random variates”, Journal of Computational and Applied Mathematics, 31, pp. 181-189 (1990)。

示例

从分布中绘制样本

>>> rng = np.random.default_rng()
>>> ngood, nbad, nsamp = 100, 2, 10
# number of good, number of bad, and number of samples
>>> s = rng.hypergeometric(ngood, nbad, nsamp, 1000)
>>> from matplotlib.pyplot import hist
>>> hist(s)
#   note that it is very unlikely to grab both bad items

假设你有一个瓮,里面有 15 个白球和 15 个黑球。如果你随机抽取 15 个球,其中 12 个或更多是同一种颜色的可能性有多大?

>>> s = rng.hypergeometric(15, 15, 15, 100000)
>>> sum(s>=12)/100000. + sum(s<=3)/100000.
#   answer = 0.003 ... pretty unlikely!