Constraints on curve fitting parameters

三世轮回 提交于 2019-12-25 08:25:23

问题


I am trying to impose bounds and constraints in my quadratic curve fitting process. Objective is to find coefficients a,b and c. Imposing constraint on b: delta-2*a*x is my doubt. How can I add a variable, x in my constraints. Workable code:

from lmfit import Model, Parameters

#create x and y data to be used for curve fitting
xip=[ 0.02237461, 0.0983837 , 0.25707382, 0.56959641, 1.33419197, 4.95835927]
yip=[0.20085822, 0.23583258, 0.28996988, 0.36350284, 0.47981232, 0.67602165] 

#function to fit data: a,b,c needs to be found
def f(xx, a, b, c):
    # constraints: c <=0,  a>0  and 2*a*x+b >= 0
    return a*xx**2 + b*xx + c

fmodel = Model(f)
params = Parameters()

params.add('a', value=-1e-2, vary=True, min = -1e10, max = 0)
params.add('c', value=-4e-2, vary=True, min = -1e10, max =0)
params.add('delta', value=5e-2, vary=True, min=0, max=1e10)
params.add('xpara', value=5, vary=True)
params.add('b', expr = 'delta-2*a*xpara')

result = fmodel.fit(yip, params, xx=xip)
print(result.fit_report())


import  matplotlib.pyplot as plt
op = plt.subplot(1,1,1)
op.scatter(xip,yip)
plt.plot(xip, result.init_fit, 'k--')
#plt.plot(xip, result.best_fit, 'r-')

Thanks !

Edit: I have changed variables, to make this program work. But not sure if it is the right way to apply constraints.

Edit 2: necessary constrains added: c <=0, a>0 and 2*a*x+b >= 0 ;


回答1:


What error do you get?

It looks to me like the code should work. But, in your message you said you wanted to constraint c to be delta+b+2*a*x while in your code you have delta-b-2*a*xpara. Is there a sign problem?

You also initialize delta to 5e-2, but set it's maximum value to 0. That seems like a mistake, possibly related to confusing signs.



来源:https://stackoverflow.com/questions/40806362/constraints-on-curve-fitting-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!