pythonscikit-learn

How can I silence `UndefinedMetricWarning`?


How can I silence the following warning while running GridSearchCV(model, params, cv=10, scoring='precision', verbose=1, n_jobs=20, refit=True)?

/opt/dev/myenv/lib/python3.9/site-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. Use `zero_division` parameter to control this behavior.

I have tried without success:

import os, warnings
warnings.simplefilter("ignore")
warnings.filterwarnings("ignore")
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
os.environ["PYTHONWARNINGS"] = "ignore"

Solution

  • Try this code

    import warnings
    from sklearn.exceptions import UndefinedMetricWarning
    with warnings.catch_warnings():
        # Ignore only UndefinedMetricWarning
        warnings.filterwarnings("ignore", category=UndefinedMetricWarning)