.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/neighbors/plot_lof_novelty_detection.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_neighbors_plot_lof_novelty_detection.py: ================================================= 使用局部离群因子(LOF)进行新颖性检测 ================================================= 局部离群因子(LOF)算法是一种无监督的异常检测方法,它通过计算给定数据点相对于其邻居的局部密度偏差来识别异常点。它将密度显著低于其邻居的样本视为异常点。本示例展示了如何使用LOF进行新颖性检测。请注意,当LOF用于新颖性检测时,绝对不能在训练集上使用predict、decision_function和score_samples方法,因为这会导致错误的结果。您必须仅在未见过的新数据(不在训练集中)上使用这些方法。有关离群检测和新颖性检测之间的区别以及如何使用LOF进行离群检测的详细信息,请参见用户指南。 考虑的邻居数量(参数n_neighbors)通常设置为:1)大于一个簇必须包含的最小样本数,以便其他样本可以相对于该簇成为局部离群点;2)小于可能成为局部离群点的最大邻近样本数。在实际操作中,通常无法获得此类信息,并且n_neighbors=20通常效果良好。 .. GENERATED FROM PYTHON SOURCE LINES 11-72 .. image-sg:: /auto_examples/neighbors/images/sphx_glr_plot_lof_novelty_detection_001.png :alt: Novelty Detection with LOF :srcset: /auto_examples/neighbors/images/sphx_glr_plot_lof_novelty_detection_001.png :class: sphx-glr-single-img .. code-block:: Python import matplotlib import matplotlib.lines as mlines import matplotlib.pyplot as plt import numpy as np from sklearn.neighbors import LocalOutlierFactor np.random.seed(42) xx, yy = np.meshgrid(np.linspace(-5, 5, 500), np.linspace(-5, 5, 500)) # 生成正常(非异常)训练观测值 X = 0.3 * np.random.randn(100, 2) X_train = np.r_[X + 2, X - 2] # 生成新的正常(非异常)观测值 X = 0.3 * np.random.randn(20, 2) X_test = np.r_[X + 2, X - 2] # 生成一些异常的新奇观测 X_outliers = np.random.uniform(low=-4, high=4, size=(20, 2)) # 拟合模型以进行新颖性检测(novelty=True) clf = LocalOutlierFactor(n_neighbors=20, novelty=True, contamination=0.1) clf.fit(X_train) # 请勿在 X_train 上使用 predict、decision_function 和 score_samples,因为这会给出错误的结果,而应仅在新的未见过的数据(未在 X_train 中使用)上使用,例如 X_test、X_outliers 或 meshgrid。 y_pred_test = clf.predict(X_test) y_pred_outliers = clf.predict(X_outliers) n_error_test = y_pred_test[y_pred_test == -1].size n_error_outliers = y_pred_outliers[y_pred_outliers == 1].size # 绘制学习到的边界、点和最近的向量到平面 Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.title("Novelty Detection with LOF") plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7), cmap=plt.cm.PuBu) a = plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors="darkred") plt.contourf(xx, yy, Z, levels=[0, Z.max()], colors="palevioletred") s = 40 b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c="white", s=s, edgecolors="k") b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c="blueviolet", s=s, edgecolors="k") c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c="gold", s=s, edgecolors="k") plt.axis("tight") plt.xlim((-5, 5)) plt.ylim((-5, 5)) plt.legend( [mlines.Line2D([], [], color="darkred"), b1, b2, c], [ "learned frontier", "training observations", "new regular observations", "new abnormal observations", ], loc="upper left", prop=matplotlib.font_manager.FontProperties(size=11), ) plt.xlabel( "errors novel regular: %d/40 ; errors novel abnormal: %d/40" % (n_error_test, n_error_outliers) ) plt.show() .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 1.325 seconds) .. _sphx_glr_download_auto_examples_neighbors_plot_lof_novelty_detection.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/scikit-learn/scikit-learn/main?urlpath=lab/tree/notebooks/auto_examples/neighbors/plot_lof_novelty_detection.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_lof_novelty_detection.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_lof_novelty_detection.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_lof_novelty_detection.zip ` .. include:: plot_lof_novelty_detection.recommendations .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_