SHOURIE MRSS
SHOURIE MRSS

Reputation: 11

Fitting cosine squared to points in python

I am trying to fit the cosine squared curve to the data that I have using curve_fit from scipy optimise. BUt unfortunately I am getting a straight line. Hoping that somebody would be able to help me.

import pylab as plb
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp
import numpy as np

x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])


def cosq(x,a,x0):
    return a*(np.cos(np.pi*x*x0)**2)

popt,pcov = curve_fit(cosq,x,y,p0=[1,1])

plt.plot(x,y,'b+:',label='data')
plt.plot(x,cosq(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Blu Blah')
plt.xlabel('Blu')
plt.ylabel('Blah')
plt.show()

I am getting the following graph with the straight line fit as the output

Upvotes: 0

Views: 1273

Answers (1)

Nils
Nils

Reputation: 930

I've noticed that when using curve_fit the starting parameters are very important and can lead to very different results. Therfore you should be able to get a better fit if you play around with your p0 values.

Additionally you can use bounds to constrain the optimization to a region such as:

popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1.]))

which, for instance, constraints the optimization to the region of 0 <= a <= 3, 0 <= x0 <= 1

For more details look at https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html

I hope that will help

Upvotes: 2

Related Questions