我试图用scipy.optimize.curve_fit
来拟合一些数据。我有read the documentation和this 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))
这将输出:
蓝色代表数据橙色代表适合。很明显我做错了什么。有什么建议吗?你知道吗
如果没有为参数
p0
的初始猜测提供值,则假定每个参数的值为1
。从文档中:由于您的数据具有非常大的x值和非常小的y值,
1
的初始猜测与实际解决方案相差甚远,因此优化器不会收敛。您可以通过提供合适的初始参数值来帮助优化器,这些初始参数值可以从数据中猜测/近似:A = (y.max() - y.min()) / 2
C = (y.max() + y.min()) / 2
pi
,我们可以用这个数乘以pi
:y_shifted = y - offset; oemga = np.pi * np.sum(y_shifted[:-1] * y_shifted[1:] < 0) / (t.max() - t.min())
dphi = 0
总之,可以使用以下初始参数猜测:
它提供了以下拟合函数:
相关问题 更多 >
编程相关推荐