使用局部离群因子(LOF)进行离群点检测#

局部异常因子(LOF)算法是一种无监督异常检测方法,它计算给定数据点相对于其邻居的局部密度偏差。它将密度远低于邻居的样本视为离群值。此示例展示了如何使用LOF进行异常值检测,这是scikit-learn中该估计器的默认用例。请注意,当LOF用于异常值检测时,它没有 predict , decision_functionscore_samples 方法.看到 User Guide 了解异常值检测和新奇性检测之间的区别以及如何使用LOF进行新奇性检测的详细信息。

考虑的邻居数量(参数 n_neighbors )通常设置1)大于集群必须包含的最小样本数量,以便其他样本可能是相对于该集群的局部异常值,以及2)小于可能是局部异常值的附近样本的最大数量。在实践中,此类信息通常是不可用的,并且采取 n_neighbors=20 似乎在一般情况下运作良好。

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

生成带有异常值的数据#

import numpy as np

np.random.seed(42)

X_inliers = 0.3 * np.random.randn(100, 2)
X_inliers = np.r_[X_inliers + 2, X_inliers - 2]
X_outliers = np.random.uniform(low=-4, high=4, size=(20, 2))
X = np.r_[X_inliers, X_outliers]

n_outliers = len(X_outliers)
ground_truth = np.ones(len(X), dtype=int)
ground_truth[-n_outliers:] = -1

为异常值检测匹配模型(默认)#

使用 fit_predict 计算训练样本的预测标签(当LOF用于异常值检测时,估计器没有 predict , decision_functionscore_samples 方法)。

from sklearn.neighbors import LocalOutlierFactor

clf = LocalOutlierFactor(n_neighbors=20, contamination=0.1)
y_pred = clf.fit_predict(X)
n_errors = (y_pred != ground_truth).sum()
X_scores = clf.negative_outlier_factor_

图结果#

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerPathCollection


def update_legend_marker_size(handle, orig):
    "Customize size of the legend marker"
    handle.update_from(orig)
    handle.set_sizes([20])


plt.scatter(X[:, 0], X[:, 1], color="k", s=3.0, label="Data points")
# plot circles with radius proportional to the outlier scores
radius = (X_scores.max() - X_scores) / (X_scores.max() - X_scores.min())
scatter = plt.scatter(
    X[:, 0],
    X[:, 1],
    s=1000 * radius,
    edgecolors="r",
    facecolors="none",
    label="Outlier scores",
)
plt.axis("tight")
plt.xlim((-5, 5))
plt.ylim((-5, 5))
plt.xlabel("prediction errors: %d" % (n_errors))
plt.legend(
    handler_map={scatter: HandlerPathCollection(update_func=update_legend_marker_size)}
)
plt.title("Local Outlier Factor (LOF)")
plt.show()
Local Outlier Factor (LOF)

Total running time of the script: (0分0.079秒)

相关实例

利用本地异常值因子(LOF)进行新颖性检测

Novelty detection with Local Outlier Factor (LOF)

比较玩具数据集异常值检测的异常检测算法

Comparing anomaly detection algorithms for outlier detection on toy datasets

真实数据集上的离群值检测

Outlier detection on a real data set

带非线性核(RBS)的一类支持者

One-class SVM with non-linear kernel (RBF)

Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io> _