You need to enable JavaScript to run this app. 使用pandas DataFrame计算自定义性能指标触发KeyError如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用pandas DataFrame计算自定义性能指标触发KeyError如何解决

核心报错原因
  • 直接触发错误的问题:confusion_matrix方法中循环范围写的是len(df["proba"]),这里的df是全局变量,而非实例属性self.df。如果全局df的长度大于当前实例调用的df长度,就会出现循环索引超出实例df范围的问题,触发KeyError 2852。
  • 索引逻辑错误:你用y[val]、ypred[val]访问pandas Series元素时,默认是按索引标签匹配,不是按行位置匹配。如果你的df之前做过行删除、索引不是连续的0~2851序列,哪怕df长度是2852,也会出现标签不存在的报错。
  • 额外逻辑错误:你的混淆矩阵类别判定完全写反:y=1且预测为0是假阴性(FN),y=0且预测为0才是真阴性(TN),该错误会导致后续计算的指标A完全失真。
  • 拼写错误:_falseNegtive拼写错误,正确应为_falseNegative,避免后续调用属性时报错。
修复思路
  1. 修正循环范围的变量引用,统一使用实例属性self.df,不要调用全局变量。
  2. 替换按标签索引为按位置索引,使用.iloc[val]访问元素,或者直接用zip(y, ypred)遍历配对样本,从根源避免索引问题。
  3. 修正混淆矩阵的类别判定逻辑。
  4. 将阈值排序逻辑移到循环外,避免每次迭代都重复排序浪费性能。
  5. 确认setVariables()方法每次调用时都会将TP、TN、FP、FN四个计数变量重置为0,避免历史计数累加。
  6. 不要频繁对df执行drop操作,predict方法直接覆盖ypred列即可,不需要每次删除再生成。
  7. 优化阈值遍历逻辑:取proba列的唯一值进行遍历,避免同一个阈值重复计算多次,大幅提升运行效率。
修复后参考代码
def confusion_matrix(self):
    """This method returns the confusion matrix for the given pair of Y and Y_Predicted"""
    y = self.df["y"]
    ypred = self.df["ypred"]
    self.setVariables()        
    try:
        assert len(y) == len(ypred)
        # 直接遍历配对的真实值和预测值,完全避免索引问题
        for y_true, y_pred in zip(y, ypred):
            if y_true == 1 and y_pred == 1:
                self._truePositive +=1
            elif y_true == 1 and y_pred == 0:
                self._falseNegative +=1 # 修正类别判定
            elif y_true == 0 and y_pred == 1:
                self._falsePositive +=1
            elif y_true == 0 and y_pred == 0:
                self._trueNegative +=1 # 修正类别判定
        self._cnf_matrix = [self._truePositive, self._falseNegative, 
                            self._falsePositive, self._trueNegative]
        return np.array(self._cnf_matrix).reshape(2,2)
    except AssertionError:
        print("Input Error: Length of y and ypred is not same.")
      

def metricForLowestValues(self):
    """Compute the best threshold of probability which gives lowest values of metric A"""
    dict_metricA = {}
    # 取概率的唯一值遍历,避免重复计算,同时过滤None值
    for threshold in tqdm(self.df['proba'].dropna().unique()):
        self.predict(threshold)
        cnf = self.confusion_matrix()
        # A=500×number of false negative+100×number of false positive
        metricA = 500 * self._falseNegative + 100 * self._falsePositive
        dict_metricA[threshold] = metricA
    # 排序逻辑移到循环外,只执行一次
    sorted_metricAList = sorted(dict_metricA.items(), key=lambda item:item[1])
    minKey = sorted_metricAList[0][0]
    minValue = sorted_metricAList[0][1]
    return minKey, minValue

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 08:21:03