Skip to main content
 首页 » 编程设计

python之如何使所有sklearn警告静音

2025年05月04日15zhujiabin

我在 sklearn 中使用 F1_score 指标。对于某些训练数据集,y=1(极少数情况)集的总数为零,F1_score 为零,这是正常的。但是 sklearn 给出了以下警告:

"UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 due to no predicted samples".

有谁知道如何消除这个警告?总的来说,我们可以在 sklearn 中消除各种警告吗?

请您参考如下方法:

借助 Python 中的 warnings 模块,您可以轻松地忽略警告。

import warnings 
warnings.filterwarnings('ignore')  

例如,

from sklearn.metrics import f1_score 
 
yhat = [0] * 100 
y = [0] * 90 + [1] * 10 
 
print(f1_score(y, yhat)) 

这将引发警告。为避免这种使用,

from sklearn.metrics import f1_score 
 
import warnings 
warnings.filterwarnings('ignore')  
 
yhat = [0] * 100 
y = [0] * 90 + [1] * 10 
 
print(f1_score(y, yhat)) 

这不会显示警告。