【问题标题】:Python how to filter specific warning?Python如何过滤特定的警告?
【发布时间】:2020-09-20 13:33:23
【问题描述】:

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

有没有类似这种过滤器特定警告的方法?

【问题讨论】:

  • 您是否确认可以安全地忽略该警告,并且您的代码中没有任何内容需要修复以避免此警告?

标签: python warnings suppress-warnings


【解决方案1】:

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

from scipy.linalg import LinAlgWarning

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

【讨论】:

  • 没有变量LinAlgWarning。这里必须有不同的方式。
  • 需要导入 LinAlgWarning from scipy.linalg import LinAlgWarning warnings.filterwarnings("ignore",category= LinAlgWarning, module='sklearn')
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2019-02-24
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 2019-09-13
    • 1970-01-01
    • 2021-09-24
    • 2020-01-27
    相关资源
    最近更新 更多