numpy.random.Generator.gamma#
方法
- random.Generator.gamma(shape, scale=1.0, size=None)#
從 Gamma 分佈中抽取樣本。
樣本是從具有指定參數的 Gamma 分佈中抽取的,
shape
(有時指定為 “k”) 和 scale (有時指定為 “theta”),其中兩個參數都 > 0。- 參數:
- shapefloat 或 float 的類陣列 (array_like)
Gamma 分佈的形狀。必須是非負數。
- scalefloat 或 float 的類陣列 (array_like),可選
Gamma 分佈的尺度。必須是非負數。預設值等於 1。
- sizeint 或 int 的元組,可選
輸出形狀。如果給定的形狀是,例如,
(m, n, k)
,則會抽取m * n * k
個樣本。如果 size 是None
(預設值),如果shape
和scale
都是純量,則會傳回單一值。否則,會抽取np.broadcast(shape, scale).size
個樣本。
- 返回:
- outndarray 或 純量
從參數化的 Gamma 分佈中抽取的樣本。
參見
scipy.stats.gamma
機率密度函數、分佈或累積密度函數等。
註解
Gamma 分佈的機率密度為
\[p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},\]其中 \(k\) 是形狀,\(\theta\) 是尺度,而 \(\Gamma\) 是 Gamma 函數。
Gamma 分佈常用於為電子元件的故障時間建模,並且自然地出現在泊松分佈事件之間的等待時間相關的過程中。
參考文獻
[1]Weisstein, Eric W. “Gamma Distribution.” From MathWorld–A Wolfram Web Resource. https://mathworld.wolfram.com/GammaDistribution.html
[2]Wikipedia, “Gamma distribution”, https://en.wikipedia.org/wiki/Gamma_distribution
範例
從分佈中抽取樣本
>>> shape, scale = 2., 2. # mean=4, std=2*sqrt(2) >>> rng = np.random.default_rng() >>> s = rng.gamma(shape, scale, 1000)
顯示樣本的直方圖,以及機率密度函數
>>> import matplotlib.pyplot as plt >>> import scipy.special as sps >>> count, bins, _ = plt.hist(s, 50, density=True) >>> y = bins**(shape-1)*(np.exp(-bins/scale) / ... (sps.gamma(shape)*scale**shape)) >>> plt.plot(bins, y, linewidth=2, color='r') >>> plt.show()