{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Plot Hierarchical Clustering Dendrogram\nThis example plots the corresponding dendrogram of a hierarchical clustering\nusing AgglomerativeClustering and the dendrogram method available in scipy.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.cluster.hierarchy import dendrogram\n\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.datasets import load_iris\n\n\ndef plot_dendrogram(model, **kwargs):\n # Create linkage matrix and then plot the dendrogram\n\n # create the counts of samples under each node\n counts = np.zeros(model.children_.shape[0])\n n_samples = len(model.labels_)\n for i, merge in enumerate(model.children_):\n current_count = 0\n for child_idx in merge:\n if child_idx < n_samples:\n current_count += 1 # leaf node\n else:\n current_count += counts[child_idx - n_samples]\n counts[i] = current_count\n\n linkage_matrix = np.column_stack(\n [model.children_, model.distances_, counts]\n ).astype(float)\n\n # Plot the corresponding dendrogram\n dendrogram(linkage_matrix, **kwargs)\n\n\niris = load_iris()\nX = iris.data\n\n# setting distance_threshold=0 ensures we compute the full tree.\nmodel = AgglomerativeClustering(distance_threshold=0, n_clusters=None)\n\nmodel = model.fit(X)\nplt.title(\"Hierarchical Clustering Dendrogram\")\n# plot the top three levels of the dendrogram\nplot_dendrogram(model, truncate_mode=\"level\", p=3)\nplt.xlabel(\"Number of points in node (or index of point if no parenthesis).\")\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 }