【问题标题】:How do I set constraints for my parameters when making a curvefit using the lmfit library?使用 lmfit 库进行曲线拟合时,如何为我的参数设置约束?
【发布时间】:2019-10-28 23:26:12
【问题描述】:

我正在尝试使用 lmfit 库进行曲线拟合。我的目标是让曲线从 x=0 开始,f(0) = "a constant"。我还希望它的最小值为 x=1。但是,当我将约束放入模型时,f(1) > f(0)。

F(x) = Aexp(Bx) + Cx2 + Dx + E
F'(x) = ABexp(B*x) + 2*Cx + D
F''(x) = A
B2 exp(Bx) +2C

F(0) = 常数 = A + E => E = 常数 - A
F'(1) = 0 = ABexp(B) + 2*C + D => D = - (2*C + BAexp(B) )
F''(1) > 0 => A*B2exp(B) +2*C > 0 => C > -A B2 *exp(B)/2

这给了我们以下约束方程:
F(x) = Cx(x-2) + A*(exp(Bx) - Bexp(B*x) -1) + 常数

除了以下需要尊重的不等式:
F''(1) > 0 => A*B**2 *exp(B) + 2*C > 0 => C > -B2AeB/2

Image of the calculations in word for easier reading

def model_5(x, a, b, c):
    return  c*x*(x-2) + a*(np.exp(b*x) - x*b*np.exp(b) - 1) + 0.003591687375349475

model_5b = Model(model_5)

pars_5b = Parameters()
pars_5b.add('a', value = 0.007)
pars_5b.add('b', value = 0.05)
pars_5b.add('delta', value = 0.02, min=0, vary=True)
pars_5b.add('c', expr="delta - 0.5*a*(b**2)*exp(b) ")

model_5b.fit(y, x=X, params=pars_5b, method="trf")

# Output from above fit
Variables
name    value   initial value   min max vary    expression
a   9.9227e-05  0.007   -inf    inf True    
b   0.08377349  0.05    -inf    inf True    
delta   5.7477e-11  0.02    0.00000000  inf True    
c   -3.7855e-07 0.019990801377906712    -inf    inf False   delta - 0.5*a*(b**2)*exp(b)

# Create predictions with the fitted models values
pred_5b = model_5(X, 9.9227e-05, 0.08377349, -3.7855e-07)

# Check if f(1) equals the minima
pred_5b[1] == np.min(pred_5b) # returns False, should return true



将我的约束放入模型时,f(1) > f(0),f(1) 不是最小值。但是,它应该是在包含约束时。因此,我觉得我一定是错误地输入了约束。有人可以指导我正确的方向吗?

与我在 Stackoverflow 上发现的其他问题的不同之处在于,约束包括与正在优化的参数的不等式。即 C > -B2AeB/2

【问题讨论】:

标签: python constraints mathematical-optimization lmfit


【解决方案1】:

我认为约束数学是正确的(太棒了!),问题出在:

# Check if f(1) equals the minima
pred_5b[1] == np.min(pred_5b) # returns False, should return true

这只有在x[1] = 1 时才是正确的。也就是说,pred_5b[1]pred_5b 的第二个元素,而不是(必然)pred_5bx=1 处的值。

【讨论】:

  • 感谢您的回复 M 纽维尔。我可以确认 x[1] == 1。X 基本上是一个年龄从 0 到 105 的向量。所以 x[z] = z,对于所有的 z。我可以提供任何其他信息以便您更轻松地提供帮助吗?我已将数学推导和函数添加为图像,以使其更具可读性..
  • 哦,您对一阶和二阶导数的约束实际上只能确保 x=1 是局部最小值,而不是全局最小值。我认为它总是适用于 x>=0,但对于某些 x
猜你喜欢
  • 1970-01-01
  • 2018-05-24
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 2021-07-13
  • 2021-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多