如何在python中检查变量的分布?

edu*_*fan 7 python arrays random statistics numpy

在单一测试中,我需要检查数组值的分布是否一致.例如:

在数组中= [1, 0, 1, 0, 1, 1, 0, 0] 存在均匀的值分布.由于有四个"1"和四个"0"

对于较大长度的阵列,分布更"均匀"

如何证明正在测试的阵列具有均匀分布?

注意:数组是用random.randint(min,max,len)from 创建的numpy.random

CT *_*Zhu 7

您可以使用Kolmogorove-Smirnov Test进行连续离散分布.该函数随scipy.stats.kstest http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kstest.html#scipy.stats.kstest一起提供.

In [12]:

import scipy.stats as ss
import numpy as np
In [14]:

A=np.random.randint(0,10,100)
In [16]:

ss.kstest(A, ss.randint.cdf, args=(0,10))
#args is a tuple containing the extra parameter required by ss.randint.cdf, in this case, lower bound and upper bound
Out[16]:
(0.12, 0.10331653831438881)
#This a tuple of two values; KS test statistic, either D, D+ or D-. and p-value
Run Code Online (Sandbox Code Playgroud)

这里得到的P值是0.1033,因此我们得出结论,该阵列A与均匀分布没有显着差异.考虑P值的方法是,它假设零假设为真,测量使得检验统计量与观察到的极值(这里:元组中的第一个数字)极端的概率.在KS测试中,我们实际上具有与A均匀分布没有区别的零假设.p值0.1033通常不被认为足以拒绝零假设.通常P值必须小于0.05或0.01才能拒绝空值.如果此示例中的此p值小于0.05,那么我们将说明A与均匀分布明显不同.

另一种使用方法scipy.stats.chisquare():

In [17]:

import scipy.stats as ss
import numpy as np
In [18]:

A=np.random.randint(0, 10, 100)
In [19]:

FRQ=(A==np.arange(10)[...,np.newaxis]).sum(axis=1)*1./A.size #generate the expect frequecy table.
In [20]:

ss.chisquare(FRQ) #If not specified, the default expected frequency is uniform across categories.
Out[20]:
(0.084000000000000019, 0.99999998822800984)
Run Code Online (Sandbox Code Playgroud)

第一个值是chisquare,第二个值是P值.

  • 甚至在链接到它的scipy页面上写着:"KS测试仅对连续分发有效." (2认同)