使用相似矩阵的层次分层聚类聚类

时间:2017-11-16 03:34:48

标签: python pandas scikit-learn hierarchical-clustering

给定距离矩阵,各教授之间具有相似性:

              prof1     prof2     prof3
       prof1     0        0.8     0.9
       prof2     0.8      0       0.2
       prof3     0.9      0.2     0

我需要对这些数据执行分层聚类,其中上述数据采用二维矩阵

       data_matrix=[[0,0.8,0.9],[0.8,0,0.2],[0.9,0.2,0]]

我尝试检查是否可以使用sklearn.cluster AgglomerativeClustering来实现它,但是它将所有3行视为3个单独的向量而不是距离矩阵。可以使用this或scipy.cluster.hierarchy来完成吗?

3 个答案:

答案 0 :(得分:5)

是的,您可以使用sklearn执行此操作。你需要设置:

  • affinity='precomputed',使用距离矩阵
  • linkage='complete''average',因为默认链接(Ward)仅适用于坐标输入。

通过预先计算的亲和力,输入矩阵被解释为观察之间的距离矩阵。以下代码

from sklearn.cluster import AgglomerativeClustering
data_matrix = [[0,0.8,0.9],[0.8,0,0.2],[0.9,0.2,0]]
model = AgglomerativeClustering(affinity='precomputed', n_clusters=2, linkage='complete').fit(data_matrix)
print(model.labels_)

将返回标签[1 0 0]:第一个教授转到一个群集,第二个和第三个教授转到另一个群集。

答案 1 :(得分:0)

此处的输入data_matrix必须是距离矩阵,与给定的相似性矩阵不同,并且因为两者都与度量完全相反,并且使用一个替代其他度量会产生相当多的任意结果。检查正式文档[如果“预先计算”,则需要距离矩阵(而不是相似度矩阵)作为拟合方法的输入。”]:https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html

作为一种解决方案,可以使用相似度= 1-距离矩阵(假设距离矩阵在0和1之间归一化),然后将其用作输入。

我已经在几个示例上进行了尝试,并进行了验证,因此应该可以完成工作。

答案 2 :(得分:0)

您也可以使用scipy.cluster.hierarchy做到这一点:

from scipy.cluster.hierarchy import dendrogram, linkage, cut_tree
from matplotlib import pyplot as plt

# Data
X =[[0,0.8,0.9],[0.8,0,0.2],[0.9,0.2,0]]
labels = ['prof1','prof2','prof3']

# Perform clustering, you can choose the method
# in this case, we use 'ward'
Z = linkage(X, 'ward')

# Extract the membership to a cluster, either specify the n_clusters
# or the cut height
# (similar to sklearn labels)
print(cut_tree(Z, n_clusters=2))

# Visualize the clustering as a dendogram
fig = plt.figure(figsize=(25, 10))
dn = dendrogram(Z, orientation='right', labels=labels)
plt.show()

这将打印:

[[0]
 [1]
 [1]]

由于我们指定了n_cluster 2,这意味着有2个集群。 prof1属于群集0,prof2和prof3属于群集1。您还可以指定cut_height而不是群集的数量。 树状图如下所示:

![两个树状图] [1] https://imgur.com/EF0cW4U.png“树状图”

相关问题