简体   繁体   English

Python LMFIT - 使用有界参数时获得错误的最小化结果

[英]Python LMFIT - Get the wrong result for Minimization, when using bounded parameters

Now, I have trouble using minimize in LMFIT-Module.现在,我无法在 LMFIT 模块中使用minimize Please see the case below:请看以下案例:

Case 1: Parameter without constraints案例 1:没有约束的参数

import numpy as np
import matplotlib.pyplot as plt
from lmfit import Model, minimize, Parameters, Parameter, report_fit

noise = np.random.randn(100)

def func_model(para, x, data):
    ''' Model: y = a*sin(2*k*pi*x+theta)'''
    a = para['a']
    k = para['k']
    theta = para['theta']
    model= a*np.sin(2*k*np.pi*x+theta)
    return model-data  # thas's what I want to minimize

def func_noise(x, para):
    a, k, theta = para
    return a*np.sin(2*k*np.pi*x+theta) + noise

x_steps = np.linspace(-2*np.pi, 0, 100)
para_true = [10, 0.34, np.pi/6]
datas = func_noise(x_steps, para_true)

params = Parameters()

params.add('a', value=7)
params.add('k', value=0.2)
params.add('theta', value=0)

result = minimize(func_model, params, args=(x_steps, datas))
report_fit(result)

Got the result:得到结果:

a:      10.0054134 +/- 0.14334401 (1.43%) (init = 7)
k:      0.33954301 +/- 0.00110337 (0.32%) (init = 0.2)
theta:  0.52071533 +/- 0.02546636 (4.89%) (init = 0)

compare to the factual parameters [10, 0.34, pi/6] the results are right.与事实参数[10, 0.34, pi/6] ,结果是正确的。

Case 2: Parameter with constraints案例 2:带有约束的参数

just change to:只需更改为:

params.add('a', value=7, min=5, max=15)    #   should be 10
params.add('k', value=0.2, min=0, max=1)   #   should be 0.34
params.add('theta', value=0)

and keep other code same, then get the wrong result:并保持其他代码相同,然后得到错误的结果:

a:      14.9999918 +/- 51.0737691 (340.49%) (init = 7)
k:      0.01305462 +/- 0.58283692 (4464.60%) (init = 0.2)
theta: -2.90461833 +/- 10.5723936 (363.99%) (init = 0)

How could it happen?怎么会发生?

I think the main problem is that k goes to nearly 0 here, which makes it hard for the fitting process to determine the other parameters.我认为主要问题是k在这里接近于 0,这使得拟合过程很难确定其他参数。 When parameters hit their bounds, it can be hard for the algorithm to be able to move away from it.当参数达到极限时,算法很难摆脱它。 Here it looks like it tries a of ~15, then that pushes k toward zero and it ends up so far away it doesn't know how to get unstuck.在这里,它看起来像是尝试a ~15 的 a,然后将k推向零,结果离得很远,它不知道如何解开。

Generally, it's a good idea to set bounds based on physical limitations, or to know how the fit will respond to values near the bounds.通常,最好根据物理限制设置边界,或者了解拟合将如何响应边界附近的值。 That said, I don't really know why this case is so bad.也就是说,我真的不知道为什么这个案子这么糟糕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM