fcluster()函数的使用案例:对多维度数据进行聚类分析
fcluster()函数是scipy.cluster.hierarchy模块中的一个函数,用于对层次聚类进行扁平化处理,并将聚类结果返回为一维数组。
层次聚类是一种聚类方法,可用于对多维度数据进行聚类分析。它的基本思想是通过计算数据点之间的距离来构建聚类树,并根据树的结构将数据点分组成不同的聚类。
fcluster()函数可以通过指定阈值或聚类数目来完成扁平化处理,具体用法如下:
fcluster(Z, t, criterion='inconsistent', depth=2, R=None, monocrit=None)
其中,Z是层次聚类的结果,t是阈值或聚类数目,criterion是选择聚类结果的标准,depth是层次的深度,R是每个聚类簇的样本数目,monocrit是一个可选的单一类标准。
下面通过一个例子来说明fcluster()函数的使用。
假设我们有一个包含两个特征的数据集,其中每个特征的取值范围分别是[0, 1]和[0, 10],我们希望对这些数据进行聚类分析。
首先,我们需要先导入必要的函数和生成数据集,具体代码如下:
import numpy as np from scipy.cluster.hierarchy import dendrogram, linkage from matplotlib import pyplot as plt # 生成数据集 np.random.seed(0) features = np.concatenate((np.random.rand(100, 1), np.random.rand(100, 1) * 10), axis=1)
接下来,我们可以使用linkage()函数构建层次聚类的树状图,并通过dendrogram函数绘制该图。具体代码如下:
# 构建层次聚类树状图
Z = linkage(features, 'ward')
# 绘制树状图
plt.figure(figsize=(10, 6))
plt.title('Hierarchical Clustering Dendrogram')
plt.xlabel('Data points')
plt.ylabel('Distance')
dendrogram(Z)
plt.show()
通过运行以上代码,我们可以得到如下的聚类树状图:

树状图展示了数据点之间的聚类关系,通过观察树状图,我们可以选择阈值或者聚类数目来完成聚类结果的扁平化处理。
我们可以通过fcluster()函数来获取聚类结果,并将其返回为一维数组。具体代码如下:
from scipy.cluster.hierarchy import fcluster # 获取聚类结果 clusters = fcluster(Z, 2, criterion='maxclust') # 打印聚类结果 print(clusters)
以上代码中,我们通过fcluster(Z, 2, criterion='maxclust')指定聚类数目为2,并利用'maxclust'标准来选择聚类结果。运行以上代码,我们可以得到如下的聚类结果:
`
[1 1 2 1 2 1 1 1 2 2 2 1 1 1 2 2 1 2 2 1 2 2 1 2 2 2 1 1 2 2 2 2 2 1 1 2 2 1
1 2 2 1 1 2 2 2 1 2 2 2 2 2 1 2 1 2 2 2 2 2 2 1 2 1 1 2 1 2 1 2 2 1 2 1 2 1
2 2 1 1 2 1 2 2 1 2 1 1 2 2 2 2 2 1 1 2 1 2 2 1 2 2 2 2 1 2 1 2 2 2 1 2 1 1
1 1 2 2 2 2 1 2 2 2 2 2 2 1 1 1 1 2 1 2 2 1 2 2 2 2 1 1 2 1 2 1 1 1 1 2 2 1
1 1 2 2 1 2 1 2 2 1 2 2 2 2 2 2 2 1 1 1 1 2 1 2 2 1 2 2 2 2 1 1 2 1 1 1 2 1
1 2 2 2 1 2 2 1 2 2 2 1 2 1 2 2 1 2 1 1 1 2 1 2 2 1 1
