使用 cross_validate 生成混淆矩阵

Mul*_*loy 3 python machine-learning confusion-matrix scikit-learn cross-validation

我试图弄清楚如何使用 cross_validate 生成混淆矩阵。我可以使用迄今为止的代码打印出分数。

# Instantiating model
model = DecisionTreeClassifier()

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

# 10-fold cross validation
scores = cross_validate(model, X, y, cv=10, scoring=scoring)

print("Accuracy (Testing):  %0.2f (+/- %0.2f)" % (scores['test_accuracy'].mean(), scores['test_accuracy'].std() * 2))
print("Precision (Testing):  %0.2f (+/- %0.2f)" % (scores['test_precision'].mean(), scores['test_precision'].std() * 2))
print("Recall (Testing):  %0.2f (+/- %0.2f)" % (scores['test_recall'].mean(), scores['test_recall'].std() * 2))
print("F1-Score (Testing):  %0.2f (+/- %0.2f)" % (scores['test_f1_score'].mean(), scores['test_f1_score'].std() * 2))
Run Code Online (Sandbox Code Playgroud)

但我正在尝试将这些数据放入混淆矩阵中。我可以使用 cross_val_predict 制作混淆矩阵 -

y_train_pred = cross_val_predict(model, X, y, cv=10)
confusion_matrix(y, y_train_pred)
Run Code Online (Sandbox Code Playgroud)

这很棒,但由于它正在进行自己的交叉验证,因此结果不会匹配。我只是在寻找一种方法来产生两者匹配的结果。

任何帮助或指示都会很棒。谢谢!

Ben*_*ger 5

我认为最好的方法是将混淆矩阵定义为记分器,而不是您定义的其他矩阵,或者除了您定义的其他矩阵之外。幸运的是,这是用户指南中的一个示例;请参阅此处的第三个项目符号:

def confusion_matrix_scorer(clf, X, y):
    y_pred = clf.predict(X)
    cm = confusion_matrix(y, y_pred)
    return {'tn': cm[0, 0], 'fp': cm[0, 1],
            'fn': cm[1, 0], 'tp': cm[1, 1]}
cv_results = cross_validate(svm, X, y, cv=5,
                            scoring=confusion_matrix_scorer)
Run Code Online (Sandbox Code Playgroud)

然后cv_results['test_tp'](等)是每个折叠的真阳性数量列表。现在您可以汇总最适合您的混淆矩阵。


首先想到的是另一种方法,我将在此处添加它,以防它有助于理解 sklearn 如何处理事物。但我绝对认为第一种方法更好。

您可以设置return_estimatorin cross_validate,在这种情况下,返回的字典有一个键estimator,其值为拟合模型的列表。不过,您仍然需要能够找到相应的测试折叠。为此,您可以cv手动定义对象(例如cv = StratifiedKFold(10)cross_validate(..., cv=cv);然后cv仍将包含用于进行分割的相关数据。因此您可以使用拟合的估计器对适当的测试折叠进行评分,生成混淆矩阵。或者您可以使用cross_val_predict(..., cv=cv),但在在那一点上你重复拟合,所以你可能应该跳过cross_validate并自己做循环。