lmfit 中拟合参数的不确定性

Uncertainties on fitted parameters in lmfit

我正在寻找输出拟合参数不确定性的最简单方法。使用spo.curve_fit,我们在拟合时得到协方差矩阵,我们可以取对角线和平方根来找到不确定性。有了lmfit就好像没那么简单了

我的装修是这样的:

import lmfit 


a_lm2 = lmfit.Parameter('a', value=a_est)
b_lm2 = lmfit.Parameter('b', value=b_est)
x0_core_lm2 = lmfit.Parameter('x0_core', value=gaus1['x0_core'])
x0_1_lm2 = lmfit.Parameter('x0_1', value=gaus1['x0_1'])
x0_2_lm2 = lmfit.Parameter('x0_2', value=gaus1['x0_2'])
x0_3_lm2 = lmfit.Parameter('x0_3', value=gaus1['x0_3'])
x0_4_lm2 = lmfit.Parameter('x0_4', value=gaus1['x0_4'])
sig_core_lm2 = lmfit.Parameter('sig_core', value=gaus1['sig_core'])
sig_1_lm2 = lmfit.Parameter('sig_1', value=gaus1['sig_1'])
sig_2_lm2 = lmfit.Parameter('sig_2', value=gaus1['sig_2'])
sig_3_lm2 = lmfit.Parameter('sig_3', value=gaus1['sig_3'])
sig_4_lm2 = lmfit.Parameter('sig_4', value=gaus1['sig_4'])
m_lm2 = lmfit.Parameter('m', value=m, vary=False)
c_lm2 = lmfit.Parameter('c', value=c, vary=False)


gausfit2 = mod.fit(y, x=x, a=a_lm2, b=b_lm2, x0_core=x0_core_lm2, x0_1=x0_1_lm2, x0_2=x0_2_lm2,

x0_3=x0_3_lm2, x0_4=x0_4_lm2, sig_core=sig_core_lm2, sig_1=sig_1_lm2, sig_2=sig_2_lm2,

sig_3=sig_3_lm2, sig_4=sig_4_lm2, m=m_lm2, c=c_lm2,weights=None, scale_covar=False)


print 'a_lm2_unc =', a_lm2.stderr

当我生成拟合报告时,我得到了不确定值,因此很明显它们正在计算中。我的问题是调用它们并使用它们。我尝试像上面最后一行代码那样使用 stderr 打印参数的不确定性,但这只是 returns 'None'。我可以获得一个协方差矩阵,但我不知道它以什么顺序显示。我的最终目标只是获得值和相关的不确定性,然后我可以将它们放入一个数组中并在我的代码中进一步使用。

因为我没有你的数据,所以我无法测试,但看起来你已经差不多了。您的 "gausfit2" 应该是一个 ModelFit 对象 (http://cars9.uchicago.edu/software/python/lmfit/model.html#model.ModelFit)。因此,您只需执行以下操作即可生成报告:

print gausfit2.fit_report #will print you a fit report from your model

#you should also be able to access the best fit parameters and other associated attributes. For example, you can use gausfit2.best_values to obtain a dictionary of the best fit values for your params, or gausfit2.covar to obtain the covariance matrix you are interested in. 

print gausfit2.covar

#one suggestion to shorten your writing is to just create a parameters class with a shorter name and add your params to that.

params = lmfit.Parameters()
params.add('a', value=a_est) #and so on...

干杯!

不确定性隐藏在 .stderr 属性下的模型中。例如:

gmodel = Model(function_tofit)
fit_params = Parameters()
fit_params.add('parameter1',value=guess1)
fit_params.add('parameter2',value=guess2)
...
result = gmodel.fit(y_to_fit, fit_params, x = x_to_fit)

#get the output value of the fit
mean_fit_value = result.params['parameter1'].value
std_fit_value = result.params['parameter1'].stderr

在您的情况下,您打印了 fit_params['your_parameter'].stderr,这显然是 None,因为您没有在参数中指定任何先验信息。请记住,fit_params 是您的输入,而 params 是您想要的输出。