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

问题描述 投票:5回答:2

我试图用以下方法使DeprecationWarning保持沉默。

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

但是,它仍然显示:

DeprecationWarning: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没有帮助。

python scikit-learn suppress-warnings deprecation-warning
2个回答
2
投票

发生这种情况的原因是Scikit resets your DeprecationWarning filter when you import it

# 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)。


0
投票

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

import logging
logging.captureWarnings(True)

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

这是我做的:

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
© www.soinside.com 2019 - 2024. All rights reserved.