首页 > 解决方案 > 通过实例理解 LocalOutlinerFactor 算法

问题描述

因此,我研究了 LocalOutliner Detection 的 sklearn 示例,并尝试将其应用于我拥有的示例数据集。但不知何故,结果本身对我来说并没有什么意义。

我已经实现的看起来像:(不包括导入的东西)

import numpy as np
import matplotlib.pyplot as plt
import pandas
from sklearn.neighbors import LocalOutlierFactor


# import file
url = ".../Python/outliner.csv"
names = ['R1', 'P1', 'T1', 'P2', 'Flag']
dataset = pandas.read_csv(url, names=names)    

array = dataset.values
X = array[:,0:2] 
rng = np.random.RandomState(42)


# fit the model
clf = LocalOutlierFactor(n_neighbors=50, algorithm='auto', leaf_size=30)
y_pred = clf.fit_predict(X)
y_pred_outliers = y_pred[500:]

# plot the level sets of the decision function
xx, yy = np.meshgrid(np.linspace(0, 1000, 50), np.linspace(0, 200, 50))
Z = clf._decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.title("Local Outlier Factor (LOF)")
plt.contourf(xx, yy, Z, cmap=plt.cm.Blues_r)

a = plt.scatter(X[:200, 0], X[:200, 1], c='white',
                edgecolor='k', s=20)
b = plt.scatter(X[200:, 0], X[200:, 1], c='red',
                edgecolor='k', s=20)
plt.axis('tight')
plt.xlim((0, 1000))
plt.ylim((0, 200))
plt.legend([a, b],
           ["normal observations",
            "abnormal observations"],
           loc="upper left")
plt.show()

我得到这样的东西:LOF 轮廓检测

谁能告诉我为什么检测失败?

我尝试使用参数和范围,但对轮廓检测本身没有太大变化。

如果有人能指出我在这个问题上的正确方向,那就太好了。谢谢

编辑:添加了导入:文件

标签: pythonmachine-learningscikit-learndata-analysis

解决方案


我假设你遵循了这个例子。该示例尝试比较实际/观察数据(散点图​​)与从中学习的决策函数(等高线图)。由于数据是已知的/组成的(200 个正常值 + 20 个异常值),我们可以简单地使用X[200:](索引 200th 起)选择异常值,并使用X[:200](索引 0-199th)选择正常值。

因此,如果您想绘制预测结果(作为散点图)而不是实际/观察数据,您可能需要像下面的代码一样进行操作。基本上,您X根据y_pred(1:正常,-1:异常值)拆分,然后在散点图中使用它:

import numpy as np
import matplotlib.pyplot as plt
import pandas
from sklearn.neighbors import LocalOutlierFactor

# import file
url = ".../Python/outliner.csv"
names = ['R1', 'P1', 'T1', 'P2', 'Flag']
dataset = pandas.read_csv(url, names=names)
X = dataset.values[:, 0:2]

# fit the model
clf = LocalOutlierFactor(n_neighbors=50, algorithm='auto', leaf_size=30)
y_pred = clf.fit_predict(X)

# map results
X_normals = X[y_pred == 1]
X_outliers = X[y_pred == -1]

# plot the level sets of the decision function
xx, yy = np.meshgrid(np.linspace(0, 1000, 50), np.linspace(0, 200, 50))
Z = clf._decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.title("Local Outlier Factor (LOF)")
plt.contourf(xx, yy, Z, cmap=plt.cm.Blues_r)

a = plt.scatter(X_normals[:, 0], X_normals[:, 1], c='white', edgecolor='k', s=20)
b = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='red', edgecolor='k', s=20)
plt.axis('tight')
plt.xlim((0, 1000))
plt.ylim((0, 200))
plt.legend([a, b], ["normal predictions", "abnormal predictions"], loc="upper left")
plt.show()

如您所见,正常数据的散点图将遵循等高线图:

在此处输入图像描述


推荐阅读