I have a small problem with my Python code when I try to fit a beta function to a few points. The problem is that either the solution does not converge (and the result coefficients are nans
), or it does nothing (at the results stay the same as my initial guess), or it apparently fits, but then the fit is not similar to the data points at all.
I have been reading similar posts about beta function and about curve_fit
, because both are discussed questions in the stackoverflow literature, but I have not been able to find a solution to the specific problem I have, so I was wondering if you could give me some ideas.
I have a set of points:
x = np.array([0.1, 0.3, 0.5, 0.7, 0.9, 1.1])
y = np.array([0.45112234, 0.56934313, 0.3996803 , 0.28982859, 0.19682153,
0.]
and then I try to fit them with the gamma
function using curve_fit
as follows:
from scipy.optimize import curve_fit
from scipy.special import gamma as gamma
def betafunc(x,a,b,cst):
return cst*gamma(a+b) * (x**(a-1)) * ((1-x)**(b-1)) / ( gamma(a)*gamma(b) )
popt2,pcov2 = curve_fit(betafunc,x,y,p0=(0.5,1.5,0.5))
And there is where my problem arises, because depending on my initial guess, I get either popt2=[nan,nan,nan]
, or popt2=p0
, or a few times values that, when plotted, do not mimic the data at all.
I also know the beta function is for 0 < x < 1, so I have tried re-scaling the points, or just removing the last point of my data, but that does not well either. Adding errors to curve fit or, as mentioned, changing the initial parameters, also does not help.
Also I thought it could be just the fact that I have 3 free parameters and 4 or 5 points, but, as shown in the figure... ,
...I have already fitted another profile (that also uses three free parameters), and there is not problem with it, so I do not understand why this other beta profile does not work. Any guidance is warmly appreciated!