我正在尝试使用Local Outlier Factor (LOF)算法,并想绘制ROC曲线。问题是,scikit-learn提供的库不会为每个预测产生得分。
那么,无论如何我能解决这个问题吗?
答案 0 :(得分:2)
属性negative_outlier_factor_
实际上是documentation中所述的-LOF,而source code中更好。一种常见的方法是通过根据阈值的不同值分配预测来计算ROC。如果您的数据位于df
,且'label'
列中包含标签,则代码将如下所示:
def get_predictions(lof, threshold=1.5):
return list(map(lambda x: -1 if x > threshold else 1, lof))
lof_ths = np.arange(1.3, 6., 0.1)
clf = LocalOutlierFactor(n_neighbors=30)
clf.fit_predict(df.drop(['label'], axis=1))
lofs = -clf.negative_outlier_factor_
plt.figure()
lw = 2
plt.xlim([0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate', fontsize=14)
plt.ylabel('True Positive Rate', fontsize=14)
plt.title('Receiver operating characteristic', fontsize=16)
fpr = tpr = [0]
for ths in lof_ths:
pred = get_predictions(lof, threshold=ths)
tn, fp, fn, tp = confusion_matrix(df.label, pred, labels=[-1,1]).ravel()
fpr.append(fp / (fp + tn + .000001))
tpr.append(tp / (tp + fn + .000001))
fpr.append(1)
tpr.append(1)
plt.plot(fpr, tpr, label='ROC Curve')
plt.plot([0, 1], [0, 1], color='navy', label='Random Guessing', lw=lw, linestyle='--')
plt.legend(loc="lower right", fontsize=12)