1、脚本
# scikit-learn 没有绘制树状图的功能,需借助 SciPy 库完成
import matplotlib.pyplot as plt from sklearn.datasets import make_blobs from scipy.cluster.hierarchy import dendrogram, ward # 生成模拟数据
X, y = make_blobs(n_samples=13, random_state=42 ) # 在数据组 X 上应用 ward 聚类函数,返回聚类过程中所跨越距离的数组
linkage_array = ward(X) # 绘制树状图
dendrogram(linkage_array) # 标记数中划分为两个和三个簇的位置
ax = plt.gca() bounds = ax.get_xbound() plt.plot(bounds, [27, 27], '-.', c='y') plt.plot(bounds, [14, 14], '-.', c='y' ) plt.text(x=bounds[1], y=27, s=' two clusters', va='center', fontsize=15 ) # 添加文本注释
plt.text(x=bounds[1], y=14, s=' three clusters', va='center', fontsize=15 ) # 调整子区布局
plt.subplots_adjust(left=0.1, right=0.75, top=0.9, bottom=0.1 ) plt.show()
2、聚类过程的示意树状图
3、按语
此树状图的底部显示的是数据点,这些数据点作为叶节点最终形成一棵聚类树,每合并两个两个簇就生成一个父节点。