Scipy Optimize曲线拟合未正确拟合实际数据 [英] Scipy Optimize Curve fit not properly fitting with real data

查看:73
本文介绍了Scipy Optimize曲线拟合未正确拟合实际数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to fit a decaying exponential function to real world data. I'm having a problem with aligning the function to the actual data.

这是我的代码:

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)

我的信号和合适的功能

My signal and fitted function

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

My question: why doesn't the fitted function start where my data starts increasing in amplitude?

推荐答案

问题是您的函数没有考虑指数曲线可以移动的问题.如果将此移位作为附加参数包括在内,则拟合可能会收敛.

As I said in my comment, the problem is that your function does not take into account that the exponential curve can be shifted. If you include this shift as an additional parameter, the fit will probably converge.

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

样本输出

这篇关于Scipy Optimize曲线拟合未正确拟合实际数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆