如何使用Astropy Kuiper测试

问题描述

我要测试数据集的分布与均值= 0和方差= 1的高斯分布有多接近。

来自文档astropy.stats的{​​{3}}测试具有一个cdf参数:“可调用以评估要测试的发行版的CDF。将使用一个向量来调用所有值一次。默认值是均匀分布”,但我不知道如何使用它来测试正态分布。如果我想要例如正态分布,平均值为0.2,方差为2?

因此,我也使用了kuiper,它也来自天体,并创建了一个随机正态分布。参见下面的示例。

我看到的问题是,这取决于我生成的要比较的数据点的数量。如果我使用100个而不是10000个数据点,则概率(fpp)将会提高到43%。

我想问题是,如何正确执行此操作?另外,我该如何解释D号?

# create data and its cdf
np.random.seed(0)
data = np.random.normal(loc=0.02,scale=1.15,size=50)
data_sort = np.sort(data)
data_cdf = [x/len(data) for x in range(0,len(data))]

# create the normal data with mean 0 and variance 1
xx = np.random.normal(loc=0,scale=1,size=10000)
xx_sort = np.sort(xx)
xx_cdf = [x/len(xx) for x in range(0,len(xx))]
# compute the pdf for a plot
x = np.linspace(-4,4,50)
x_pdf = stats.norm.pdf(x,1)

# we can see it all in a plot
fig,ax = plt.subplots(figsize=(8,6))
plt.hist(xx,bins=20,density=True,stacked=True,histtype='stepfilled',alpha=0.6)
plt.hist(data,histtype='step',lw=3)
plt.plot(x,x_pdf,lw=3,label='G($\mu=0$,$\sigma^2=1$)')
ax2 = ax.twinx()
ax2.plot(xx_sort,xx_cdf,marker='o',ms=8,mec='green',mfc='green',ls='None')
ax2.plot(data_sort,data_cdf,marker='^',mec='orange',mfc='orange',ls='None')

# Kuiper test
D,fpp = kuiper_two(data_sort,xx_sort)
print('#   D number =',round(D,5))
print('#   fpp =',round(fpp,5))
# Which resulted in:
#   D number = 0.211
#   fpp = 0.14802

kuiper_two

解决方法

astropy.stats.kuiper 期望您要测试的分布中的样本作为第一个参数,第二个参数是您要测试的分布的 CDF。

这个变量是一个 Callable 并且期望它自己 (a) 个样本返回累积分布函数下的值。为此,您可以使用 scipy.stat 的 CDF。通过使用 functools.partial,我们可以设置任何参数。

from scipy import stats
from scipy.stats import norm
from astropy.stats import kuiper

from functools import partial
from random import shuffle

np.random.seed(0)
data = np.random.normal(loc=0.02,scale=1.15,size=50)

print(kuiper(data,partial(norm.cdf,loc=0.2,scale=2.0)))

# Output: (0.2252118027033838,0.08776036566607946)

# The data does not have to be sorted,in case you wondered:
shuffle(data)

print(kuiper(data,0.08776036566607946)

the Wikipedia article about this test 的这张图表中,您可以了解柯伊伯统计量 V 的测量值:

[Lucas(CA),CC BY-SA 4.0 <https://creativecommons.org/licenses/by-sa/4.0>,via Wikimedia Commons]3

如果您共享比较分布的参数,则距离更小,并且各个基础 CDF 相同的估计概率增加:

print(kuiper(data,loc=0.02,scale=1.15)))

# Output: (0.14926352419821276,0.68365004302431)

相比之下,函数 astropy.stats.kuiper_two 期望 两个 经验数据样本相互比较。因此,如果您想与具有易处理 CDF 的分布进行比较,最好直接使用 CDF(使用 kuiper),而不是从比较分布中采样(并使用 kuiper_two)。

还有一个挑剔。除了在不是 CDF 的变量名中使用 CDF 之外,这个公式比上面的更易读:

data_cdf = np.linspace(0.0,1.0,len(data),endpoint=False)
xx_cdf = np.linspace(0.0,len(xx),endpoint=False)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...