我正在尝试在python中使用kmeans。

data = [[1,2,3,4,5],[1,0,3,2,4],[4,3,234,5,5],[23,4,5,1,4],[23,5,2,3,5]]

每个数据都有一个标签。例子:
[1,2,3,4,5] -> Fiat1
[1,0,3,2,4] -> Fiat2
[4,3,234,5,5] -> Mercedes
[23,4,5,1,4] -> Opel
[23,5,2,3,5] -> bmw

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

我的目标是运行KMeans之后,我想要获得每个群集的标签。

假的例子:

集群1:
菲亚特1
菲亚特2

丛集2:
梅赛德斯

群组3:
宝马,
欧宝

我怎样才能做到这一点 ?

最佳答案

代码

from sklearn.cluster import KMeans
import numpy as np

data = np.array([[1,2,3,4,5],[1,0,3,2,4],[4,3,234,5,5],[23,4,5,1,4],[23,5,2,3,5]])
labels = np.array(['Fiat1', 'Fiat2', 'Mercedes', 'Opel', 'BMW'])
N_CLUSTERS = 3

kmeans = KMeans(init='k-means++', n_clusters=N_CLUSTERS, n_init=10)
kmeans.fit(data)
pred_classes = kmeans.predict(data)

for cluster in range(N_CLUSTERS):
    print('cluster: ', cluster)
    print(labels[np.where(pred_classes == cluster)])

输出:
cluster:  0
['Opel' 'BMW']
cluster:  1
['Mercedes']
cluster:  2
['Fiat1' 'Fiat2']

关于python - 为sklearn k-means添加标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38425990/

10-12 19:29