{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Nearest Neighbors regression\n\nDemonstrate the resolution of a regression problem\nusing a k-Nearest Neighbor and the interpolation of the\ntarget using both barycenter and constant weights.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>\n#         Fabian Pedregosa <fabian.pedregosa@inria.fr>\n#\n# License: BSD 3 clause (C) INRIA"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Generate sample data\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn import neighbors\n\nnp.random.seed(0)\nX = np.sort(5 * np.random.rand(40, 1), axis=0)\nT = np.linspace(0, 5, 500)[:, np.newaxis]\ny = np.sin(X).ravel()\n\n# Add noise to targets\ny[::5] += 1 * (0.5 - np.random.rand(8))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Fit regression model\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "n_neighbors = 5\n\nfor i, weights in enumerate([\"uniform\", \"distance\"]):\n    knn = neighbors.KNeighborsRegressor(n_neighbors, weights=weights)\n    y_ = knn.fit(X, y).predict(T)\n\n    plt.subplot(2, 1, i + 1)\n    plt.scatter(X, y, color=\"darkorange\", label=\"data\")\n    plt.plot(T, y_, color=\"navy\", label=\"prediction\")\n    plt.axis(\"tight\")\n    plt.legend()\n    plt.title(\"KNeighborsRegressor (k = %i, weights = '%s')\" % (n_neighbors, weights))\n\nplt.tight_layout()\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.9.18"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}