Python 如何过滤特定警告?

Python how to filter specific warning?

如何过滤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

我的尝试

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

必须点赞

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

是否有类似此过滤器特定警告的方法?

您必须将类别作为 WarningClass 传递,而不是在字符串中:

from scipy.linalg import LinAlgWarning

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

更多 pythonic 过滤方式警告 :


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...