Add constraints to scipy.optimize.curve_fit?

六眼飞鱼酱① 提交于 2019-12-05 05:59:24

With lmfit, you would define 4 parameters (a, b, c, and delta). a and b can vary freely. delta is allowed to vary, but has a maximum value of 10 to represent the inequality. c would be constrained to be delta-a-b (so, there are still 3 variables: c will vary, but not independently from the others). If desired, you could also put bounds on the values for a, b, and c. Without testing, your code would be approximately::

import numpy as np
from lmfit import Model, Parameters

def f(x, a, b, c):
    return a*x**2 + b*x + c

x = np.linspace(0, 100.0, 101)
y = 2*x**2 + 3*x + 4.0

fmodel = Model(f)
params = Parameters()
params.add('a', value=1, vary=True)
params.add('b', value=4, vary=True)
params.add('delta', value=5, vary=True, max=10)
params.add('c', expr = 'delta - a - b')

result = fmodel.fit(y, params, x=x)
print(result.fit_report())

Note that if you actually get to a situation where the constraint expression or bounds dictate the values for the parameters, uncertainties may not be estimated.

curve_fit and least_squares only accept box constraints. In scipy.optimize, SLSQP can deal with more complicated constraints. For curve fitting specifically, you can have a look at lmfit package.

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