{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Nearest Neighbors Classification\n\nSample usage of Nearest Neighbors classification.\nIt will plot the decision boundaries for each class.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport seaborn as sns\nfrom matplotlib.colors import ListedColormap\nfrom sklearn import neighbors, datasets\nfrom sklearn.inspection import DecisionBoundaryDisplay\n\nn_neighbors = 15\n\n# import some data to play with\niris = datasets.load_iris()\n\n# we only take the first two features. We could avoid this ugly\n# slicing by using a two-dim dataset\nX = iris.data[:, :2]\ny = iris.target\n\n# Create color maps\ncmap_light = ListedColormap([\"orange\", \"cyan\", \"cornflowerblue\"])\ncmap_bold = [\"darkorange\", \"c\", \"darkblue\"]\n\nfor weights in [\"uniform\", \"distance\"]:\n # we create an instance of Neighbours Classifier and fit the data.\n clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)\n clf.fit(X, y)\n\n _, ax = plt.subplots()\n DecisionBoundaryDisplay.from_estimator(\n clf,\n X,\n cmap=cmap_light,\n ax=ax,\n response_method=\"predict\",\n plot_method=\"pcolormesh\",\n xlabel=iris.feature_names[0],\n ylabel=iris.feature_names[1],\n shading=\"auto\",\n )\n\n # Plot also the training points\n sns.scatterplot(\n x=X[:, 0],\n y=X[:, 1],\n hue=iris.target_names[y],\n palette=cmap_bold,\n alpha=1.0,\n edgecolor=\"black\",\n )\n plt.title(\n \"3-Class classification (k = %i, weights = '%s')\" % (n_neighbors, weights)\n )\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.9.16" } }, "nbformat": 4, "nbformat_minor": 0 }