python - sklearn 凝聚聚类输入数据

标签 python scikit-learn hierarchical-clustering

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

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]。如果错了,你能告诉我如何做基于相似性的凝聚算法吗?如果正确,相似度矩阵很大,如何从庞大的列表中选择最优的聚类结果?谢谢

最佳答案

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

# 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)

关于python - sklearn 凝聚聚类输入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33023085/

相关文章:

python - 层次聚类的阈值

algorithm - 如何计算聚类熵 - 给出的示例和我的解决方案是否正确?

nltk - 互联网文章和社交媒体的层次分类+主题模型训练数据

python - 在 Python 语法中调用函数

php - 从 PHP - Linux 执行 python 文件

python - Sqlalchemy mySQL 优化查询

python - 使用 SciKit-learn 和大型数据集进行文本分类

python - 使用 scikit learn 在 Python 中导入数据集以解决机器学习问题数据集威斯康星州乳腺癌

python - Ubuntu 中的 Zipline - 安装错误

python-2.7 - 如何使用 scikit-learn 只删除多项式回归中的交互项?