如何在Python中检查变量的分布?
在单元测试中,我需要检查一个数组的值分布是否均匀。举个例子:
在这个数组中 = [1, 0, 1, 0, 1, 1, 0, 0]
,值的分布是均匀的。因为这里有四个“1”和四个“0”。
对于更长的数组,分布会更“均匀”。
我该如何证明正在测试的数组具有均匀分布呢?
注意:这个数组是通过 random.randint(min,max,len)
创建的,来自 numpy.random
。
1 个回答
8
你可以使用Kolmogorov-Smirnov检验来分析连续和离散的分布。这个功能可以通过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
在这里,得到的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)
第一个值是卡方值,第二个值是P值。