{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Feature agglomeration\n\nThese images show how similar features are merged together using\nfeature agglomeration.\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\n\nfrom sklearn import cluster, datasets\nfrom sklearn.feature_extraction.image import grid_to_graph\n\ndigits = datasets.load_digits()\nimages = digits.images\nX = np.reshape(images, (len(images), -1))\nconnectivity = grid_to_graph(*images[0].shape)\n\nagglo = cluster.FeatureAgglomeration(connectivity=connectivity, n_clusters=32)\n\nagglo.fit(X)\nX_reduced = agglo.transform(X)\n\nX_restored = agglo.inverse_transform(X_reduced)\nimages_restored = np.reshape(X_restored, images.shape)\nplt.figure(1, figsize=(4, 3.5))\nplt.clf()\nplt.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.91)\nfor i in range(4):\n    plt.subplot(3, 4, i + 1)\n    plt.imshow(images[i], cmap=plt.cm.gray, vmax=16, interpolation=\"nearest\")\n    plt.xticks(())\n    plt.yticks(())\n    if i == 1:\n        plt.title(\"Original data\")\n    plt.subplot(3, 4, 4 + i + 1)\n    plt.imshow(images_restored[i], cmap=plt.cm.gray, vmax=16, interpolation=\"nearest\")\n    if i == 1:\n        plt.title(\"Agglomerated data\")\n    plt.xticks(())\n    plt.yticks(())\n\nplt.subplot(3, 4, 10)\nplt.imshow(\n    np.reshape(agglo.labels_, images[0].shape),\n    interpolation=\"nearest\",\n    cmap=plt.cm.nipy_spectral,\n)\nplt.xticks(())\nplt.yticks(())\nplt.title(\"Labels\")\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
}