{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n=================================================\nOutlier detection with Local Outlier Factor (LOF)\n=================================================\n\nThe Local Outlier Factor (LOF) algorithm is an unsupervised anomaly detection\nmethod which computes the local density deviation of a given data point with\nrespect to its neighbors. It considers as outliers the samples that have a\nsubstantially lower density than their neighbors. This example shows how to\nuse LOF for outlier detection which is the default use case of this estimator\nin scikit-learn. Note that when LOF is used for outlier detection it has no\npredict, decision_function and score_samples methods. See\n`User Guide <outlier_detection>`: for details on the difference between\noutlier detection and novelty detection and how to use LOF for novelty\ndetection.\n\nThe number of neighbors considered (parameter n_neighbors) is typically\nset 1) greater than the minimum number of samples a cluster has to contain,\nso that other samples can be local outliers relative to this cluster, and 2)\nsmaller than the maximum number of close by samples that can potentially be\nlocal outliers.\nIn practice, such informations are generally not available, and taking\nn_neighbors=20 appears to work well in general.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.neighbors import LocalOutlierFactor\n\nprint(__doc__)\n\nnp.random.seed(42)\n\n# Generate train data\nX_inliers = 0.3 * np.random.randn(100, 2)\nX_inliers = np.r_[X_inliers + 2, X_inliers - 2]\n\n# Generate some outliers\nX_outliers = np.random.uniform(low=-4, high=4, size=(20, 2))\nX = np.r_[X_inliers, X_outliers]\n\nn_outliers = len(X_outliers)\nground_truth = np.ones(len(X), dtype=int)\nground_truth[-n_outliers:] = -1\n\n# fit the model for outlier detection (default)\nclf = LocalOutlierFactor(n_neighbors=20, contamination=0.1)\n# use fit_predict to compute the predicted labels of the training samples\n# (when LOF is used for outlier detection, the estimator has no predict,\n# decision_function and score_samples methods).\ny_pred = clf.fit_predict(X)\nn_errors = (y_pred != ground_truth).sum()\nX_scores = clf.negative_outlier_factor_\n\nplt.title(\"Local Outlier Factor (LOF)\")\nplt.scatter(X[:, 0], X[:, 1], color='k', s=3., label='Data points')\n# plot circles with radius proportional to the outlier scores\nradius = (X_scores.max() - X_scores) / (X_scores.max() - X_scores.min())\nplt.scatter(X[:, 0], X[:, 1], s=1000 * radius, edgecolors='r',\n            facecolors='none', label='Outlier scores')\nplt.axis('tight')\nplt.xlim((-5, 5))\nplt.ylim((-5, 5))\nplt.xlabel(\"prediction errors: %d\" % (n_errors))\nlegend = plt.legend(loc='upper left')\nlegend.legendHandles[0]._sizes = [10]\nlegend.legendHandles[1]._sizes = [20]\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}