我正在使用Sklearn处理不平衡数据集的分类。Sklearn计算错了false_positive_rate和true_positive_rate;当我想计算AUC分数时,结果与我从混淆矩阵中得到的结果不同。
从Sklearn中,我得到了以下混淆矩阵:
confusion = confusion_matrix(y_test, y_pred)
array([[ 9100, 4320],
[109007, 320068]], dtype=int64)当然,我的理解是:
+-----------------------------------+------------------------+
| | Predicted | Predicted |
+-----------------------------------+------------------------+
| Actual | True positive = 9100 | False-negative = 4320 |
| Actual | False-positive = 109007 | True negative = 320068|
+--------+--------------------------+------------------------+然而,对于FPR和TPR,我得到了以下结果:
false_positive_rate, true_positive_rate, thresholds = roc_curve(y_test, y_pred)
(false_positive_rate, true_positive_rate)
(array([0. , 0.3219076, 1. ]),
array([0. , 0.7459488, 1. ]))结果与confusion_matrix不同。根据我的表格,FPR实际上是FNR,TPR实际上是TNR。然后我检查了混淆矩阵文档,我发现:
因此,在二进制分类中,真负数为C0,0,假负数为C1,真正数为C1,假负数为C0,1。
这意味着,根据Sklearn的说法,confusion_matrix看起来如下所示:
+-----------------------------------+---------------------------+
| | Predicted | Predicted |
+-----------------------------------+---------------------------+
| Actual | True-Positive = 320068 | False-Negative = 109007 |
| Actual | False-Positive = 4320 | True-Negative = 9100 |
+--------+--------------------------+---------------------------+根据这一理论,对于二进制分类,稀有类被表示为正类。
为什么斯凯夫特认为大多数班级都是积极的?
发布于 2021-06-05 12:37:37
经过一些实验,我发现当使用来自IsolationForest的sklearn处理不平衡的数据时,如果检查confusion_matrix,可以看出IsolationForest将大多数(正常)类视为一个正类,而次要类应该是欺诈/异常/异常检测任务中的正类。
为了克服这一挑战,有两种解决办法:
FP代替了FN,TP代替了TN。通常情况下,如果返回值为1,异常值为1,inliers为1,那么如果在IsolationForest的输出中将1替换为-1,然后用1替换-1,那么在这种情况下,您可以正确地使用标准的度量计算。
IF_model = IsolationForest(max_samples="auto",
random_state=11,
contamination = 0.1,
n_estimators=100,
n_jobs=-1)
IF_model.fit(X_train_sf, y_train_sf)
y_pred_test = IF_model.predict(X_test_sf)
counts = np.unique(y_pred_test, return_counts=True)
#(array([-1, 1]), array([44914, 4154]))
#replace 1 with -1 and then -1 with 1
if (counts[1][0] < counts[1][1] and counts[0][0] == -1) or (counts[1][0] > counts[1][1] and counts[0][0] == 1): y_pred_test = -y_pred_test考虑到混淆矩阵文档和问题定义这里,对于欺诈/离群/异常检测或基于文学性Ref.1、Ref.2、Ref.3的二进制分类器,上述技巧应该有效并正确地形成混淆矩阵如下:
+----------------------------+---------------+--------------+
| | Predicted | Predicted |
+----------------------------+---------------+--------------+
| Actual (Positive class)[1] | TP | FN |
| Actual (Negative class)[-1]| FP | TN |
+----------------------------+---------------+--------------+tn, fp, fn, tp = confusion_matrix(y_test_sf, y_pred_test).ravel()
print("TN: ",tn,"\nFP: ", fp,"\nFN: " ,fn,"\nTP: ", tp)
print("Number of positive class instances: ",tp+fn,"\nNumber of negative class instances: ", tn+fp)检查评估结果:
print(classification_report(y_test_sf, y_pred_test, target_names=["Anomaly", "Normal"]))https://stackoverflow.com/questions/56459660
复制相似问题