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

标签 python arrays random numpy statistics

<分区>

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

相关文章:

arrays - MongoDB - 无法将项目推送到数组内对象内的数组

ruby - 如何在ruby中获取字符串数组的总和

javascript - 将内联 JavaScript 转换为外部文件

php - 来自数据库的随机数据

c++ - random_shuffle 不允许我传递种子

python - 错误 : command 'cc' failed with exit status 1 - MySQLdb installation on MAC

python - 如何在 plotly 和 python 中使用色阶调色板?

python - 我如何洗牌有约束的列表(1 和 2、3 和 4、5 和 6 不相邻)?

python - 过滤混合类型和对象的列

python - Electron 应用程序与打开的其他浏览器之间如何通信?