首页 > 解决方案 > Scipy.Optimize.Curve_Fit Not Fitting Cos^2 Well

问题描述

I am trying to fit a curve of the form

acos^2(x+b)+c

using scipy's curve_fit routine but I have not been able to get it to find good parameters. The fit doesn't seem to find the right amplitude or period.

I've tried modifying the fit function and changing the initial guesses to math the data. Below is the fit function and the fitting routine.

def fit(x, a, phi, b):
    return (a*abs(math.cos(x+phi)**2))+b

#Vectorizing fit function to accept list input
fit_v = np.vectorize(fit)

params1, covs1 = optimize.curve_fit(fit_v, data_1_x_calibrated, data_1_y, p0=[20,30,90])

The data is plotted using the following code

#Plotting Fit 1
fit_1_y_data = []
for i in range(len(data_1_x)):
    fit_1_y_data.append(params1[0]*math.cos(data_1_x_calibrated[i]+params1[1])**2+params1[2])
plt.plot(data_1_x_calibrated, fit_1_y_data, label="Fit")
plt.plot(data_1_x_calibrated, data_1_y, "r", label = "Data")
plt.legend()

The result is the following: Data and Fit Plot

Any help would be appreciated.

标签: pythonoptimizationscipy

解决方案


推荐阅读