问题描述
Here is my data in excel 我想将此数据拟合为正弦曲线
这是我的代码,
#Fitting function
def func(x,offset,A,freq,phi):
return offset + A * np.sin(freq * x + phi)
#Experimental x and y data points
# test_df is the input excel df
x_data = test_df['x_data']
y_data = test_df['y_data']
#Plot input data points
plt.plot(x_data,y_data,'bo',label='experimental-data')
# Initial guess for the parameters
initial_guess = [.38,2.3,.76,2.77]
#Perform the curve-fit
popt,pcov = curve_fit(func,x_data,initial_guess)
print(popt)
#x values for the fitted function
x_fit = np.arange(0.0,31,0.01)
#Plot the fitted function
plt.plot(x_fit,func(x_fit,*popt),'r')
plt.show()
这是图形。 我认为这不是最佳选择。我想提出改善曲线拟合的建议。
解决方法
好吧,这似乎不是一个数学函数,例如对于参数值15
,您可能有多个值(f(x)等于什么?)。因此,这将不是经典
在这种情况下插值。如果您可以通过某种方式规格化数据,即根据数据进行功能化,则可以使用numpy。
最简单的方法是在参数值相等的情况下添加一些小的干扰。让我们来看一个数据示例:
4 0.0326
4 0.014
4 -0.0086
4 0.0067
因此,如您所见,您无法确定f(4)的关系值是多少。如果您想稍微干扰一下参数,例如:
3.9 -0.0086
3.95 0.0067
4 0.014
4.05 0.0326
以此类推,对于数据文件中的所有此类示例。最简单的方法是通过它们的x
参数对这些值进行分组,排序和打扰。
那显然会引入一些错误,但是,好吧……无论如何,您都在进行曲线拟合,对吧?
要公式化正弦,必须知道幅度,频率和相位:f(x)= A * sin(F * x + p)其中A
是幅度,F
是频率,p
是相位。如果您准备了适当的数据集,Numpy会为此提供专用方法:
How do I fit a sine curve to my data with pylab and numpy?