两个仅含0、1的numpy数组逐元素比较分类的最高效计算方法
可行实现方案
以下两种方案均为numpy向量化实现,完全避免Python原生循环,计算效率远高于逐索引遍历。
方案1:算术查找表法(性能最优、代码最简洁)
利用两个数组均为0/1取值的特性,先计算加权组合值,再通过预定义查找表直接映射到目标分类编码:
import numpy as np prediction = np.array([1, 0, 0, 1, 1, 0, 1, 1, 1]) groundtrue = np.array([1, 0, 1, 0, 1, 1, 0, 0, 1]) # 查找表索引对应规则:prediction*2 + groundtrue 的计算结果 lookup = np.array([2, 3, 4, 1]) comparison = lookup[prediction * 2 + groundtrue]
输出结果完全符合预期:array([1, 2, 3, 4, 1, 3, 4, 4, 1])
方案2:嵌套np.where法(可读性更高)
如果后续需要调整分类规则,嵌套条件判断的写法更容易理解和修改:
comparison = np.where( (prediction == 1) & (groundtrue == 1), 1, np.where( (prediction == 0) & (groundtrue == 0), 2, np.where( (prediction == 0) & (groundtrue == 1), 3, 4 ) ) )
内容的提问来源于stack exchange,提问作者SantoshGupta7
相关产品推荐
相关产品推荐

