在 python 中使用 scipy 的曲线拟合 boxcar 函数的问题

Problems fitting to boxcar function using scipy's curvefit in python

我无法让这个 boxcar 正常工作...我得到 " OptimizeWarning: 无法估计参数的协方差 category=OptimizeWarning)",并且输出系数没有改善超出起始猜测。

import numpy as np
from scipy.optimize import curve_fit
def box(x, *p):
    height, center, width = p
    return height*(center-width/2 < x)*(x < center+width/2)

x = np.linspace(-5,5)
y = (-2.5<x)*(x<2.5) + np.random.random(len(x))*.1

coeff, var_matrix = curve_fit(box, x, y, p0=[1,0,2])

输出系数是[1.04499699,0.,2.],不是第三个连改都没有

我怀疑这个函数形式不适合 curve_fit 使用的 levenberg-marquardt 算法,这有点烦人,因为我喜欢这个函数。相反,在 mathematica 中指定 monte carlo 优化是微不足道的。

I suspect that this functional form is not amenable to the levenberg-marquardt algorithm used by curve_fit

你是对的。通常,基于梯度的优化不太适合具有锐边的函数。通过稍微扰动函数参数并查看拟合质量的变化来估计梯度。但是,如果边缘不穿过数据点,则稍微移动边缘会导致零梯度:

  • A:很容易拟合振幅,因为高度的微小变化会立即导致残差发生变化。
  • B:难以拟合边缘,因为位置的微小变化不会影响残差(除非变化大到足以使边缘穿过数据点)。

使用随机方法应该效果更好。 Scipy 有 differential_evolution 函数,它使用遗传算法,因此与蒙特卡洛方法有关。但是,使用起来不如 curve_fit 简单。您需要为参数指定成本函数和范围:

res = differential_evolution(lambda p: np.sum((box(x, *p) - y)**2),  # quadratic cost function
                             [[0, 2], [-5, 5], [0.1, 10]])  # parameter bounds

还是单行:)

coeff, var_matrix = curve_fit(box, x, y, p0=[1,0,2])

res = differential_evolution(lambda p: np.sum((box(x, *p) - y)**2), [[0, 2], [-5, 5], [0.1, 10]])

plt.step(x, box(x, *coeff), where='mid', label='curve_fit')
plt.step(x, box(x, *res.x), where='mid', label='diff-ev')
plt.plot(x, y, '.')
plt.legend()