'Python how to filter specific warning?

How to filter the specific warning for specific module in python?

MWE

ERROR:

cross_val_score(model, df_Xtrain,ytrain,cv=2,scoring='r2')

/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/_ridge.py:148: LinAlgWarning: Ill-conditioned matrix (rcond=3.275e-20): result may not be accurate.
  overwrite_a=True).T

My attempt

import warnings
warnings.filterwarnings(action='ignore',module='sklearn')

cross_val_score(model, df_Xtrain,ytrain,cv=2,scoring='r2')

This works but I assume it ignores all the warnings such as deprecation warnings. I would like to exclude only LinAlgWarning

Required Like

import warnings
warnings.filterwarnings(action='ignore', category='LinAlgWarning', module='sklearn')

Is there a way like this filter specific warning?



Solution 1:[1]

You have to pass category as a WarningClass not in a String:

from scipy.linalg import LinAlgWarning

warnings.filterwarnings(action='ignore', category=LinAlgWarning, module='sklearn')

Solution 2:[2]


More pythonic way to filter WARNING :


import logging
    
for name in logging.Logger.manager.loggerDict.keys():
    if ('LinAlgWarning' in name):
            logging.getLogger(name).setLevel(logging.CRITICAL)

#rest of the code starts here...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mr. Discuss
Solution 2 Safvan CK