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

如何拟合先递增后趋于平稳的函数?现有分段拟合效果不佳

数据函数拟合问题

我尝试对以下数据进行函数拟合:

import numpy as np
x_data = np.array([0.01      , 0.01871795, 0.0274359 , 0.03615385, 0.04487179,
       0.05358974, 0.06230769, 0.07102564, 0.07974359, 0.08846154,
       0.09717949, 0.10589744, 0.11461538, 0.12333333, 0.13205128,
       0.14076923, 0.14948718, 0.15820513, 0.16692308, 0.17564103,
       0.18435897, 0.19307692, 0.20179487, 0.21051282, 0.21923077,
       0.22794872, 0.23666667, 0.24538462, 0.25410256, 0.26282051,
       0.27153846, 0.28025641, 0.28897436, 0.29769231, 0.30641026,
       0.31512821, 0.32384615, 0.3325641 , 0.34128205, 0.35      ])
y_data = np.array([0.07462271, 0.12197987, 0.15732335, 0.18376046, 0.2035856 ,
       0.21849438, 0.22974112, 0.23825469, 0.24472376, 0.24965963,
       0.25344248, 0.25635547, 0.2586099 , 0.26036377, 0.26173554,
       0.26281424, 0.26366699, 0.26434454, 0.26488545, 0.2653191 ,
       0.265668  , 0.26594946, 0.26617689, 0.26636074, 0.26650917,
       0.26662865, 0.2667243 , 0.26680021, 0.26685972, 0.26690551,
       0.26693978, 0.26696438, 0.26698081, 0.26699036, 0.2669941 ,
       0.26699297, 0.26698774, 0.26697912, 0.26696768, 0.26695394])

尝试过的拟合方法

  • 通用幂函数:无法捕捉x超过阈值后y趋于恒定的特性,拟合失败。
  • 分段函数:定义x<a时为幂律函数,x≥a时为常数,具体实现代码如下:
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

def fpiece(x, a, b, c, d):
    return np.where(x < a, b*np.power(x, c), d)

# 初始参数猜测
pars0 = (0.15, 0.4, 1, 0.25)

# 执行拟合(最大迭代次数5000)
popt, pcov = curve_fit(fpiece, x_data, y_data, p0=pars0, maxfev=5000)

# 绘制数据与拟合曲线
plt.errorbar(x_data, y_data, yerr=0, fmt="..", color='black', label='data', zorder=1, markersize=10)
x_interval = np.linspace(0, max(x_data), len(x_data))
y_fit = fpiece(x_interval, *popt)

plt.plot(x_interval, y_fit, color="red", label="Best fit", zorder=2, linewidth=3)

plt.grid(True)
plt.ylabel("y data")
plt.xlabel("x data")
plt.title("Best fit of data")
plt.legend()
plt.show()

拟合结果问题

上述分段函数的拟合效果不理想,示意图如下:
拟合效果示意图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:52:05