我有一个包含二元分类问题的不平衡数据集。我构建了随机森林分类器并使用了 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])
计算平均值和标准值,其中值 - 1您指定的指标名称。
关于python - 如何计算 K 折交叉验证的不平衡数据集的精度、召回率和 f1 分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598301/