Skip to main content
 首页 » 编程设计

python之使用 sklearn 计算 F1 分数

2024年10月17日11wuhuacong

我想弄清楚为什么 F1 分数是 sklearn 中的分数。我知道它的计算方式是:

F1 = 2 * (precision * recall) / (precision + recall) 

我的代码:

from sklearn.metrics import f1_score, precision_score, recall_score 
... 
fmeasure1 = f1_score(true_output, predicted_output, average="macro") 
fmeasure2 = f1_score(true_output, predicted_output, average="micro") 
 
precision = precision_score(true_output, predicted_output, average="macro") 
recall = recall_score(true_output, predicted_output, average="macro") 
 
print 2*(precision*recall)/(precision + recall), fmeasure1, fmeasure2 

我得到的数据值是:

0.785744255639 0.769527615775 0.984532095901 

我不明白为什么这三个值彼此不同。我试过阅读文档 here ,但我还是迷路了。

我的数据集是多类的,本质上是高度不平衡的。此处的哪个值是“正确”值,推而广之,我应该使用平均值参数(即无、微观、宏观、权重)中的哪些?

谢谢,任何见解都将非常有值(value)。

请您参考如下方法:

查看返回值:

Returns:     
f1_score : float or array of float, shape = [n_unique_labels] 
F1 score of the positive class in binary classification or weighted average of the F1 scores of each class for the multiclass task. 

每个值都是该特定类别的 F1 分数,因此可以用不同的分数预测每个类别。

关于什么是最好的分数。

best value at 1 and worst score at 0.[ \[From documentation\]][1] 

附带说明一下,如果您处理的是高度不平衡的数据集,则应考虑研究抽样方法,或者在允许的情况下简单地从现有数据中进行子抽样。

如果你想要预测的平均值average='weighted':

sklearn.metrics.f1_score(y_true, y_pred, labels=None, pos_label=1, average='weighted')