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

如何为曲线拟合(curve fit)添加基于标准误差的权重

加权曲线拟合实现评估与优化建议

核心逻辑问题

你当前的实现存在权重逻辑倒置的问题:
scipy的curve_fit方法中,sigma参数传入的是每个观测点的标准不确定度,拟合时优化的目标函数为:

$ \chi^2 = \sum_{i=1}^n \left( \frac{y_i - f(x_i)}{\sigma_i} \right)^2 $
你数据集里的Weight列取值为1/Standard_Error,直接传入sigma会导致:标准误差越小的点,对应的Weight值越大,目标函数中对应项的分母越大,该项在总和中的占比越低,最终权重反而越小,完全不符合你「标准误差越小权重越高」的需求。

修正方案

两种修正方式二选一即可:

  • 方案1:直接传入Standard_Error列作为sigma参数,无需额外使用Weight列
    代码修改如下:
    popt2, pcov2 = curve_fit(boatman_temperature_function_optimised, 
                            xdata = df_altered.Temperature, 
                            ydata = df_altered.Growth_rate, 
                            p0 = array_of_maxima, 
                            sigma=df_altered.Standard_Error, 
                            bounds = (array_of_minima, array_of_maxima), 
                            absolute_sigma=True)
    
    该方案下标准误差越小的点,目标函数对应项分母越小、占比越高,权重越大,完全匹配你的需求。
  • 方案2:如果需要保留Weight列的使用,将sigma参数设置为1/df_altered.Weight即可,本质和方案1逻辑一致。

其他优化建议

  • 绘图时补充误差棒展示原始数据的不确定度,结果呈现更直观,可调整绘图代码如下:
    import numpy as np
    import matplotlib.pyplot as plt
    x = df_altered['Temperature']
    y1 = df_altered['Growth_rate']
    y_err = df_altered['Standard_Error']
    y2 = df_altered['Final_results']
    
    fig, ax1 = plt.subplots()
    # 原始数据增加误差棒展示
    ax1.errorbar(x, y1, yerr=y_err, fmt='ro', ecolor='r', alpha=0.7)
    ax2 = ax1.twinx()
    ax2.plot(x, y2, 'g-')
    
    ax1.set_xlabel('Temperature (°C)')
    ax1.set_ylabel('Observed growth rate', color='r')
    ax2.set_ylabel('Optimised modelled growth rate', color='g')
    
    plt.show()
    
  • 拟合完成后可计算归一化$\chi2$($\chi2$/自由度)验证拟合质量,数值接近1说明拟合结果和数据不确定度的匹配度较好。
  • 确认absolute_sigma参数的合理性:如果你传入的Standard_Error是真实测量得到的绝对标准误差,保留absolute_sigma=True即可,此时返回的协方差矩阵pcov2可直接用于计算参数的真实不确定度;如果Standard_Error只是相对不确定度,建议将该参数设置为False。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:45:03