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

10折交叉验证保存每折混淆矩阵报shape mismatch错误如何解决?

问题根因分析

1. 首次报错的核心错误

  • 索引选择错误:你把训练集样本索引train_index作为conf_matrix的下标,train_index的长度是总样本数的9/10(从报错信息可推得总样本为300,单折训练集共270条,对应索引长度270),而你初始化的conf_matrix是3行3列的二维数组,conf_matrix[train_index]会试图选中270行数据,和你要赋值的3×3混淆矩阵形状完全不匹配。
  • 存储逻辑错误:你初始化的单个3×3数组只能存一个混淆矩阵,无法存储10折的全部结果。

2. 第二次修改后仍报错的原因

你修改后的初始化代码conf_matrix = np.zeros((10,len(y_test),len(y_test)))仍然存在问题:

  • 维度定义错误:你用len(y_test)定义混淆矩阵的维度,len(y_test)是单折测试集的样本数(30条),但混淆矩阵的维度是由分类类别数决定的,你的场景是3分类对应3×3矩阵,和测试集样本数没有关联,因此你初始化出来的数组是10×30×30,和要赋值的3×3矩阵形状不匹配。
  • 索引错误未修复:你依然在使用train_index作为数组索引,索引出来的结果形状为270×30×30,和目标形状差距更大。
正确可运行代码
from sklearn.model_selection import KFold
import numpy as np
from sklearn.metrics import confusion_matrix

# 固定分类类别数、折数
n_classes = 3
n_splits = 10
kf = KFold(n_splits=n_splits, shuffle=True)
# 初始化形状为(10, 3, 3)的数组,10折每折对应一个3×3混淆矩阵
conf_matrix_list = np.zeros((n_splits, n_classes, n_classes))

# 用fold_idx记录当前折数,作为存储的下标
for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):
    X_train, X_test = X.iloc[train_index], X.iloc[test_index]
    y_train, y_test = y.iloc[train_index], y.iloc[test_index]
    
    model.fit(X_train, y_train)
    pred = model.predict(X_test)
    # 用折数作为索引赋值对应位置
    conf_matrix_list[fold_idx] = confusion_matrix(y_test, pred)

# 输出所有折的混淆矩阵
print(conf_matrix_list)
可选扩展功能

如果需要得到10折平均的混淆矩阵,直接对数组第一维求平均即可:

avg_conf_matrix = conf_matrix_list.mean(axis=0)
print(avg_conf_matrix)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:27:01