You need to enable JavaScript to run this app. 如何通过NumPy对比两个数组,提取不同类别预测错误的索引
优惠活动
大模型
产品
解决方案
定价
更多

如何通过NumPy对比两个数组,提取不同类别预测错误的索引

实现方法

你可以通过NumPy的np.where()结合布尔掩码直接筛选符合要求的索引,实现代码如下:

import numpy as np

correct   = np.array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2])
predicted = np.array([1, 1, 2, 1, 1, 1, 2, 2, 1, 2])

# 取真实值为1、预测错误的索引,转Python列表
incorrect_ones = np.where((correct == 1) & (predicted != 1))[0].tolist()
# 取真实值为2、预测错误的索引,转Python列表
incorrect_twos = np.where((correct == 2) & (predicted != 2))[0].tolist()

print(incorrect_ones) # 输出 [2]
print(incorrect_twos) # 输出 [5, 8]

代码说明

  • 布尔掩码(correct == 1) & (predicted != 1)会逐位判断是否满足「真实值为1且预测错误」的条件,返回等长的布尔数组
  • np.where()传入布尔数组时会返回满足条件的索引元组,一维数组只需要取元组的第一个元素[0]即可得到索引数组
  • 调用tolist()可以把NumPy数组转为Python原生列表,和你预期的输出格式完全匹配。如果不需要转列表,去掉该方法即可得到NumPy格式的索引数组

你也可以用np.argwhere实现同样效果:

incorrect_ones = np.argwhere((correct == 1) & (predicted != 1)).flatten().tolist()
incorrect_twos = np.argwhere((correct == 2) & (predicted != 2)).flatten().tolist()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 04:24:03