Python如何过滤特定警告?

Python how to filter specific warning?

提问人:BhishanPoudel 提问时间:9/20/2020 更新时间:4/23/2022 访问量:5121

问:

如何在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 警告 suppress-warnings

评论

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

答:

14赞 badreelal patidar 9/20/2020 #1

您必须将 category 作为 WarningClass 传递,而不是在 String 中:

from scipy.linalg import LinAlgWarning

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

评论

0赞 BhishanPoudel 9/21/2020
没有变量。这里必须有一种不同的方式。LinAlgWarning
2赞 badreelal patidar 9/21/2020
您需要导入 LinAlgWarningfrom scipy.linalg import LinAlgWarning warnings.filterwarnings("ignore",category= LinAlgWarning, module='sklearn')