【问题标题】:Generating chi_squared using best fit使用最佳拟合生成 chi_squared
【发布时间】:2021-02-07 13:17:36
【问题描述】:

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

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

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,offset,amp,mean,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,y_values_fit,yerr=y_err)

为了有一个合理的情节应该修改什么。

【问题讨论】:

    标签: python numpy data-analysis chi-squared


    【解决方案1】:

    问题是你的功能定义和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,offset,amp,mean,wid):
        return (offset + amp*np.exp(-((x_values-mean)/wid)**2))
    

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

    【讨论】:

    • 哦,函数是我为上一个问题定义的,应该没问题。但是我在 y_values_fit 的末尾添加了 flatted() 并且它起作用了。我对这如何解决问题感到有些困惑?你能给我一些进一步的解释,以便我更好地理解吗?无论哪种方式,它都解决了我的问题,我非常感谢您的帮助!谢谢
    • 您发布的版本有x_values参数,但没有使用。相反,您使用了变量i,该变量用于其他目的。
    猜你喜欢
    • 2021-07-05
    • 1970-01-01
    • 2014-09-07
    • 2019-12-05
    • 1970-01-01
    • 2015-08-21
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多