You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Sklearn通过10折交叉验证获取10个独立混淆矩阵

获取交叉验证每个折的混淆矩阵

你的问题出在cross_val_predict会把所有折的预测结果合并成一个数组,最后只能得到全局混淆矩阵。要获取每个折单独的混淆矩阵,需要手动遍历交叉验证的每个折,分别完成训练、预测和矩阵计算。

以下是修改后的实现代码:

from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import KFold
import numpy as np

target = df["class"]
features = df.drop("class", axis=1)

# 统一打乱数据(和你原代码的随机操作保持一致)
shuffled_indices = np.random.RandomState(0).permutation(len(df))
features = features.iloc[shuffled_indices]
target = target.iloc[shuffled_indices]

# 初始化10折交叉验证器
kf = KFold(n_splits=10, shuffle=False, random_state=0)  # 已提前打乱数据,这里无需重复shuffle
tree = DecisionTreeClassifier(random_state=0)

# 遍历每个折,计算并保存混淆矩阵
fold_conf_matrices = []
for fold_num, (train_idx, test_idx) in enumerate(kf.split(features), 1):
    # 拆分当前折的训练/测试数据
    X_train, X_test = features.iloc[train_idx], features.iloc[test_idx]
    y_train, y_test = target.iloc[train_idx], target.iloc[test_idx]
    
    # 训练模型并预测测试集
    tree.fit(X_train, y_train)
    y_pred = tree.predict(X_test)
    
    # 计算当前折的混淆矩阵
    conf_matrix = confusion_matrix(y_test, y_pred)
    fold_conf_matrices.append(conf_matrix)
    print(f"第 {fold_num} 折的混淆矩阵:\n", conf_matrix)

# 所有折的混淆矩阵已存入fold_conf_matrices列表,可后续调用分析

关键细节说明

  • 提前统一打乱数据后,KFold的shuffle设为False,避免重复打乱导致数据分布不一致;若不想提前打乱,也可将KFold的shuffle=True,让拆分前自动打乱。
  • 每个折都独立训练全新的决策树模型,符合交叉验证"各折模型独立训练"的标准逻辑。
  • 你原代码中先手动拆分80%训练集、20%测试集,却又用全量数据做交叉验证,这可能存在逻辑矛盾:如果是做交叉验证,无需提前手动拆分;如果要留一部分数据做最终测试,交叉验证应仅在训练集上执行,避免数据泄露。

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:45:45