如何通过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
相关产品推荐
相关产品推荐

