{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# K-Means clustering\n\nAn example of ``scikit-learn``, copied from\n[scikit-learn.org](https://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_plusplus.html#sphx-glr-auto-examples-cluster-plot-kmeans-plusplus-py).\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sklearn.cluster import kmeans_plusplus\nfrom sklearn.datasets import make_blobs\nimport matplotlib.pyplot as plt\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 kmeans++\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.8.10" } }, "nbformat": 4, "nbformat_minor": 0 }