[英]python warnings.filterwarnings does not ignore DeprecationWarning from 'import sklearn.ensemble'
I am trying to silence the DeprecationWarning with the following method.我正在尝试使用以下方法使 DeprecationWarning 静音。
import warnings
warnings.filterwarnings(action='ignore')
from sklearn.ensemble import RandomForestRegressor
However, it still shows:但是,它仍然显示:
DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported.
弃用警告:numpy.core.umath_tests 是一个内部 NumPy 模块,不应导入。 It will be removed in a future NumPy release.
它将在未来的 NumPy 版本中删除。 from numpy.core.umath_tests import inner1d
从 numpy.core.umath_tests 导入 inner1d
Why does this happen, and how can I fix it?为什么会发生这种情况,我该如何解决?
I'm running this on python 3.6.6, numpy 1.15.0 and scikit-learn 0.19.2, and adding category=DeprecationWarning
didn't help.我在 python 3.6.6、numpy 1.15.0 和 scikit-learn 0.19.2 上运行它,并且添加
category=DeprecationWarning
没有帮助。
The reason this happens is that Scikit resets your DeprecationWarning filter when you import it :发生这种情况的原因是 Scikit 在您导入时会重置您的 DeprecationWarning 过滤器:
# Make sure that DeprecationWarning within this package always gets printed
warnings.filterwarnings('always', category=DeprecationWarning,
module=r'^{0}\.'.format(re.escape(__name__)))
Sneaky!偷偷摸摸!
The only fix I've found is to temporarily suppress stderr:我发现的唯一解决方法是暂时抑制 stderr:
import os
import sys
sys.stderr = open(os.devnull, "w") # silence stderr
from sklearn.ensemble import RandomForestRegressor
sys.stderr = sys.__stderr__ # unsilence stderr
where sys.__stderr__
refers to the system's actual stderr (as opposed to sys.stderr
, which just tells Python where to print stderr to).其中
sys.__stderr__
指的是系统的实际 stderr(与sys.stderr
相反,它只是告诉 Python 将 stderr 打印到哪里)。
Not sure if this would work.不确定这是否可行。 But I tried to recreate the warning and it was silenced so try this:
但我试图重新创建警告并且它被静音所以试试这个:
import logging
logging.captureWarnings(True)
According to the docs "If capture is True, warnings issued by the warnings module will be redirected to the logging system. "根据文档“如果捕获为真,警告模块发出的警告将被重定向到日志系统。”
Here's what I did:这是我所做的:
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)
Warning wasn't thrown.没有发出警告。
logging.captureWarnings(False)
warnings.warn("This is a DeprecationWarning",category=DeprecationWarning)
Output:输出:
.../ipython:2: DeprecationWarning: This is a DeprecationWarning
Yet another heavy-hand approach.又是一种严厉的做法。
import warnings as wa
wa.warn_explicit = wa.warn = lambda *_, **__: None
Indeed, overwriting ~.warn_explicit
and ~.warn
does the job once for all wherever it is called.事实上,覆盖
~.warn_explicit
和~.warn
一次就可以完成这项工作,无论它被调用到哪里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.