繁体   English   中英

python warnings.filterwarnings 不会忽略“import sklearn.ensemble”中的 DeprecationWarning

[英]python warnings.filterwarnings does not ignore DeprecationWarning from 'import sklearn.ensemble'

我正在尝试使用以下方法使 DeprecationWarning 静音。

import warnings
warnings.filterwarnings(action='ignore')
from sklearn.ensemble import RandomForestRegressor

但是,它仍然显示:

弃用警告:numpy.core.umath_tests 是一个内部 NumPy 模块,不应导入。 它将在未来的 NumPy 版本中删除。 从 numpy.core.umath_tests 导入 inner1d

为什么会发生这种情况,我该如何解决?

我在 python 3.6.6、numpy 1.15.0 和 scikit-learn 0.19.2 上运行它,并且添加category=DeprecationWarning没有帮助。

发生这种情况的原因是 Scikit 在您导入时会重置您的 DeprecationWarning 过滤器

# Make sure that DeprecationWarning within this package always gets printed
warnings.filterwarnings('always', category=DeprecationWarning,
                        module=r'^{0}\.'.format(re.escape(__name__)))

偷偷摸摸!

我发现的唯一解决方法是暂时抑制 stderr:

import os
import sys
sys.stderr = open(os.devnull, "w")  # silence stderr
from sklearn.ensemble import RandomForestRegressor
sys.stderr = sys.__stderr__  # unsilence stderr

其中sys.__stderr__指的是系统的实际 stderr(与sys.stderr相反,它只是告诉 Python 将 stderr 打印到哪里)。

不确定这是否可行。 但我试图重新创建警告并且它被静音所以试试这个:

import logging
logging.captureWarnings(True)

根据文档“如果捕获为真,警告模块发出的警告将被重定向到日志系统。”

这是我所做的:

import logging
import re
import warnings
logging.captureWarnings(True)
warnings.filterwarnings('always', category=DeprecationWarning,
                        module=r'^{0}\.'.format(re.escape(__name__)))
warnings.warn("This is a DeprecationWarning",category=DeprecationWarning)

没有发出警告。

logging.captureWarnings(False)
warnings.warn("This is a DeprecationWarning",category=DeprecationWarning)

输出:

.../ipython:2: DeprecationWarning: This is a DeprecationWarning

又是一种严厉的做法。

import warnings as wa
wa.warn_explicit = wa.warn = lambda *_, **__: None

事实上,覆盖~.warn_explicit~.warn一次就可以完成这项工作,无论它被调用到哪里。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM