python - 如何为每个交叉验证折叠显示混淆矩阵和报告(召回、精度、fmeasure)
问题描述
我正在尝试在 python 中执行 10 折交叉验证。我知道如何计算混淆矩阵和拆分测试的报告(例如拆分 80% 的训练和 20% 的测试)。但问题是我不知道如何计算混淆矩阵并报告每个折叠,例如当折叠 10 时,我只知道平均准确度的代码。
解决方案
为简单起见,这是一个包含乳腺癌数据和 3 倍 CV 的可重现示例:
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.model_selection import KFold
X, y = load_breast_cancer(return_X_y=True)
n_splits = 3
kf = KFold(n_splits=n_splits, shuffle=True)
model = DecisionTreeClassifier()
for train_index, val_index in kf.split(X):
model.fit(X[train_index], y[train_index])
pred = model.predict(X[val_index])
print(confusion_matrix(y[val_index], pred))
print(classification_report(y[val_index], pred))
结果是 3 个混淆矩阵和分类报告,每个 CV 折叠一个:
[[ 63 9]
[ 10 108]]
precision recall f1-score support
0 0.86 0.88 0.87 72
1 0.92 0.92 0.92 118
micro avg 0.90 0.90 0.90 190
macro avg 0.89 0.90 0.89 190
weighted avg 0.90 0.90 0.90 190
[[ 66 8]
[ 6 110]]
precision recall f1-score support
0 0.92 0.89 0.90 74
1 0.93 0.95 0.94 116
micro avg 0.93 0.93 0.93 190
macro avg 0.92 0.92 0.92 190
weighted avg 0.93 0.93 0.93 190
[[ 59 7]
[ 8 115]]
precision recall f1-score support
0 0.88 0.89 0.89 66
1 0.94 0.93 0.94 123
micro avg 0.92 0.92 0.92 189
macro avg 0.91 0.91 0.91 189
weighted avg 0.92 0.92 0.92 189
推荐阅读
- react-native - 不为 Android 构建,仅在实现 react-native-maps 后为 IOS
- python - 从字典中删除嵌套值列表中的特定值
- azure - Azure 自动化是否支持写入信息?
- amazon-web-services - 验证 ALB + AWS Cognito 时出现 500 错误
- web - 部署时有没有办法控制nuxt缓存?
- json - 将 JSON 解析为字符串键和值
- azure - 自动化 Azure Question 以生成基础架构
- visual-studio-code - 如何在 VScode mac 上调试特使单元测试
- java - 算术问答游戏中每次运行时游戏屏幕上的随机问题数
- android - Nativescript 模拟器安装头疼