0

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?

1 Answer 1

2

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')
Sign up to request clarification or add additional context in comments.

1 Comment

That worked. I decided to capture all the warning that the snippet could generate and report with a generic message. with warnings.catch_warnings(record=True) as w: self.clfObj.fit(self.train_x,self.train_y) self.preds = list(self.clfObj.predict(self.test_x)) self.predProbabs = self.clfObj.predict_proba(self.test_x)[:,1] self.evalClassifierPerf() if len(w) >= 1: print("Poor Classifer detected")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.