{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Nearest Centroid Classification\n\nSample usage of Nearest Centroid classification.\nIt will plot the decision boundaries for each class.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.colors import ListedColormap\n\nfrom sklearn import datasets\nfrom sklearn.inspection import DecisionBoundaryDisplay\nfrom sklearn.neighbors import NearestCentroid\n\n# import some data to play with\niris = datasets.load_iris()\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 = ListedColormap([\"darkorange\", \"c\", \"darkblue\"])\n\nfor shrinkage in [None, 0.2]:\n # we create an instance of Nearest Centroid Classifier and fit the data.\n clf = NearestCentroid(shrink_threshold=shrinkage)\n clf.fit(X, y)\n y_pred = clf.predict(X)\n print(shrinkage, np.mean(y == y_pred))\n\n _, ax = plt.subplots()\n DecisionBoundaryDisplay.from_estimator(\n clf, X, cmap=cmap_light, ax=ax, response_method=\"predict\"\n )\n\n # Plot also the training points\n plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold, edgecolor=\"k\", s=20)\n plt.title(\"3-Class classification (shrink_threshold=%r)\" % shrinkage)\n plt.axis(\"tight\")\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.21" } }, "nbformat": 4, "nbformat_minor": 0 }