You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用optimize.curve_fit拟合时如何固定phi参数?

如何用optimize.curve_fit固定phi参数

想要用scipy.optimize.curve_fit固定phi参数?这里有几种实用的方法,帮你轻松实现:

  • 方法1:重定义拟合函数,将phi设为常量

    如果你已经确定了phi的固定值(比如phi_fixed = 1.0),直接改写拟合函数,把phi替换成固定值,只保留需要优化的参数:

    import numpy as np
    from scipy import optimize
    
    # 替换成你需要固定的phi值
    phi_fixed = 1.0
    
    def sinefunction_fixed_phi(x, a, b, c, omega):
        return a + b * np.sin(omega*x + phi_fixed) + c*(np.sin(omega*x + phi_fixed))**2
    
    x = scan_no
    y = fwhm_r
    # 初始值p0只对应a、b、c、omega四个待拟合参数
    p0 = [0.05, 0.1, 0.01, 0.12]
    params2, params_covariance2 = optimize.curve_fit(
        sinefunction_fixed_phi, x, y, p0, sigma=error_r, absolute_sigma=True
    )
    

    这种方法最直观,适合只固定少数参数的场景。

  • 方法2:利用bounds参数锁定phi的范围

    如果你不想修改原函数,可以通过bounds参数把phi的上下限设置成同一个值,这样拟合过程中它就会保持固定:

    import numpy as np
    from scipy import optimize
    
    def sinefunction2(x, a, b, c, phi, omega):
        return a + b * np.sin(omega*x + phi) + c*(np.sin(omega*x + phi))**2
    
    phi_fixed = 1.0  # 你的固定值
    x = scan_no
    y = fwhm_r
    p0 = [0.05, 0.1, 0.01, phi_fixed, 0.12]
    
    # 定义每个参数的上下界:phi的上下限都设为固定值,其他参数保留默认范围
    lower_bounds = (-np.inf, -np.inf, -np.inf, phi_fixed, -np.inf)
    upper_bounds = (np.inf, np.inf, np.inf, phi_fixed, np.inf)
    
    params2, params_covariance2 = optimize.curve_fit(
        sinefunction2, x, y, p0, sigma=error_r, absolute_sigma=True,
        bounds=(lower_bounds, upper_bounds)
    )
    

    注意phi在参数列表里的位置是第4个(索引为3),要确保bounds里的对应位置设置正确。

  • 方法3:用args参数传递固定值

    调整原函数的参数顺序,把固定参数放到最后,然后通过curve_fit的args参数传入固定值,这样拟合时只会优化前面的参数:

    import numpy as np
    from scipy import optimize
    
    # 调整参数顺序,把phi放到最后作为额外参数
    def sinefunction2(x, a, b, c, omega, phi):
        return a + b * np.sin(omega*x + phi) + c*(np.sin(omega*x + phi))**2
    
    phi_fixed = 1.0  # 你的固定值
    x = scan_no
    y = fwhm_r
    # p0只对应a、b、c、omega四个待拟合参数
    p0 = [0.05, 0.1, 0.01, 0.12]
    
    params2, params_covariance2 = optimize.curve_fit(
        sinefunction2, x, y, p0, sigma=error_r, absolute_sigma=True,
        args=(phi_fixed,)  # 传入固定的phi值
    )
    

    这种方法灵活性很高,适合需要固定多个参数的场景,只需要把所有固定参数都放到args里即可。

内容的提问来源于stack exchange,提问作者Krystal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 15:44:06