Hoonnn 2023-03-03 17:29 采纳率: 64.3%
浏览 17
已结题

optimize.curve_fit的lm方法和bound冲突

请问如果用了optimize.curve_fit的‘lm’方法,但‘lm’和对参数设边界(>0)矛盾,只能用‘trf’,导致拟合结果很奇怪,有啥能够兼顾lm和边界的方法吗,或许不能用scipy?

  • 写回答

1条回答 默认 最新

  • 「已注销」 2023-03-04 00:19
    关注

    “Devil组”引证GPT后的撰写:
    要在优化过程中同时使用 Levenberg-Marquardt(LM)方法和参数边界,则可以考虑使用其他的优化库,例如 lmfit 或 cma-es。

    lmfit 库是一个专门用于拟合的 Python 库,它提供了许多与参数拟合相关的函数和类。其中包括一个 Minimizer 类,它使用 LM 算法,并且允许您在拟合过程中设置参数边界。

    下面是一个使用 lmfit 库拟合一个正弦函数的例子:

    import numpy as np
    import matplotlib.pyplot as plt
    from lmfit import Model
    
    # Define the model
    def sine(x, amplitude, frequency, phase, offset):
        return amplitude * np.sin(2 * np.pi * frequency * x + phase) + offset
    
    # Generate some noisy data
    x = np.linspace(0, 2 * np.pi, 50)
    y = sine(x, 1, 1, 0, 0) + np.random.normal(0, 0.1, 50)
    
    # Define the LM model
    model = Model(sine)
    
    # Set the parameter bounds
    model.set_param_hint('amplitude', min=0)
    model.set_param_hint('frequency', min=0)
    model.set_param_hint('offset', min=0)
    
    # Fit the model to the data
    result = model.fit(y, x=x, amplitude=0.5, frequency=2, phase=0, offset=0)
    
    # Plot the results
    plt.scatter(x, y)
    plt.plot(x, result.best_fit)
    plt.show()
    
    # Print the fitted parameters
    print(result.params)
    
    
    

    cma-es 库是另一个常用的全局优化库,它可以在不知道参数范围的情况下进行优化。该库使用进化策略算法来寻找全局最优解。下面是一个使用 cma-es 库拟合同样正弦函数的例子:

    import numpy as np
    import matplotlib.pyplot as plt
    import cma
    
    # Define the objective function
    def objective_function(params):
        amplitude, frequency, phase, offset = params
        y_pred = amplitude * np.sin(2 * np.pi * frequency * x + phase) + offset
        error = np.sum((y - y_pred) ** 2)
        return error
    
    # Generate some noisy data
    x = np.linspace(0, 2 * np.pi, 50)
    y = np.sin(x) + np.random.normal(0, 0.1, 50)
    
    # Set the initial guess
    initial_guess = [0.5, 2, 0, 0]
    
    # Set the bounds
    bounds = [[0, np.inf], [0, np.inf], [0, 2 * np.pi], [0, np.inf]]
    
    # Run the optimizer
    result = cma.fmin(objective_function, initial_guess, bounds=bounds)
    
    # Plot the results
    plt.scatter(x, y)
    plt.plot(x, result[0] * np.sin(2 * np.pi * result[1] * x + result[2]) + result[3])
    plt.show()
    
    # Print the fitted parameters
    print(result)
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月12日
  • 已采纳回答 3月4日
  • 创建了问题 3月3日

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)