我有一个3D数据,我想使用lmfit
将非线性模型拟合到数据中。这是我写的代码,但它不起作用。
from lmfit import minimize, Parameters, Parameter, report_fit
import numpy as np
m=np.array([13.8, 14.38, 14.316, 13.799, 14.135, 13.791, 14.531, 14.262, 14.08, 14.267, 14.259, 14.849, 14.396, 13.609])
lower_error_m=np.array([0.221,0.159,0.202,0.276,0.267,0.217,0.109,0.174,0.183,0.317,0.099,0.124,0.300,0.258])
upper_error_m=np.array([0.466,0.988,1.141,0.819,0.944,0.864,1.126,0.837,0.619,0.421,0.692,0.530,0.997,0.655])
asymmetric_error_m = [lower_error_m, upper_error_m]
r=np.array([7.168, 5.99, 6.296, 6.756, 6.297, 6.639, 5.857, 5.94, 7.312, 6.201, 7.191, 5.624, 5.584, 6.701])
lower_error_r=np.array([1.709,1.882,1.038,1.656,1.676,1.593,1.937,1.474,1.511,1.247,1.504,1.386,1.492,1.294])
upper_error_r=np.array([0.223,0.168,0.300,0.399,0.405,0.444,0.201,0.306,0.362,0.058,0.401,0.267,0.471,0.529])
asymmetric_error_r = [lower_error_r, upper_error_r]
q=np.array([0.13, 0.312,0.327,0.322,0.327,0.381,0.357,0.386,0.133,0.354,0.128,0.339,0.479,0.325])
# define objective function: returns the array to be minimized
def fcn2min(params, m, q, data):
""" model decaying sine wave, subtract data"""
A0 = params['A0'].value
B = params['B'].value
alpha = params['alpha'].value
model = 10**( np.log10(A0/(1+q)**B)+alpha*(m-14))
return model - data
# create a set of Parameters
params = Parameters()
params.add('A0', value= 6)
params.add('B', value= 0.1)
params.add('alpha', value= -0.1)
# do fit, here with leastsq model
result = minimize(fcn2min, params, args=(m, q, r))
我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/vol/anaconda/lib/python2.7/site-packages/lmfit-0.9.2_4_gfc81f36-py2.7.egg/lmfit/minimizer.py", line 774, in minimize
return fitter.minimize(method=method)
File "/vol/anaconda/lib/python2.7/site-packages/lmfit-0.9.2_4_gfc81f36-py2.7.egg/lmfit/minimizer.py", line 706, in minimize
return function(**kwargs)
File "/vol/anaconda/lib/python2.7/site-packages/lmfit-0.9.2_4_gfc81f36-py2.7.egg/lmfit/minimizer.py", line 547, in leastsq
lsout = scipy_leastsq(self.__residual, vars, **lskws)
File "/vol/anaconda/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 371, in leastsq
shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
File "/vol/anaconda/lib/python2.7/site-packages/scipy/optimize/minpack.py", line 20, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
File "/vol/anaconda/lib/python2.7/site-packages/lmfit-0.9.2_4_gfc81f36-py2.7.egg/lmfit/minimizer.py", line 258, in __residual
out = self.userfcn(params, *self.userargs, **self.userkws)
File "<stdin>", line 6, in fcn2min
TypeError: unsupported operand type(s) for +: 'int' and 'list'
这是我想要的模型:
其中A0
,B
和alpha
是模型的免费参数。我在m
和r
上也有错误,我想知道如何将它们包含在拟合过程中?
感谢。
答案 0 :(得分:0)
一个。使用lmfit版本0.9.3,你的例子运行完成没有这样的错误。
B中。您可以通过让目标函数返回
来包含数据中的不确定性 return (model - data)/ uncertainty
其中uncertainty
是数据的不确定性。
℃。抱歉,与MINPACK一样,最小二乘最小化不容易支持自变量中的非对称错误或错误。