如何计算不平衡数据集的精度,召回率和f1分数以进行K折交叉验证? [英] How to compute precision,recall and f1 score of an imbalanced dataset for K fold cross validation?

查看:266
本文介绍了如何计算不平衡数据集的精度,召回率和f1分数以进行K折交叉验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含二进制分类问题的不平衡数据集,我构建了Random Forest分类器并使用了10倍的k倍交叉验证.

I have an imbalanced dataset containing binary classification problem.I have built Random Forest Classifier and used k fold cross validation with 10 folds.

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]

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

I have calculated accuracy by taking mean and standard deviation of the results

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中计算值?

Since this is an imbalanced dataset,I would like to calculate precision,recall and f1 score of each fold and average the results. How to calculate the values in python?

推荐答案

当您使用 cross_val_score 方法时,可以指定每次折叠可以计算的得分:

When you use cross_val_score method, you can specify, which scorings you can calculate on each fold:

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])计算平均值和标准价值,其中value-指定指标名称的名称.

After cross validation, you will get results dictionary with keys: 'accuracy', 'precision', 'recall', 'f1_score', which store metrics values on each fold for certain metric. For each metric you can calculate mean and std value by using np.mean(results[value]) and np.std(results[value]), where value - one of your specified metric name.

这篇关于如何计算不平衡数据集的精度,召回率和f1分数以进行K折交叉验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆