【问题标题】:Dict of cluster and partition with kmeans python使用kmeans python进行集群和分区的字典
【发布时间】:2020-07-06 14:03:06
【问题描述】:

我正在寻找解决问题的方法。

我使用 sklearn 的 Kmeans,我想要一本带有 { cluster : list of partition} 的字典

kmeans = KMeans(n_clusters=n)
kmeans.fit(data)

result = zip(data,kmeans.labels_)
sortedR = sorted(result,key=lambda x: x[1])

cluster_nb = {}
for k,v in sortedR:
    if v in cluster_nb:
        cluster_nb[v].append(k)
    else:
        cluster_nb[v] = [k] 

我将 kmoyen.labels 集群的位置作为键,但我需要 kmoyen.cluster_centers_ 的相应元素

例如:

{'[1,2]' :  [array([1, 3]), array([2,4])], '[5,5]' : [array([7, 8]), array([10,12])]}

我尝试了一个新循环:

for x in cluster_nb:
    cluster_nb[str(kmeans.cluster_centers_[x])] = cluster_nb.pop(x)
return cluster_nb

但我有这个错误:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

我在哪里犯错了?

有没有更简单的解决方案?

【问题讨论】:

  • 确定:您正在尝试为每个集群检索属于该集群的输入数据的分区?
  • 可以,以分区簇坐标为key

标签: python arrays numpy dictionary k-means


【解决方案1】:

试试这个:

from sklearn.cluster import KMeans
import numpy as np

data = np.random.randint(100, size=(100, 2))
kmeans = KMeans(n_clusters=5)
kmeans.fit(data)

centroids_partitions = {}
for centr in kmeans.cluster_centers_:
    centroid_label = kmeans.predict([centr])
    partition = []
    for k, v in zip(data, kmeans.labels_):
        if v == centroid_label:
            partition.append(k.ravel())

    centroids_partitions[centroid_label[0]] = partition

print(centroids_partitions)

返回一个像这样的字典:

{0: [array([55,  8]), ... ,[truncated], 1: [array([70, 87]), array([77, 63]), ... ]}

其中 0、1 等是来自 kmeans.labels_ 的集群标签

或者,如果您想将质心作为字典的键进行协调,请替换为:

centroids_partitions[centr[0],centr[1]] = partition

输出:

{(68.29411764705881, 24.470588235294127): [array([72, 19]), array([69,  1]), array([58, 46]), .... ]}

【讨论】:

  • 非常感谢!这正是我想要的祝你有美好的一天
猜你喜欢
  • 2019-11-12
  • 2014-10-07
  • 2017-12-15
  • 2016-09-11
  • 2019-01-14
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
  • 2017-04-06
相关资源
最近更新 更多