原始问题:
python自编程实现层次聚类并绘制图像代码
以下是Python实现层次聚类并绘制图像的代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
# 生成随机数据
np.random.seed(4711)
a = np.random.multivariate_normal([10, 0], [[3, 1], [1, 4]], size=[100,])
b = np.random.multivariate_normal([0, 20], [[3, 1], [1, 4]], size=[50,])
X = np.concatenate((a, b),)
# 层次聚类
Z = linkage(X, 'ward')
# 绘制树状图
plt.figure(figsize=(25, 10))
plt.title('Hierarchical Clustering Dendrogram')
plt.xlabel('sample index')
plt.ylabel('distance')
dendrogram(Z, leaf_rotation=90., leaf_font_size=8.)
plt.show()
这段代码首先生成了一些随机数据,然后使用linkage
函数进行层次聚类,最后使用dendrogram
函数绘制树状图。其中,linkage
函数的第一个参数是数据集,第二个参数是指定聚类算法,这里使用的是ward
算法。dendrogram
函数的第一个参数是聚类结果,其余参数用于设置图像的样式。
Prev:层次聚类python代码