<分区>
在 uni-testing 中,我需要检查数组值的分布是否均匀。例如:
在数组中 = [1, 0, 1, 0, 1, 1, 0, 0]
值分布均匀。由于有四个“1”和四个“0”
对于更大长度的数组,分布更“均匀”
如何证明正在测试的数组具有均匀分布?
注意:数组是使用 random.randint(min,max,len)
创建的,来自 numpy.random
<分区>
在 uni-testing 中,我需要检查数组值的分布是否均匀。例如:
在数组中 = [1, 0, 1, 0, 1, 1, 0, 0]
值分布均匀。由于有四个“1”和四个“0”
对于更大长度的数组,分布更“均匀”
如何证明正在测试的数组具有均匀分布?
注意:数组是使用 random.randint(min,max,len)
创建的,来自 numpy.random
最佳答案
您可以对连续和 离散分布使用 Kolmogorove-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
与均匀分布没有区别。 0.1033 的 p 值通常被认为不足以拒绝原假设。通常 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)
第一个值是chisquare,第二个值是P值。
关于python - 如何检查python中变量的分布?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22392562/