.. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_packages_scikit-learn_auto_examples_plot_iris_knn.py: Nearest-neighbor prediction on iris ==================================== Plot the decision boundary of nearest neighbor decision on iris, first with a single nearest neighbor, and then using 3 nearest neighbors. .. code-block:: python import numpy as np from matplotlib import pyplot as plt from sklearn import neighbors, datasets from matplotlib.colors import ListedColormap # Create color maps for 3-class classification problem, as with iris cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. We could # avoid this ugly slicing by using a two-dim dataset y = iris.target knn = neighbors.KNeighborsClassifier(n_neighbors=1) knn.fit(X, y) x_min, x_max = X[:, 0].min() - .1, X[:, 0].max() + .1 y_min, y_max = X[:, 1].min() - .1, X[:, 1].max() + .1 xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100)) Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) Put the result into a color plot .. code-block:: python Z = Z.reshape(xx.shape) plt.figure() plt.pcolormesh(xx, yy, Z, cmap=cmap_light) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) plt.xlabel('sepal length (cm)') plt.ylabel('sepal width (cm)') plt.axis('tight') .. image:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_iris_knn_001.png :class: sphx-glr-single-img And now, redo the analysis with 3 neighbors .. code-block:: python knn = neighbors.KNeighborsClassifier(n_neighbors=3) knn.fit(X, y) Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.figure() plt.pcolormesh(xx, yy, Z, cmap=cmap_light) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold) plt.xlabel('sepal length (cm)') plt.ylabel('sepal width (cm)') plt.axis('tight') plt.show() .. image:: /packages/scikit-learn/auto_examples/images/sphx_glr_plot_iris_knn_002.png :class: sphx-glr-single-img **Total running time of the script:** ( 0 minutes 0.129 seconds) .. _sphx_glr_download_packages_scikit-learn_auto_examples_plot_iris_knn.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download :download:`Download Python source code: plot_iris_knn.py ` .. container:: sphx-glr-download :download:`Download Jupyter notebook: plot_iris_knn.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_