如何绘制局部离群因子算法的ROC曲线?

2024-06-16 09:48:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Local Outlier Factor (LOF)算法,并想绘制ROC曲线。问题是,scikit learn提供的库并没有为每个预测生成分数。在

那么,有没有什么办法我可以解决这个问题?在


Tags: 算法local绘制scikitlearn曲线分数roc
1条回答
网友
1楼 · 发布于 2024-06-16 09:48:06

属性negative_outlier_factor_实际上是documentation中所述的-LOF,在{a2}中更好。一种常见的方法是根据阈值的不同值分配预测值来计算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)

相关问题 更多 >