numpy.random.Generator.hypergeometric#
方法
- random.Generator.hypergeometric(ngood, nbad, nsample, size=None)#
從超幾何分佈中抽取樣本。
樣本是從具有指定參數的超幾何分佈中抽取的,ngood (做出良好選擇的方式)、nbad (做出不良選擇的方式) 和 nsample (抽樣的項目數量,小於或等於總和
ngood + nbad
)。- 參數:
- ngoodint 或 int 的陣列型別
做出良好選擇的方式的數量。必須為非負數且小於 10**9。
- nbadint 或 int 的陣列型別
做出不良選擇的方式的數量。必須為非負數且小於 10**9。
- nsampleint 或 int 的陣列型別
抽樣的項目數量。必須為非負數且小於
ngood + nbad
。- sizeint 或 int 的元組,選用
輸出形狀。如果給定的形狀為,例如,
(m, n, k)
,則會抽取m * n * k
個樣本。如果 size 為None
(預設值),如果 ngood、nbad 和 nsample 都是純量,則會傳回單一值。否則,會抽取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 個彈珠,則超幾何分佈描述了抽取樣本中黑色彈珠的分佈。
請注意,此分佈與二項式分佈非常相似,不同之處在於,在這種情況下,樣本是不放回地抽取的,而在二項式情況下,樣本是放回地抽取的 (或樣本空間是無限的)。隨著樣本空間變得很大,此分佈會趨近於二項式分佈。
引數 ngood 和 nbad 各自都必須小於 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.wolfram.com/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!