{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n===========================================================\nHierarchical clustering: structured vs unstructured ward\n===========================================================\n\nExample builds a swiss roll dataset and runs\nhierarchical clustering on their position.\n\nFor more information, see `hierarchical_clustering`.\n\nIn a first step, the hierarchical clustering is performed without connectivity\nconstraints on the structure and is solely based on distance, whereas in\na second step the clustering is restricted to the k-Nearest Neighbors\ngraph: it's a hierarchical clustering with structure prior.\n\nSome of the clusters learned without connectivity constraints do not\nrespect the structure of the swiss roll and extend across different folds of\nthe manifolds. On the opposite, when opposing connectivity constraints,\nthe clusters form a nice parcellation of the swiss roll.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Authors : Vincent Michel, 2010\n#           Alexandre Gramfort, 2010\n#           Gael Varoquaux, 2010\n# License: BSD 3 clause\n\nprint(__doc__)\n\nimport time as time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.mplot3d.axes3d as p3\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.datasets.samples_generator import make_swiss_roll\n\n# #############################################################################\n# Generate data (swiss roll dataset)\nn_samples = 1500\nnoise = 0.05\nX, _ = make_swiss_roll(n_samples, noise)\n# Make it thinner\nX[:, 1] *= .5\n\n# #############################################################################\n# Compute clustering\nprint(\"Compute unstructured hierarchical clustering...\")\nst = time.time()\nward = AgglomerativeClustering(n_clusters=6, linkage='ward').fit(X)\nelapsed_time = time.time() - st\nlabel = ward.labels_\nprint(\"Elapsed time: %.2fs\" % elapsed_time)\nprint(\"Number of points: %i\" % label.size)\n\n# #############################################################################\n# Plot result\nfig = plt.figure()\nax = p3.Axes3D(fig)\nax.view_init(7, -80)\nfor l in np.unique(label):\n    ax.scatter(X[label == l, 0], X[label == l, 1], X[label == l, 2],\n               color=plt.cm.jet(np.float(l) / np.max(label + 1)),\n               s=20, edgecolor='k')\nplt.title('Without connectivity constraints (time %.2fs)' % elapsed_time)\n\n\n# #############################################################################\n# Define the structure A of the data. Here a 10 nearest neighbors\nfrom sklearn.neighbors import kneighbors_graph\nconnectivity = kneighbors_graph(X, n_neighbors=10, include_self=False)\n\n# #############################################################################\n# Compute clustering\nprint(\"Compute structured hierarchical clustering...\")\nst = time.time()\nward = AgglomerativeClustering(n_clusters=6, connectivity=connectivity,\n                               linkage='ward').fit(X)\nelapsed_time = time.time() - st\nlabel = ward.labels_\nprint(\"Elapsed time: %.2fs\" % elapsed_time)\nprint(\"Number of points: %i\" % label.size)\n\n# #############################################################################\n# Plot result\nfig = plt.figure()\nax = p3.Axes3D(fig)\nax.view_init(7, -80)\nfor l in np.unique(label):\n    ax.scatter(X[label == l, 0], X[label == l, 1], X[label == l, 2],\n               color=plt.cm.jet(float(l) / np.max(label + 1)),\n               s=20, edgecolor='k')\nplt.title('With connectivity constraints (time %.2fs)' % elapsed_time)\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.6.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}