{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Comparing Nearest Neighbors with and without Neighborhood Components Analysis\n\n\nAn example comparing nearest neighbors classification with and without\nNeighborhood Components Analysis.\n\nIt will plot the class decision boundaries given by a Nearest Neighbors\nclassifier when using the Euclidean distance on the original features, versus\nusing the Euclidean distance after the transformation learned by Neighborhood\nComponents Analysis. The latter aims to find a linear transformation that\nmaximises the (stochastic) nearest neighbor classification accuracy on the\ntraining set.\n\nAdapted from `<https://scikit-learn.org/stable/auto_examples/neighbors/plot_nca_classification.html>`_\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# License: BSD 3 clause\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\n\nfrom skhubness.neighbors import (KNeighborsClassifier,\n                                 NeighborhoodComponentsAnalysis)\nimport warnings\nwarnings.filterwarnings('ignore')\n\nprint(__doc__)\n\nn_neighbors = 1\n\ndataset = datasets.load_iris()\nX, y = dataset.data, dataset.target\n\n# we only take two features. We could avoid this ugly\n# slicing by using a two-dim dataset\nX = X[:, [0, 2]]\n\nX_train, X_test, y_train, y_test = \\\n    train_test_split(X, y, stratify=y, test_size=0.7, random_state=42)\n\nh = .01  # step size in the mesh\n\n# Create color maps\ncmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])\ncmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])\n\nnames = ['KNN',\n         'NCA, KNN',\n         'KNN, MP (normal)',\n         'KNN, MP (empiric)',\n         'KNN, LS (standard)',\n         'KNN, LS (nicdm)',\n        ]\n\nclassifiers = [Pipeline([('scaler', StandardScaler()),\n                         ('knn', KNeighborsClassifier(n_neighbors=n_neighbors))\n                         ]),\n               Pipeline([('scaler', StandardScaler()),\n                         ('nca', NeighborhoodComponentsAnalysis()),\n                         ('knn', KNeighborsClassifier(n_neighbors=n_neighbors))\n                         ]),\n               Pipeline([('scaler', StandardScaler()),\n                         ('knn', KNeighborsClassifier(n_neighbors=n_neighbors,\n                                                      hubness='mutual_proximity',\n                                                      hubness_params={'method': 'normal'}))\n                         ]),\n               Pipeline([('scaler', StandardScaler()),\n                         ('knn', KNeighborsClassifier(n_neighbors=n_neighbors,\n                                                      hubness='mutual_proximity',\n                                                      hubness_params={'method': 'empiric'}))\n                         ]),\n               Pipeline([('scaler', StandardScaler()),\n                         ('knn', KNeighborsClassifier(n_neighbors=n_neighbors,\n                                                      hubness='local_scaling',\n                                                      hubness_params={'method': 'standard'}))\n                         ]),\n               Pipeline([('scaler', StandardScaler()),\n                         ('knn', KNeighborsClassifier(n_neighbors=n_neighbors,\n                                                      hubness='local_scaling',\n                                                      hubness_params={'method': 'nicdm'}))\n                         ]),\n               ]\n\nx_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\ny_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\nxx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n                     np.arange(y_min, y_max, h))\n\nfor name, clf in zip(names, classifiers):\n\n    clf.fit(X_train, y_train)\n    score = clf.score(X_test, y_test)\n\n    # Plot the decision boundary. For that, we will assign a color to each\n    # point in the mesh [x_min, x_max]x[y_min, y_max].\n    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n\n    # Put the result into a color plot\n    Z = Z.reshape(xx.shape)\n    plt.figure()\n    plt.pcolormesh(xx, yy, Z, cmap=cmap_light, alpha=.8)\n\n    # Plot also the training and testing points\n    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold, edgecolor='k', s=20)\n    plt.xlim(xx.min(), xx.max())\n    plt.ylim(yy.min(), yy.max())\n    plt.title(\"{} (k = {})\".format(name, n_neighbors))\n    plt.text(0.9, 0.1, '{:.2f}'.format(score), size=15,\n             ha='center', va='center', transform=plt.gca().transAxes)\n\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.7.4"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}