微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用最佳拟合生成卡方

如何解决使用最佳拟合生成卡方

我正在生成一些假数据集的 1000 次迭代,并使用 curve_fit 找到最佳拟合模型(具有特定均值、偏移量、放大器...的高斯)而不是猜测我的拟合模型的平均值,而是使用 curve_fit 所以我可以有更好的 chi2 值。 但现在输出很奇怪,甚至数据和模型也不一致。

This is the scatter plots of my data and fitting model

此外,如果我绘制 chi2 值的直方图,

The chi2_fit values don't spread out like expected

true_mean = 5 #Assume that we kNow the perfect fitting model is gaussian 
#with mean value 5. And use try_mean with different mean values to see how 
#does the chi2 behave
true_amp = 100
true_wid = 2
true_offset =10
x_values =  np.array([i for i in np.arange(0,10,0.4)])
exact_y_values = np.array([true_offset + true_amP*
                               np.exp(-((i-true_mean)/true_wid)**2)
                               for i in x_values])
    

    
try_mean = 4.8   # Notice the data is generated centered at 5;
# by comparing it to a 4.8 we expect disagreement.
try_amp = 100
try_wid = 2  
try_offset =10
try_these_y_values = np.array([try_offset + try_amP*
                                   np.exp(-((i-try_mean)/try_wid)**2)
                                   for i in x_values])

def func (x_values,offset,amp,mean,wid):
    return (offset + amP*np.exp(-((i-mean)/wid)**2))
#Excercise 2
#def func (x_values,wid): return (offset + amP*np.exp(-((i-mean)/wid)**2))

chi2_fit=np.zeros(1000)
for i in range (1000):

    fake_exp_y_values = np.array([np.random.poisson(y)
                                      for y in exact_y_values])
    p01=[true_offset,true_amp,true_mean,true_wid]
    [popt,pcov]=opt.curve_fit(func,x_values,fake_exp_y_values,p01)
    y_values_fit=np.array([popt[0]+ popt[1]
                           *np.exp(
                               -((x_values-popt[2])/popt[3])**2)])
    residuals=fake_exp_y_values-y_values_fit
    y_err=np.clip(np.sqrt(fake_exp_y_values),1,9999)
    pulls=residuals/y_err
    chi2_fit[i]=np.sum(pulls**2)
    
plt.hist(chi2_fit)
plt.scatter(x_values,exact_y_values,color='k',ls='--',label='true model')
plt.scatter(x_values,y_values_fit,color='r')
plt.errorbar(x_values,yerr=y_err)

应该修改什么才能有合理的情节。

something like this

And the histogram should be like this

解决方法

问题在于您的函数定义和 i 的用法:

def func (x_values,offset,amp,mean,wid):
    return (offset + amp*np.exp(-((i-mean)/wid)**2))

for i in range (1000):
    ...
    [popt,pcov]=opt.curve_fit(func,x_values,fake_exp_y_values,p01)
    ...

修正版:

def func (x_values,wid):
    return (offset + amp*np.exp(-((x_values-mean)/wid)**2))

也请下次发帖MRE。这个不是最小的,也不是可重复的(我必须在最后添加 y_values_fit = y_values_fit.flatten() 才能使其工作)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。