曲线拟合参数的约束 [英] Constraints on curve fitting parameters
问题描述
我正在尝试在二次曲线拟合过程中施加界限和约束.目的是找到系数a,b
和c
.对b施加约束:delta-2*a*x
是我的疑问.如何在约束中添加变量x
.可行的代码:
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-')
谢谢!
为了使该程序正常运行,我更改了变量.但不确定是否是应用约束的正确方法.
I have changed variables, to make this program work. But not sure if it is the right way to apply constraints.
添加了必要的约束:c< = 0,a> 0和2 * a * x + b> = 0;
Edit 2: necessary constrains added: c <=0, a>0 and 2*a*x+b >= 0 ;
推荐答案
您遇到什么错误?
在我看来,该代码应该可以工作.但是,在您的消息中,您说过想将c
约束为delta+b+2*a*x
,而在代码中却具有delta-b-2*a*xpara
.有征兆问题吗?
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?
您还可以将delta
初始化为5e-2,但是将其最大值设置为0.这似乎是一个错误,可能与混乱的符号有关.
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.
这篇关于曲线拟合参数的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!