【问题标题】:How to extract and map cluster indices from sklearn.cluster.KMeans?如何从 sklearn.cluster.KMeans 中提取和映射集群索引?
【发布时间】:2019-12-02 02:12:26
【问题描述】:

我有一张数据地图:

import seaborn as sns
import matplotlib.pyplot as plt

X = 101_by_99_float32_array
ax = sns.heatmap(X, square = True)
plt.show()

请注意,这些数据本质上是一个 3D 表面,我对聚类后X 中的索引位置感兴趣。我可以轻松地将 kmeans 算法应用于我的数据:

from sklearn.cluster import KMeans
# three clusters is arbitrary; just used for testing purposes
k_means = KMeans(init='k-means++', n_clusters=3, n_init=10).fit(X)

但我不确定如何导航kmeans,以识别上面地图中的像素属于哪个集群。我想要做的是制作一张看起来像上面的地图,但不是为 100x99 数组 X 中的每个单元格绘制 z 值,我想绘制 簇号 对于X 中的每个单元格。

我不知道kmeans算法的输出是否可行,但我确实尝试了scikitlearn文档here中的一种方法:

import numpy as np
k_means_labels = k_means.labels_
k_means_cluster_centers = k_means.cluster_centers_
k_means_labels_unique = np.unique(k_means_labels)

colors = ['#4EACC5', '#FF9C34', '#4E9A06']
plt.figure()
#plt.hold(True)
for k, col in zip(range(3), colors):
    my_members = k_means_labels == k
    cluster_center = k_means_cluster_centers[k]
    plt.plot(X[my_members, 0], X[my_members, 1], 'w',
            markerfacecolor=col, marker='.')
    plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
            markeredgecolor='k', markersize=6)
plt.title('KMeans')    
plt.show()

但很明显,这不是访问我想要的信息......

很明显,我没有完全理解kmeans 输出的每个组成部分代表什么,我尝试阅读here 问题答案中的解释。但是,该答案中没有任何内容明确说明在聚类后是否保留了原始数据的索引,这确实是我问题的核心。如果这些信息通过一些矩阵乘法隐含在kmeans 中,我真的可以使用一些帮助来提取它。

感谢您的时间和帮助!

编辑

感谢@Nakor,感谢他对 kmeans 的解释和重塑我的数据的建议。 kmeans 如何解释我的数据现在更加清晰。我不应该期望它捕获每个样本的索引,而是依靠reshape 来做到这一点。 reshaperavel 将原始 (101,99) 矩阵转换为 (9999,1) 数组,正如@Nakor 指出的那样,它适合将每个条目作为单独的样本进行聚类。

只需使用数据的原始形状将reshape 重新应用到kmeans.labels_,我就得到了我正在寻找的结果:

Y = X.reshape(-1, 1) # shape data to cluster each individual entry 

kmeans= KMeans(init='k-means++', n_clusters=3, n_init=10)
kmeans.fit(Y)

Z = kmeans.labels_
A = Z.reshape(101,99)

plt.figure()
ax = sns.heatmap(cu_map, square = True)
plt.figure()
ay = sns.heatmap(A, square = True)

【问题讨论】:

    标签: python scikit-learn k-means


    【解决方案1】:

    您的问题是sklearn.cluster.KMeans预计使用[N_samples,N_features]的2D矩阵。但是,您提供了原始图像,因此Sklearn了解您有101个样本,每个功能99个功能(每行图像是示例,并且列是特征的列。作为结果,您在k_means.labels_是每个行的群集分配。

    在您想要群集每一个条目时,您需要重新塑造像这样的数据:

    model = KMeans(init='k-means++', n_clusters=3, n_init=10)
    model.fit(X.reshape(-1,1))
    

    如果我检查随机生成的数据,我得到:

    In [1]: len(model.labels_)
    Out[1]: 9999
    

    每个条目有一个标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      • 2020-02-23
      • 1970-01-01
      • 2019-10-13
      相关资源
      最近更新 更多