Catch optimization as an exception

I was just trying to catch the OptimizeWarning

one written out by the function scipy.optimize.curve_fit

, but I realized that it was not recognized as a valid exception.

This is a broken simple idea of ​​what I am doing:

from scipy.optimize import curve_fit
try:
    popt, pcov = curve_fit(some parameters)
except OptimizeWarning:
    print 'Maxed out calls.'
    # do something

      

I looked through the documents , but there was nothing there.

Am I missing something obvious or is it just not defined for some reason?

By the way, this is the complete warning I am getting and what I want to catch:

/usr/local/lib/python2.7/dist-packages/scipy/optimize/minpack.py:604: OptimizeWarning: Covariance of the parameters could not be estimated
  category=OptimizeWarning)

      

+3


source to share


1 answer


You can require Python to raise this warning as an exception using the following code:

import warnings
from scipy.optimize import OptimizeWarning

warnings.simplefilter("error", OptimizeWarning)
# Your code here

      

Problems with warnings

Unfortunately, warnings

Python has several problems that you need to be aware of.

Multiple filters



First, there may be multiple filters, so your alert filter might be overridden by something else. This is not so bad and you can work with a context manager catch_warnings

:

import warnings
from scipy.optimize import OptimizeWarning

with warnings.catch_warnings():
    warnings.simplefilter("error", OptimizeWarning)
    try:
        # Do your thing 
    except OptimizeWarning:
        # Do your other thing 

      

Raised times

Second, warnings are only raised once by default. If your alert has already been raised before you install the filter, you can change the filter, it will not raise the alert again.

Unfortunately, as far as I know, there is very little you can do about this. You will want to make sure you launch warnings.simplefilter("error", OptimizeWarning)

as early as possible.

+2


source







All Articles