{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# An example of K-Means++ initialization\n\nAn example to show the output of the :func:`sklearn.cluster.kmeans_plusplus`\nfunction for generating initial seeds for clustering.\n\nK-Means++ is used as the default initialization for `k_means`.\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\n\nfrom sklearn.cluster import kmeans_plusplus\nfrom sklearn.datasets import make_blobs\n\n# Generate sample data\nn_samples = 4000\nn_components = 4\n\nX, y_true = make_blobs(\n n_samples=n_samples, centers=n_components, cluster_std=0.60, random_state=0\n)\nX = X[:, ::-1]\n\n# Calculate seeds from k-means++\ncenters_init, indices = kmeans_plusplus(X, n_clusters=4, random_state=0)\n\n# Plot init seeds along side sample data\nplt.figure(1)\ncolors = [\"#4EACC5\", \"#FF9C34\", \"#4E9A06\", \"m\"]\n\nfor k, col in enumerate(colors):\n cluster_data = y_true == k\n plt.scatter(X[cluster_data, 0], X[cluster_data, 1], c=col, marker=\".\", s=10)\n\nplt.scatter(centers_init[:, 0], centers_init[:, 1], c=\"b\", s=50)\nplt.title(\"K-Means++ Initialization\")\nplt.xticks([])\nplt.yticks([])\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 }