首页 > 解决方案 > 如何修复 GBTclassifier 混淆矩阵中的 Keyerror

问题描述

在使用 gbt 分类器时,在卷积矩阵中收到一个错误作为 keyerror...

cm_gbt_result = predictions_gbt.crosstab("prediction", "indexedLabel")
cm_gbt_result = cm_gbt_result.toPandas()
cm_gbt_result
#calculate accuracy, sensitivity, specificity and precision
TP = cm_gbt_result["1"][0]
FP = cm_gbt_result["0"][0]
TN = cm_gbt_result["0"][1]
FN = cm_gbt_result["1"][1]
Accuracy = (TP+TN)/(TP+FP+TN+FN)
Sensitivity = TP/(TP+FN)
Specificity = TN/(TN+FP)
Precision = TP/(TP+FP)

print ("Accuracy = %0.2f" %Accuracy )
print ("Sensitivity = %0.2f" %Sensitivity )
print ("Specificity = %0.2f" %Specificity )
print ("Precision = %0.2f" %Precision )

上述代码的跟踪:

追溯

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2894             try:
-> 2895                 return self._engine.get_loc(casted_key)
   2896             except KeyError as err:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: '1'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
2 frames
<ipython-input-56-24962cb86bab> in <module>()
      1 #calculate accuracy, sensitivity, specificity and precision
----> 2 TP = cm_gbt_result["1"][0]
      3 FP = cm_gbt_result["0"][0]
      4 TN = cm_gbt_result["0"][1]
      5 FN = cm_gbt_result["1"][1]

/usr/local/lib/python3.6/dist-packages/pandas/core/frame.py in __getitem__(self, key)
   2904             if self.columns.nlevels > 1:
   2905                 return self._getitem_multilevel(key)
-> 2906             indexer = self.columns.get_loc(key)
   2907             if is_integer(indexer):
   2908                 indexer = [indexer]

/usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2895                 return self._engine.get_loc(casted_key)
   2896             except KeyError as err:
-> 2897                 raise KeyError(key) from err
   2898 
   2899         if tolerance is not None:

KeyError: '1'

cm_gbt_result

 prediction_indexedLabel 0.0    1.0
0   0.0               479994    11598

谁能告诉我为什么会发生这个错误以及如何解决它......因为我是python的新手......如果有任何愚蠢的错误请原谅我

标签: pythonpysparkconfusion-matrixkeyerror

解决方案


推荐阅读