如何在sic-kit学习K-means中检索聚类质心?

时间:2016-01-27 21:21:24

标签: python scikit-learn k-means

我使用这个简单的脚本使用sci-kit learn

来聚类数据
from sklearn.cluster import KMeans
import pandas as pd 
import matplotlib.pyplot as plt
X = pd.read_csv('TestData.csv')
est = KMeans(n_clusters=10)
Y = pd.DataFrame(est.fit_predict(X))
frames = [X,Y]
Out = pd.concat(frames, axis = 1)  

这给了我以下输出:

   (feat1) (feat2) (cluster ID) 
0   0.866  1124.182  9
1   2.078  2688.612  1
2   0.000     0.000  0
3   0.000     0.000  0
4   1.038  1344.306  6
5   2.388  3090.338  5
6   0.580   749.456  8
7   1.556  2016.456  2

我还要显示每个群集的质心,以便输出如下:

   (feat1) (feat2) (cluster ID) (centroid 1) (centroid 2)  
0   0.866  1124.182  9
1   2.078  2688.612  1
2   0.000     0.000  0
3   0.000     0.000  0
4   1.038  1344.306  6
5   2.388  3090.338  5
6   0.580   749.456  8
7   1.556  2016.456  2

我尝试使用est.cluster_centers_

但那并没有奏效。

如何获得正确的群集中心?

1 个答案:

答案 0 :(得分:3)

import sklearn.cluster as cluster
import pandas as pd 
import numpy as np 
np.random.seed(2016)

X = pd.DataFrame(np.random.random((100, 2)))
est = cluster.KMeans(n_clusters=10)
Y = pd.DataFrame(est.fit_predict(X), columns=['cluster ID'])
Z = pd.DataFrame(est.cluster_centers_[Y['cluster ID']], 
                 columns=['centroid_x', 'centroid_y'])
result = pd.concat([X, Y, Z], axis=1)  

print(result.head())

产量

          0         1  cluster ID  centroid_x  centroid_y
0  0.896705  0.730239           4    0.900182    0.772332
1  0.783276  0.741652           7    0.705625    0.720808
2  0.462090  0.642565           6    0.279384    0.689603
3  0.224864  0.708547           6    0.279384    0.689603
4  0.747126  0.625107           7    0.705625    0.720808

请注意,Z会向DataFrame添加大量重复信息。如果数据集很大,您不希望这样做。