我可以使用
warnings
库,通过 scikit-learn 的多个选项关闭警告:
# After the imports
warnings.filterwarnings(action='ignore')
# Or in the code
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# do stuff
但是,一旦 n_jobs 参数高于 1(由于多重处理?),这不适用于分类器。以下代码示例说明了这一点:
import numpy as np
from sklearn.multiclass import OneVsRestClassifier
from sklearn.linear_model import LogisticRegression
import warnings
import logging
logger = logging.getLogger()
for n_job in [1, 2]:
print("START")
print("n_jobs =", n_job)
clf = OneVsRestClassifier(LogisticRegression(solver="liblinear", multi_class="ovr"), n_jobs=n_job)
x_train = np.array([[1,1], [0,1], [0,0], [1,5], [2,1], [3,1]])
y_train = np.array([[False, False, True], [False, False, True], [True, False, False], [True, False, False], [True, False, True], [True, False, False]])
with warnings.catch_warnings():
warnings.simplefilter("ignore")
clf.fit(x_train, y_train) # "UserWarning: Label not 1 is present in all training examples."
print("END")
print()
输出:
START
n_jobs = 1
END
START
n_jobs = 2
UserWarning: Label not 1 is present in all training examples.
END
如何在 n_jobs > 1 时禁用警告?
编辑:因为它可能与
multiprocessing
有关,我可能会补充一点,我在linux上使用python 3.6运行了这个脚本。
发现同样的问题,答案嵌入此处 如何消除所有 sklearn 警告
除了警告忽略之外,还可以使用os设置PYTHONWARNINGS变量
import warnings
import os
warnings.filterwarnings('ignore')
os.environ['PYTHONWARNINGS'] = 'ignore