sklearn 凝聚聚类输入数据

问题描述 投票:0回答:2

我有四个用户之间的相似度矩阵。我想做一个凝聚聚类。代码是这样的:

lena = np.matrix('1 1 0 0;1 1 0 0;0 0 1 0.2;0 0 0.2 1')
X = np.reshape(lena, (-1, 1))

print("Compute structured hierarchical clustering...")
st = time.time()
n_clusters = 3 # number of regionsle


ward = AgglomerativeClustering(n_clusters=n_clusters,
        linkage='complete').fit(X)
print ward
label = np.reshape(ward.labels_, lena.shape)
print("Elapsed time: ", time.time() - st)
print("Number of pixels: ", label.size)
print("Number of clusters: ", np.unique(label).size)
print label

标签打印结果如下:

[[1 1 0 0]
 [1 1 0 0]
 [0 0 1 2]
 [0 0 2 1]]

这是否意味着它给出了可能的聚类结果列表,我们可以从中选择一个?比如选择:[0,0,2,1]。如果错了,你能告诉我如何做基于相似度的凝聚算法吗?如果是正确的,相似度矩阵很大,我如何从一个巨大的列表中选择最佳的聚类结果?谢谢

python scikit-learn hierarchical-clustering
2个回答
2
投票

我认为这里的问题是你用错误的数据拟合模型

# This will return a 4x4 matrix (similarity matrix)
lena = np.matrix('1 1 0 0;1 1 0 0;0 0 1 0.2;0 0 0.2 1')

# However this will return 16x1 matrix
X = np.reshape(lena, (-1, 1))

你得到的真实结果是这样的:

 ward.labels_
 >> array([1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 2, 0, 0, 2, 1])

这是 X 向量中每个元素的标签,它没有意义

如果我很好地理解您的问题,您需要根据用户之间的距离(相似性)对用户进行分类。好吧,在这种情况下,我会建议以这种方式使用谱聚类:

import numpy as np
from sklearn.cluster import SpectralClustering

lena = np.matrix('1 1 0 0;1 1 0 0;0 0 1 0.2;0 0 0.2 1')

n_clusters = 3
SpectralClustering(n_clusters).fit_predict(lena)

>> array([1, 1, 0, 2], dtype=int32)

0
投票

为什么要重塑

X
?如果你不重塑
X
,它会给你正确的结果。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.