层次聚类树形图

Machine LearningMachine LearningBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将学习如何使用凝聚聚类(AgglomerativeClustering)和scipy中可用的树形图方法绘制层次聚类的相应树形图。

虚拟机提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签以访问Jupyter Notebook进行练习。

有时,你可能需要等待几秒钟让Jupyter Notebook完成加载。由于Jupyter Notebook的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,请随时向Labby提问。课程结束后提供反馈,我们将立即为你解决问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/UtilitiesandDatasetsGroup(["Utilities and Datasets"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn(("Sklearn")) -.-> sklearn/CoreModelsandAlgorithmsGroup(["Core Models and Algorithms"]) sklearn/CoreModelsandAlgorithmsGroup -.-> sklearn/cluster("Clustering") sklearn/UtilitiesandDatasetsGroup -.-> sklearn/datasets("Datasets") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/cluster -.-> lab-49063{{"层次聚类树形图"}} sklearn/datasets -.-> lab-49063{{"层次聚类树形图"}} ml/sklearn -.-> lab-49063{{"层次聚类树形图"}} end

导入必要的库

我们将从导入本实验所需的库开始。

import numpy as np
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram
from sklearn.datasets import load_iris
from sklearn.cluster import AgglomerativeClustering

加载数据集

我们将使用sklearn.datasets模块中的load_iris()函数来加载鸢尾花数据集。

iris = load_iris()
X = iris.data

创建模型

接下来,我们将使用sklearn.cluster模块中的AgglomerativeClustering()函数创建凝聚聚类模型。

model = AgglomerativeClustering(distance_threshold=0, n_clusters=None)

拟合模型

我们将使用模型对象的fit()方法来拟合凝聚聚类模型。

model = model.fit(X)

绘制树形图

我们将使用scipy.cluster.hierarchy模块中的dendrogram()函数以及原始代码中定义的plot_dendrogram()函数来绘制树形图。

plt.title("Hierarchical Clustering Dendrogram")
plot_dendrogram(model, truncate_mode="level", p=3)
plt.xlabel("Number of points in node (or index of point if no parenthesis).")
plt.show()

总结

在本实验中,我们学习了如何使用凝聚聚类(AgglomerativeClustering)以及scipy中可用的树形图方法来绘制层次聚类的相应树形图。我们加载了鸢尾花数据集,创建了一个凝聚聚类模型,并对该模型进行了拟合。最后,我们使用scipy.cluster.hierarchy模块中的dendrogram()函数以及原始代码中定义的plot_dendrogram()函数绘制了树形图。