numpy.random.Generator.chisquare#

method

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

从卡方分布中抽取样本.

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

参数:
dffloat 或 floats 的类数组对象

自由度数,必须 > 0.

sizeint 或 int 的元组,可选.

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

返回:
outndarray 或标量

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

提出:
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.\]

参考

[1]

NIST “Engineering Statistics Handbook” https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm

示例

>>> 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