如何计算 K 折交叉验证的不平衡数据集的精度、召回率和 f1 分数?

How to compute precision,recall and f1 score of an imbalanced dataset for K fold cross validation?

我有一个包含二元分类的不平衡数据集problem.I已经构建了随机森林分类器并使用了 10 折的 k 折交叉验证。

kfold = model_selection.KFold(n_splits=10, random_state=42)
model=RandomForestClassifier(n_estimators=50) 

我得到了10折的结果

results = model_selection.cross_val_score(model,features,labels, cv=kfold)
print results
[ 0.60666667  0.60333333  0.52333333  0.73        0.75333333  0.72        0.7
  0.73        0.83666667  0.88666667]

我通过计算结果的均值和标准差来计算准确度

print("Accuracy: %.3f%% (%.3f%%)") % (results.mean()*100.0, results.std()*100.0)
Accuracy: 70.900% (10.345%)

我的预测如下

predictions = cross_val_predict(model, features,labels ,cv=10)

由于这是一个不平衡的数据集,我想计算每个折叠的精度、召回率和 f1 分数,并对结果进行平均。 如何计算python?

中的值

当你使用cross_val_score方法时,你可以指定,你可以计算每折的分数:

from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score

scoring = {'accuracy' : make_scorer(accuracy_score), 
           'precision' : make_scorer(precision_score),
           'recall' : make_scorer(recall_score), 
           'f1_score' : make_scorer(f1_score)}

kfold = model_selection.KFold(n_splits=10, random_state=42)
model=RandomForestClassifier(n_estimators=50) 

results = model_selection.cross_val_score(estimator=model,
                                          X=features,
                                          y=labels,
                                          cv=kfold,
                                          scoring=scoring)

交叉验证后,您将获得 results 字典,其键为:'accuracy'、'precision'、'recall'、'f1_score',其中存储指标值特定指标的每一次折叠。对于每个指标,您可以使用 np.mean(results[value])np.std(results[value]) 计算平均值和标准值,其中值 - 您指定的指标名称之一。