我使用以下代码生成了两个发行版:
rand_num1 = 2*np.random.randn(10000) + 1
rand_num2 = 2*np.random.randn(10000) + 1
stats.ks_2samp(rand_num1, rand_num2)
我的问题是为什么这两个发行版都没有根据kstest和chisquare测试进行测试。
当我在2个发行版上运行kstest时,我得到了:
Ks_2sampResult(statistic=0.019899999999999973, pvalue=0.037606196570126725)
这意味着这两个分布在统计上是不同的。我使用以下代码绘制两个发行版的CDF:
count1, bins = np.histogram(rand_num1, bins = 100)
count2, _ = np.histogram(rand_num2, bins = bins)
plt.plot(np.cumsum(count1), 'g-')
plt.plot(np.cumsum(count2), 'b.')
This is how the CDF of two distributions looks。
当我运行chisquare测试时,我得到以下内容:
stats.chisquare(count1, count2) # Gives an nan output
stats.chisquare(count1+1, count2+1) # Outputs "Power_divergenceResult(statistic=180.59294741316694, pvalue=1.0484033143507713e-06)"
我有以下3个问题:
答案 0 :(得分:0)
CDF,在我看来,并不是一个好看的曲线。它会隐藏很多细节,因为它是一个不可或缺的事实。基本上,一些低于分布的异常值将由另一个异常值补偿。
好的,我们来看看K-S结果的分布情况。我已经运行了100次测试并绘制了统计数据与p值,并且正如预期的那样,在某些情况下会有(小p,大数据)点。
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
np.random.seed(12345)
x = []
y = []
for k in range(0, 100):
rand_num1 = 2.0*np.random.randn(10000) + 1.0
rand_num2 = 2.0*np.random.randn(10000) + 1.0
q = stats.ks_2samp(rand_num1, rand_num2)
x.append(q.statistic)
y.append(q.pvalue)
plt.scatter(x, y, alpha=0.1)
plt.show()
图形
更新
实际上,如果我运行测试并看到我的指标的测试与控制分布,如我的情节所示,那么我希望能够说它们是相同的 - 这些测试周围是否有任何统计数据或参数可以告诉我这些分布有多近?
当然,他们是 - 你正在使用其中一种测试! K-S是最普遍但最弱的测试。正如您将使用的任何测试一样,总有一些情况下测试会说这些样本来自不同的分布,即使您故意从同一例程中采样它们。这只是事物的自然,
您会有信心地获得yes
或no
,但不会更多。看
再次在图表中插图。
关于你使用chi2的练习我从一开始就非常怀疑使用chi2来完成这项任务。对我来说,考虑到决定两个样本的问题,要使用的测试应该是明确对称的。 K-S还可以,但是看看chi2的定义,它不是对称的。简单修改 你的代码
count1, bins = np.histogram(rand_num1, bins = 40, range=(-2.,2.))
count2, _ = np.histogram(rand_num2, bins = bins, range=(-2.,2.))
q = stats.chisquare(count2, count1)
print(q)
q = stats.chisquare(count1, count2)
print(q)
产生类似
的东西Power_divergenceResult(statistic=87.645335824746468, pvalue=1.3298580128472864e-05)
Power_divergenceResult(statistic=77.582358201839526, pvalue=0.00023275129585256563)
基本上,这意味着如果你运行(1,2)
,测试可能会通过但是如果你运行(2,1)
则会失败,这是不好的,恕我直言。一旦你测试了已知分布曲线的预期值,Chi2就可以了 - 这里测试不对称是有意义的
我建议尝试Anderson-Darling测试
q = stats.anderson_ksamp([np.sort(rand_num1), np.sort(rand_num2)])
print(q)
但请记住,它与K-S相同,即使它们是从相同的基础分布中抽取出来的,一些样本也可能无法通过测试 - 这只是野兽的性质。
更新:一些阅读材料
https://stats.stackexchange.com/questions/187016/scipy-chisquare-applied-on-continuous-data