我正在尝试使用lmfit
使某些模型适合我的数据。请参阅下面的MWE:
import lmfit
import numpy as np
def lm(params, x):
slope = params['slope']
interc = params['interc']
return interc + slope * x
def lm_min(params, x, data):
y = lm(params, x)
return data - y
x = np.linspace(0,100,1000)
y = lm({'slope':1, 'interc':0.5}, x)
ydata = y + np.random.randn(1000)
params = lmfit.Parameters()
params.add('slope', 2)
params.add('interc', 1)
fitter = lmfit.Minimizer(lm_min, params, fcn_args=(x, ydata), fit_kws={'xatol':0.01})
fit = fitter.minimize(method='nelder')
为了尽早完成(准确性现在不是最重要的事情),我想更改停止拟合的标准。基于docs和对SO的一些搜索,我尝试提供一些关键字参数(在下面的行中为fit_kws
),这些参数将传递给所使用的最小化器。我也尝试使用kws
和**{'xatol':0.01}
。紧接着,我还在最后一行称为fitter.minimize()
的行中尝试了上述选项。但是,在所有情况下,我都会得到一个TypeError
,说它得到了意外的关键字参数:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~/STACK/WUR/PhD/Experiments/Microclimate experiment/Scripts/Fluctuations/mwe.py in <module>()
25
26 fitter = lmfit.Minimizer(lm_min, params, fcn_args=(x, ydata), fit_kws={'xatol':0.01})
---> 27 fit = fitter.minimize(method='nelder')
28
~/anaconda3/envs/py/lib/python3.6/site-packages/lmfit/minimizer.py in minimize(self, method, params, **kws)
1924 val.lower().startswith(user_method)):
1925 kwargs['method'] = val
-> 1926 return function(**kwargs)
1927
1928
~/anaconda3/envs/py/lib/python3.6/site-packages/lmfit/minimizer.py in scalar_minimize(self, method, params, **kws)
906 else:
907 try:
--> 908 ret = scipy_minimize(self.penalty, variables, **fmin_kws)
909 except AbortFitException:
910 pass
TypeError: minimize() got an unexpected keyword argument 'fit_kws'
有人知道我如何为特定的求解器添加关键字参数吗?
python:3.6.9
scipy:1.3.1
lmfit:0.9.12
答案 0 :(得分:0)
将关键字参数传递给基础scipy
求解器的最佳方法就是使用
# Note: valid but will not do what you want
fitter = lmfit.Minimizer(lm_min, params, fcn_args=(x, ydata), xatol=0.01)
fit = fitter.minimize(method='nelder')
或
# Also: valid but will not do what you want
fitter = lmfit.Minimizer(lm_min, params, fcn_args=(x, ydata))
fit = fitter.minimize(method='nelder', xatol=0.01)
这里的主要问题是xatol
对于基础求解器scipy.optimize.minimize()
不是有效的关键字参数。相反,您可能打算使用tol
:
fitter = lmfit.Minimizer(lm_min, params, fcn_args=(x, ydata), tol=0.01)
fit = fitter.minimize(method='nelder')
或
fitter = lmfit.Minimizer(lm_min, params, fcn_args=(x, ydata))
fit = fitter.minimize(method='nelder', tol=0.01)
答案 1 :(得分:0)
在github issue中,我找到了以下解决方案:
fit = fitter.minimize(method='nelder', **{'options':{'xatol':4e-4}})
更新
如@dashesy所述,这与编写相同:
fit = fitter.minimize(method='nelder', options={'xatol':4e-4})
这也适用于其他求解器选项。