【问题标题】:Finding the size of a specific k-means cluster查找特定 k-means 集群的大小
【发布时间】:2020-01-16 20:42:17
【问题描述】:

这个问题我已经有一段时间了,我似乎无法找到一种方法来获取特定集群中的数据点数量。到目前为止,这是我所拥有的:

第一个块输出我的 8 个集群中每个集群中的数据点数:

 def CountFrequency(my_list):  
    freq = {} 
    for item in my_list: 
        if (item in freq): 
            freq[item] += 1
        else: 
            freq[item] = 1

    for key, value in freq.items(): 
        print ("% d : % d"%(key, value)) 
​
def clusterCounts(df):

    df3 = df.fillna(df.mean())
    array3 = df3[['column1', 'column2', 'column3']].values
    kmeans = KMeans(n_clusters=8, random_state=42) 
    kmeans.fit(array3)
    return CountFrequency(kmeans.labels_) 

结果:

 1 :  26625
 6 :  2562
 2 :  9892
 7 :  2165
 3 :  1633
 0 :  3072
 4 :  1228
 5 :  4315
 None

(不知道为什么会有None,但我认为这是一个小问题)

我的下一个代码块为我的 8 个集群中的每一个打印质心:

def clusters(df):

    df3 = df.fillna(df.mean())
    array3 = df3[['column1', 'column2', 'column3']].values
    kmeans = KMeans(n_clusters=8, random_state=42) 
    kmeans.fit(array3)
    kmeans.labels_
    clusters = kmeans.cluster_centers_
    return clusters

结果:

[[49.2  2.4 48.4]
 [18.9 18.9 62.1]
 [ 0.2  0.4 99.4]
 [ 1.1 98.3  0.6]
 [98.2  1.   0.9]
 [33.3 32.7 34. ]
 [27.   1.2 71.7]
 [ 3.6 51.9 44.5]]

我正在尝试找到一种方法来找出具有[33.3 32.7 34. ] 质心的集群中有多少数据点。如何隔离这个质心的集群以获得它包含的数据点数量?作为第二个问题,我发布的第一个结果代码块中的键(每个集群的数据点数)是否与上述质心的顺序完全一致?我希望这很清楚,并提前感谢您!

【问题讨论】:

    标签: python machine-learning scikit-learn cluster-analysis k-means


    【解决方案1】:

    为什么你不做一个简单的

    for i in range(len(kmeans.cluster_centers)):
      print("Cluster", i)
      print("Center:", kmeans.cluster_centers_[i])
      print("Size:", sum(kmeans.labels_ == i))
    

    由于True将是1且False为0。

    【讨论】:

      猜你喜欢
      • 2016-11-24
      • 2015-09-18
      • 2018-10-04
      • 2019-11-26
      • 2014-09-15
      • 2012-11-01
      • 2012-11-06
      • 1970-01-01
      • 2020-10-24
      相关资源
      最近更新 更多