尽管搜索了两天的相关问题,但我尚未真正找到该问题的答案…
在下面的代码中,我生成了n个正态分布的随机变量,然后将其表示为直方图:
import numpy as np
import matplotlib.pyplot as plt
n = 10000 # number of generated random variables
x = np.random.normal(0,1,n) # generate n random variables
# plot this in a non-normalized histogram:
plt.hist(x, bins='auto', normed=False)
# get the arrays containing the bin counts and the bin edges:
histo, bin_edges = np.histogram(x, bins='auto', normed=False)
number_of_bins = len(bin_edges)-1
之后,找到曲线拟合函数及其参数.
它通常使用参数a1和b1进行分布,并使用scale_factor进行缩放,以满足样本未标准化的事实.
它确实非常适合直方图:
import scipy as sp
a1, b1 = sp.stats.norm.fit(x)
scaling_factor = n*(x.max()-x.min())/number_of_bins
plt.plot(x_achse,scaling_factor*sp.stats.norm.pdf(x_achse,a1,b1),'b')
之后,我想使用卡方检验来测试此函数对直方图的拟合程度.
该测试使用这些点的观测值和预期值.为了计算期望值,我首先计算每个bin中间的位置,此信息包含在数组x_middle中.然后,我在每个bin的中间点计算拟合函数的值,从而得到了Expected_value数组:
observed_values = histo
bin_width = bin_edges[1] - bin_edges[0]
# array containing the middle point of each bin:
x_middle = np.linspace( bin_edges[0] + 0.5*bin_width,
bin_edges[0] + (0.5 + number_of_bins)*bin_width,
num = number_of_bins)
expected_values = scaling_factor*sp.stats.norm.pdf(x_middle,a1,b1)
将其插入Scipy的卡方函数中,我得到大约e-5到e-15数量级的p值,这告诉我拟合函数未描述直方图:
print(sp.stats.chisquare(observed_values,expected_values,ddof=2))
但是,事实并非如此,该函数非常适合直方图!
有人知道我在哪里犯错了吗?
非常感谢!!
查尔斯
附注:我将自由度变化数设置为2,因为2个参数a1和b1是根据样本估算的.我尝试使用其他ddof,但结果仍然很差!