Sreejith Menon Sreejith Menon - 4 months ago 22
Python Question

Python - Replacing warnings with a simple message

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

sklearn
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/classification.py:1074: 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
stdout
, say for instance,
"poor classifier performance"
.

Is there any way to suppress
warnings
in general?

Answer

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):
    pass

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

with warnings.catch_warnings(record=True) as w:
    # Trigger a warning.
    something()
    # Verify some things
    if ((len(w) == 1) 
            and issubclass(w[0].category, MyWarning) 
            and "magic" in str(w[-1].message)):
        print('something magical')
Comments