Python中SKlearn中kmeans聚类


1.随机生成二维聚类数据

[python]  view plain  copy
  1. import numpy as np  
  2. x1 = np.array([1231565567899])  
  3. x2 = np.array([1322867671213])  
  4. x = np.array(list(zip(x1, x2))).reshape(len(x1), 2)  
  5. print x  
  6. # [[1 1]  
  7. #  [2 3]  
  8. #  [3 2]  
  9. #  [1 2]  
  10. #  [5 8]  
  11. #  [6 6]  
  12. #  [5 7]  
  13. #  [5 6]  
  14. #  [6 7]  
  15. #  [7 1]  
  16. #  [8 2]  
  17. #  [9 1]  
  18. #  [9 3]]  

2.生成聚类标签

[python]  view plain  copy
  1. from sklearn.cluster import KMeans  
  2. kmeans=KMeans(n_clusters=3)   #n_clusters:number of cluster  
  3. kmeans.fit(x)  
  4. print kmeans.labels_  
  5. #[0 0 0 0 2 2 2 2 2 1 1 1 1]  

3.显示聚类效果

[python]  view plain  copy
  1. import matplotlib.pyplot as plt  
  2. plt.figure(figsize=(8,10))  
  3. colors = ['b''g''r']  
  4. markers = ['o''s''D']  
  5. for i,l in enumerate(kmeans.labels_):  
  6.      plt.plot(x1[i],x2[i],color=colors[l],marker=markers[l],ls='None')  
  7. plt.show()  
效果如下图:

猜你喜欢

转载自blog.csdn.net/sinat_23338865/article/details/80406120