在scipy.optimize.curve_fit中添加约束吗? [英] Add constraints to scipy.optimize.curve_fit?

查看:228
本文介绍了在scipy.optimize.curve_fit中添加约束吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以选择将边界添加到sio.curve_fit.有没有办法扩展涉及参数功能的边界功能?换句话说,假设我有一个带有两个或多个未知常量的任意函数.然后再说一遍,我知道所有这些常数的总和小于10.有没有办法实现最后一个约束?

I have the option to add bounds to sio.curve_fit. Is there a way to expand upon this bounds feature that involves a function of the parameters? In other words, say I have an arbitrary function with two or more unknown constants. And then let's also say that I know the sum of all of these constants is less than 10. Is there a way I can implement this last constraint?

import numpy as np
import scipy.optimize as sio
def f(x, a, b, c):
    return a*x**2 + b*x + c

x = np.linspace(0, 100, 101)
y = 2*x**2 + 3*x + 4

popt, pcov = sio.curve_fit(f, x, y, \
     bounds = [(0, 0, 0), (10 - b - c, 10 - a - c, 10 - a - b)]) # a + b + c < 10

现在,这显然是错误的,但是我认为这有助于理解要点.有什么方法可以将涉及参数的约束函数合并到曲线拟合中?

Now, this would obviously error, but I think it helps to get the point across. Is there a way I can incorporate a constraint function involving the parameters to a curve fit?

谢谢!

推荐答案

使用lmfit,您将定义4个参数(abcdelta). ab可以自由变化. delta允许变化,但最大值为10以表示不等式. c将被约束为delta-a-b(因此,仍然存在3个变量:c将有所不同,但不能独立于其他变量).如果需要,还可以对abc的值设置边界.如果不进行测试,您的代码将大致为::

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.

这篇关于在scipy.optimize.curve_fit中添加约束吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆