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()  
效果如下图:

  • 7
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值