16

I am using scipy.optimize.curve_fit() in an iterative way.

My problem is that when ever it is unable to fit the parameters the whole program (and thus the iteration) stops, this is the error it gives:

RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 800.

I understand that why it has been unable to fit. My problem is that is there any way I can write the program in Python 3.2.2 that will ignore such occurrences and just continue?

Cleb
  • 25,102
  • 20
  • 116
  • 151
makhlaghi
  • 3,856
  • 6
  • 27
  • 34

1 Answers1

20

You can use standard Python exception handling to trap the error raised by curve_fit in cases where the optimization fails to find a solution. So something like:

try:
    popt,pcov = scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None)

except RuntimeError:
    print("Error - curve_fit failed")

That construct will let you catch and handle the error condition raised by curve_fit without having your program abort.

talonmies
  • 70,661
  • 34
  • 192
  • 269
  • 1
    Thank you very much. I am new to Python and this error was really bothering me. I read the manual on the try-except error handling procedure and understood it. Thanks again... – makhlaghi Feb 08 '12 at 01:16
  • 2
    So one quick word to wrap this up. Does an error like this (even when is raised to, say, `maxfev=2000`) mean that the fit is not possible, e.g., the curve we are trying to fit is not a good fit, or maybe not a fit at all? Ultimately, if you are testing a number of laws, is this error telling us that we should discard the function for which the error was raised? – FaCoffee May 13 '16 at 16:59