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

运行混淆矩阵绘制代码时遇ValueError错误,求解决方案

解决ValueError: Shape of passed values is (14, 14), indices imply (15, 15)错误

问题场景

运行以下代码时触发错误:

ValueError: Shape of passed values is (14, 14), indices imply (15, 15)

代码片段:

def plot_confusion_matrix(cm):
    cm = cm[::-1]
    cm = pd.DataFrame(cm, columns=classes, index=classes[::-1])

    fig = ff.create_annotated_heatmap(z=cm.values, x=list(cm.columns), y=list(cm.index), colorscale='ice', showscale=True, reversescale=True)
    fig.update_layout(width=500, height=500, title='Confusion Matrix', font_size=16)
    fig.show()

import plotly.figure_factory as ff
plot_confusion_matrix(cm)

核心原因

错误本质是混淆矩阵cm的维度与classes列表的长度不匹配:cm是14×14的二维数组,但classes包含15个类别,导致创建DataFrame时,列/索引的长度(15)与矩阵元素的维度(14)冲突。

解决步骤

  1. 确认维度匹配性
    在函数开头添加调试代码,明确两者的维度:

    def plot_confusion_matrix(cm):
        print(f"混淆矩阵形状: {cm.shape}")
        print(f"类别数量: {len(classes)}")
        # 原有代码...
    
  2. 对齐维度

    • 如果classes多了一个无效类别:直接删除多余的类别项,确保len(classes)等于cm.shape[0](或cm.shape[1],混淆矩阵是方阵)。
    • 如果cm维度不足:检查混淆矩阵的生成逻辑(比如分类模型的输出类别数是否与classes一致,是否漏统计了某个类别)。
    • 临时兼容(仅当确认classes长度错误时使用):截取classes的匹配部分,比如classes = classes[:14],但需保证截取逻辑符合业务需求。
  3. 容错式创建DataFrame
    可以修改DataFrame的创建代码,自动适配矩阵维度,避免硬编码长度:

    def plot_confusion_matrix(cm):
        cm = cm[::-1]
        # 自动匹配矩阵的行列数,避免维度冲突
        cm = pd.DataFrame(
            cm,
            columns=classes[:cm.shape[1]],
            index=classes[::-1][:cm.shape[0]]
        )
        # 原有代码...
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:20:30