numpy.random.Generator.chisquare#

method

random.Generator.chisquare(df, size=None)#

从卡方分布中抽取样本.

df 个独立的随机变量(每个变量都具有标准正态分布,均值为 0,方差为 1)的平方和时,得到的分布为卡方分布(请参阅注释).此分布通常用于假设检验.

参数:
dffloat 或 float 的类数组

自由度数,必须 > 0.

sizeint 或 int 元组,可选

输出形状.如果给定的形状是,例如 (m, n, k) ,则抽取 m * n * k 个样本.如果 size 为 None (默认),则如果 df 是标量,则返回单个值.否则,抽取 np.array(df).size 个样本.

返回:
outndarray 或标量

从参数化的卡方分布中抽取的样本.

Raises:
ValueError

df <= 0 或给出不适当的 size (例如 size=-1 ) 时.

注释

通过将 df 个独立的,标准正态分布的随机变量的平方和得到的变量:

\[Q = \sum_{i=1}^{\mathtt{df}} X^2_i\]

是卡方分布,表示为

\[Q \sim \chi^2_k.\]

卡方分布的概率密度函数为

\[p(x) = \frac{(1/2)^{k/2}}{\Gamma(k/2)} x^{k/2 - 1} e^{-x/2},\]

其中 \(\Gamma\) 是伽马函数,

\[\Gamma(x) = \int_0^{-\infty} t^{x - 1} e^{-t} dt.\]

参考文献

示例

>>> rng = np.random.default_rng()
>>> rng.chisquare(2,4)
array([ 1.89920014,  9.00867716,  3.13710533,  5.62318272]) # random

具有 20 个自由度的卡方随机变量的分布如下所示:

>>> import matplotlib.pyplot as plt
>>> import scipy.stats as stats
>>> s = rng.chisquare(20, 10000)
>>> count, bins, _ = plt.hist(s, 30, density=True)
>>> x = np.linspace(0, 60, 1000)
>>> plt.plot(x, stats.chi2.pdf(x, df=20))
>>> plt.xlim([0, 60])
>>> plt.show()
../../../_images/numpy-random-Generator-chisquare-1.png