层次聚类树形图

Beginner

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

简介

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

虚拟机提示

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

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

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

导入必要的库

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

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()函数绘制了树形图。