尝试用scipy使trig函数适合数据

2024-09-24 20:34:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用scipy.optimize.curve_fit来拟合一些数据。我有read the documentationthis StackOverflow post,但似乎都没有回答我的问题。你知道吗

我有some data,这是一个简单的二维数据,看起来像一个trig函数。我想用一个通用的trig函数来拟合它 使用scipy。你知道吗

我的方法如下:

from __future__ import division
import numpy as np
from scipy.optimize import curve_fit



#Load the data
data = np.loadtxt('example_data.txt')
t = data[:,0]
y = data[:,1]


#define the function to fit
def func_cos(t,A,omega,dphi,C):
    # A is the amplitude, omega the frequency, dphi and C the horizontal/vertical shifts
    return A*np.cos(omega*t + dphi) + C

#do a scipy fit
popt, pcov = curve_fit(func_cos, t,y)

#Plot fit data and original data
fig = plt.figure(figsize=(14,10))
ax1 = plt.subplot2grid((1,1), (0,0))

ax1.plot(t,y)
ax1.plot(t,func_cos(t,*popt))

这将输出:

enter image description here

蓝色代表数据橙色代表适合。很明显我做错了什么。有什么建议吗?你知道吗


Tags: the数据importdatanpscipycosfit
1条回答
网友
1楼 · 发布于 2024-09-24 20:34:06

如果没有为参数p0的初始猜测提供值,则假定每个参数的值为1。从文档中:

p0 : array_like, optional
Initial guess for the parameters (length N). If None, then the initial values will all be 1 (if the number of parameters for the function can be determined using introspection, otherwise a ValueError is raised).

由于您的数据具有非常大的x值和非常小的y值,1的初始猜测与实际解决方案相差甚远,因此优化器不会收敛。您可以通过提供合适的初始参数值来帮助优化器,这些初始参数值可以从数据中猜测/近似:

  • 振幅:A = (y.max() - y.min()) / 2
  • 偏移量:C = (y.max() + y.min()) / 2
  • 频率:这里我们可以通过将连续的y值相乘来估计过零的次数,并检查哪些乘积小于零。这个数除以总的x范围得到频率,为了得到它的单位是pi,我们可以用这个数乘以piy_shifted = y - offset; oemga = np.pi * np.sum(y_shifted[:-1] * y_shifted[1:] < 0) / (t.max() - t.min())
  • 相移:可以设置为零,dphi = 0

总之,可以使用以下初始参数猜测:

offset = (y.max() + y.min()) / 2
y_shifted = y - offset
p0 = (
    (y.max() - y.min()) / 2,
    np.pi * np.sum(y_shifted[:-1] * y_shifted[1:] < 0) / (t.max() - t.min()),
    0,
    offset
)
popt, pcov = curve_fit(func_cos, t, y, p0=p0)

它提供了以下拟合函数:

Fit

相关问题 更多 >