# [SciPy-User] Curve fitting questions

josef.pktd@gmai... josef.pktd@gmai...
Tue Oct 19 13:04:24 CDT 2010

```On Tue, Oct 19, 2010 at 1:50 PM, Gökhan Sever <gokhansever@gmail.com> wrote:
> Hello,
>
> I am doing a few simple tests to see if I could estimate parameters
> from a function fitting using less number of inputs. Three inputs
> version works very well. The original version has 5 input points but
> the difference between 3 and 5 inputs estimations are very small in
> this case. I am wondering if two inputs case would be improved and if
> anything could be done to estimate somewhat reasonable parameters
> (with or without initial parameters provided) using 1 input only.
>
> The code is as follows:
>
> import numpy as np
> import matplotlib.pyplot as plt
> from scipy.optimize import curve_fit
>
> def my_ck(x, a, b):
>    return a*x**b

I think you could take logs and you would have a linear function in
param=log(x), and you could use linalg to solve for param, and then
transform back exp(param).  Or this would give you a starting value if
you want the non-linear optimization.

>
> ccn_ss1 = [0.27, 0.34, 0.57]
> ccn_conc1 = np.array([383.51237409766452, 424.82669523141652,
> 511.48197391304342])
>
> # works fine with defaults
> tfit1, pcov1 = curve_fit(my_ck, ccn_ss1, ccn_conc1)
>
> ccn_ss1 = [0.27, 0.34]
> ccn_conc1 = np.array([383.51237409766452, 424.82669523141652])
>
> # Fails with RuntimeError: Optimal parameters not found: The relative error
> # between two consecutive iterates is at most 0.000000
> # tfit1, pcov1 = curve_fit(my_ck, ccn_ss1, ccn_conc1)
>
> # Trying with the original estimates, ftol should be set to a big
> number otherwise this one fails as well.
> # Is there any different optimize function which will auto-discover the
> # initial parameters instead of supplying them explicitly?
> tfit2, pcov2 = curve_fit(my_ck, ccn_ss1, ccn_conc1, p0=tfit1, ftol=1)

Without knowing and using properties of the non-linear function and
choosing starting values well enough, there will always be numerical
problems like this, especially with very few observations.

>
> ccn_ss1 = 0.27
> ccn_conc1 = 383.51237409766452
> # One data point estimation fails with IndexError: index out of range for array
> tfit3, pcov3 = curve_fit(my_ck, ccn_ss1, ccn_conc1, p0=tfit1, ftol=1)

If you have one parameter to estimate and only one observations, then
you should be able to solve it exactly with one of the solvers/
rootfinders in scipy. optimize.

Josef

>
> Thanks.
>
> --
> Gökhan
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
```