【问题标题】:Scipy Optimize Curve fit not properly fitting with real dataScipy 优化曲线拟合与真实数据不正确拟合
【发布时间】:2021-02-16 09:05:12
【问题描述】:

我正在尝试将衰减指数函数拟合到现实世界的数据中。我在将函数与实际数据对齐时遇到问题。

这是我的代码:

def test_func(x, a, b, c):
    return a*np.exp(-b*x)*np.sin(c*x)

my_time = np.linspace(0,2.5e-6,25000)
p0 = [60000, 700000, 2841842]

params, params_covariance = curve_fit(test_func, my_time, my_amp,p0)

我的信号和拟合函数

我的问题:为什么拟合函数没有从我的数据开始幅度增加的地方开始?

【问题讨论】:

  • 但它确实会复制您的数据。 fit 函数不知道它必须在开始时排除高原并稍后开始。您必须在 test_func 中定义它。

标签: python python-3.x curve-fitting scipy-optimize


【解决方案1】:

正如我在评论中所说,问题在于您的函数没有考虑到指数曲线可以移动。如果将此偏移作为附加参数包含在内,则拟合可能会收敛。

from scipy.optimize import curve_fit 
from matplotlib import pyplot as plt
import numpy as np

def test_func(x, a, b, c, d):  
    return a*np.exp(-b*(x+d))*np.sin(c*(x+d))

my_time = np.linspace(0,2.5e-6,25000)

#generate fake data
testp0 = [66372, 765189, 2841842, -1.23e-7]
test_amp = test_func(my_time, *testp0)
my_amp = test_func(my_time, *testp0)
my_amp[:2222] = my_amp[2222]

p0 = [600, 700000, 2000, -2e-7]
params, params_covariance = curve_fit(test_func, my_time, test_amp, p0)
print(params)
fit_amp = test_func(my_time, *params)

plt.plot(my_time, my_amp, label="data")
plt.plot(my_time, fit_amp, label="fit")
plt.legend()

plt.show()

样本输出

【讨论】:

  • 很高兴这解决了它。始终检查您的模型在理论上是否能够拟合您的数据。根据定义,您的初始函数必须从 [0,0] 开始。
猜你喜欢
  • 2020-05-05
  • 1970-01-01
  • 2018-08-16
  • 2017-04-21
  • 1970-01-01
  • 2023-03-23
  • 2018-06-02
  • 2021-11-01
  • 2019-08-08
相关资源
最近更新 更多