我使用以下代码来预测异常检测。这是一个二分类问题,所以混淆矩阵应该是2×2,但实际上是3×3。混淆矩阵中以T形附加了额外的零。几周前使用OneClassSVM时也发生了类似的情况,但我以为是我自己操作错误。请问您能帮我解决这个问题吗?
import numpy as npimport pandas as pdimport osfrom sklearn.ensemble import IsolationForestfrom sklearn.metrics import confusion_matrix, accuracy_score, classification_report from sklearn import metricsfrom sklearn.metrics import roc_auc_scoredata = pd.read_csv('opensky_train.csv')#to make sure that normal data contains no anomalysortedData = data.sort_values(by=['class'])target = pd.DataFrame(sortedData['class'])Y = target.replace(['surveill', 'other'], [1,0])X = sortedData.drop(['class'], axis = 1)x_normal = X.iloc[:200,:]y_normal = Y.iloc[:200,:]x_anomaly = X.iloc[200:,:]y_anomaly = Y.iloc[200:,:]
已编辑:
column_values = y_anomaly.values.ravel()unique_values = pd.unique(column_values)print(unique_values)
输出 : [0 1]
clf = IsolationForest(random_state=0).fit(x_normal)pred = clf.predict(x_anomaly)print(pred)
输出 : [ 1 1 1 1 1 1 -1 1 -1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 -1 1 1 -1 1 1 -1 1 1 -1 1 -1 1 -1 1 1 -1 -1 1 -1 -1 1 1 1 1 -1 1 1 -1 -1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 1 1 1 -1]
#打印结果 print(confusion_matrix(y_anomaly, pred))print (classification_report(y_anomaly, pred))
结果:
混淆矩阵 :[[ 0 0 0] [ 7 0 60] [12 0 28]] 精确率 召回率 F1分数 支持数 -1 0.00 0.00 0.00 0 0 0.00 0.00 0.00 67 1 0.32 0.70 0.44 40 准确率 0.26 107 宏平均 0.11 0.23 0.15 107加权平均 0.12 0.26 0.16 107
回答:
内部点标记为1,而异常点标记为-1
来源: scikit-learn 异常和异常值检测。
您的例子将类别转换为了0,1 – 因此可能的选项是-1,0,1
您需要将
Y = target.replace(['surveill', 'other'], [1,0])
改为
Y = target.replace(['surveill', 'other'], [1,-1])