Skip to content Skip to sidebar Skip to footer

Fitting Hyperbolic And Harmonic Functions With Curvefit

I have a problem working with curvefit function. Here I have a code with two functions to work with. The first is an hyperbolic function. The second is the same but with one param

Solution 1:

It's a classic problem. The curve_fit algorithm starts from an initial guess for the arguments to be optimized, which, if not supplied, is simply all ones.

That means, when you call

popt, pcov = optimize.curve_fit(funcHar, xData, yData)

the first attempt for the fitting routine will be to assume

funcHar(xData, qi=1, di=1)

If you haven't specified any of the other options, the fit will be poor, as evidenced by the large variances of the parameter estimates (check the diagonal of pcov and compare it to the actual values returned in popt).

In many cases, the situation is solved by supplying an intelligent guess. From your HAR-model, I gather that the values around x==0 are the same in size as qi. So you could supply an initial guess of p0 = (pir[0], 1), which will already lead to a satisfying solution. You could also call it with

popt, pcov = optimize.curve_fit(funcHar, ptp, pir, p0=(0, 1))

which leads to the same result. So the problem is just that the algorithm finds a local minimum.

An alternative would've been to supply a different factor, the "parameter determining the initial step bound":

popt, pcov = optimize.curve_fit(funcHar, ptp, pir, p0=(1, 1), factor=1)

In this case, even with the (default) initial guess of p0=(1,1), it gives the same resulting fit.

Remember: fitting is an art, not a science. Often times, by analyzing the model you want to fit, you could already supply a good initial guess.

I can't speak for the algorithm used in the commercial program. If it is open-source (unlikely), you could have a look to see what they do.


Post a Comment for "Fitting Hyperbolic And Harmonic Functions With Curvefit"