Scikit-learn 计算错误 recall_score

Scikit-learn incorrectly calculating recall_score

在 jupyterlab 中使用 scikit-learn 版本 0.22.1。但是,我无法提供最小的可重现示例,希望这没问题,因为它更像是一个概念性问题。

我正在构建分类模型。我在 X 中有我的特征,在 y 中有我的目标变量。我拟合逻辑回归模型并计算预测:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

from sklearn.linear_model import LogisticRegression
logmodel = LogisticRegression(solver='liblinear')
logmodel.fit(X_train, y_train)

predictions = logmodel.predict(X_test)

现在我想查看混淆矩阵、准确率得分、精确率得分和召回率得分。所以我 运行 以下内容:

from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score
print(f"Confusion matrix: \n {confusion_matrix(y_test, predictions)}")
print(f"Accuracy: \t {accuracy_score(y_test, predictions):.2%}")
print(f"Precision: \t {precision_score(y_test, predictions):.3f}")
print(f"Recall: \t {recall_score(y_test, predictions):.3f}")

>> Confusion matrix:
>> [[128838     54]
>>  [  8968    279]]
>> Accuracy:    93.47%
>> Precision:   0.838
>> Recall:      0.030

召回分数应为 TP / (TP + FN) = 128838 / (128838 + 8968) = 0.934923008。为什么 sklearn 给我 0.03 的召回?是我算错了,还是 recall_score 的工作方式与我预期的不同?

编辑:不小心输入了 TP / (TP+FP) 而不是上面的。更正。

您正在计算 class 0 的召回率。

这里的召回率(顺便说一句,你混淆了精度)是 R = 279/(279+8968) = 0.03

精度为 P = 279/(279+54) = 0.83

这里的矩阵是

---------------------------
|      x    |true 0  |true 1|
---------------------------
|predicted 0| 128838 |  8968|
|predicted 1|   54   |  279 |

意思是:

  • TP = 279

  • FP = 54

  • FN = 8968

  • TN = 128838

而不是相反。