![](/img/trans.png)
[英]Cannot supress Python Warnings with warnings.filterwarnings("ignore")
[英]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.