{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Bisecting K-Means and Regular K-Means Performance Comparison\n\nThis example shows differences between Regular K-Means algorithm and Bisecting K-Means.\n\nWhile K-Means clusterings are different when increasing n_clusters,\nBisecting K-Means clustering builds on top of the previous ones. As a result, it\ntends to create clusters that have a more regular large-scale structure. This\ndifference can be visually observed: for all numbers of clusters, there is a\ndividing line cutting the overall data cloud in two for BisectingKMeans, which is not\npresent for regular 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 BisectingKMeans, KMeans\nfrom sklearn.datasets import make_blobs\n\n# Generate sample data\nn_samples = 10000\nrandom_state = 0\n\nX, _ = make_blobs(n_samples=n_samples, centers=2, random_state=random_state)\n\n# Number of cluster centers for KMeans and BisectingKMeans\nn_clusters_list = [4, 8, 16]\n\n# Algorithms to compare\nclustering_algorithms = {\n    \"Bisecting K-Means\": BisectingKMeans,\n    \"K-Means\": KMeans,\n}\n\n# Make subplots for each variant\nfig, axs = plt.subplots(\n    len(clustering_algorithms), len(n_clusters_list), figsize=(12, 5)\n)\n\naxs = axs.T\n\nfor i, (algorithm_name, Algorithm) in enumerate(clustering_algorithms.items()):\n    for j, n_clusters in enumerate(n_clusters_list):\n        algo = Algorithm(n_clusters=n_clusters, random_state=random_state, n_init=3)\n        algo.fit(X)\n        centers = algo.cluster_centers_\n\n        axs[j, i].scatter(X[:, 0], X[:, 1], s=10, c=algo.labels_)\n        axs[j, i].scatter(centers[:, 0], centers[:, 1], c=\"r\", s=20)\n\n        axs[j, i].set_title(f\"{algorithm_name} : {n_clusters} clusters\")\n\n\n# Hide x labels and tick labels for top plots and y ticks for right plots.\nfor ax in axs.flat:\n    ax.label_outer()\n    ax.set_xticks([])\n    ax.set_yticks([])\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.11.14"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}