gpt4 book ai didi

python - 在 python 中使用 scipy curve_fit 拟合 boxcar 函数的问题

转载 作者:太空宇宙 更新时间:2023-11-04 00:28:31 25 4
gpt4 key购买 nike

我无法让这个 boxcar 正常工作...我得到 "OptimizeWarning: Covariance of the parameters could not be estimated 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 中指定蒙特卡洛优化是微不足道的。

最佳答案

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

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

enter image description here

  • 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()

enter image description here

关于python - 在 python 中使用 scipy curve_fit 拟合 boxcar 函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46624376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com