Sreejith Menon Sreejith Menon - 1 year ago 144
Python Question

Python - Replacing warnings with a simple message

I have built a few off-the-shelf classifiers from

and there are some expected scenarios where I know the classifier is bound to perform badly and not predict anything correctly. The sklearn.svm package runs without an error but raises the following warning.

~/anaconda/lib/python3.5/site-packages/sklearn/metrics/ UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 due to no predicted samples.
'precision', 'predicted', average, warn_for)

I wish to suppress this warning and instead replace with a message to
, say for instance,
"poor classifier performance"

Is there any way to suppress
in general?

Answer Source

Suppressing all warnings is easy with -Wignore (see warning flag docs)

The warnings module can do some finer-tuning with filters (ignore just your warning type).

Capturing just your warning (assuming there isn't some API in the module to tweak it) and doing something special could be done using the warnings.catch_warnings context manager and code adapted from "Testing Warnings":

import warnings

class MyWarning(Warning):

def something():
    warnings.warn("magic warning", MyWarning)

with warnings.catch_warnings(record=True) as w:
    # Trigger a warning.
    # Verify some things
    if ((len(w) == 1) 
            and issubclass(w[0].category, MyWarning) 
            and "magic" in str(w[-1].message)):
        print('something magical')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download