首页 > 其他 > 详细

Scikit-learn的kmeans聚类

时间:2018-04-18 23:03:39      阅读:253      评论:0      收藏:0      [点我收藏+]

1. 生成随机的二维数据:

import numpy as np  
x1 = np.array([1, 2, 3, 1, 5, 6, 5, 5, 6, 7, 8, 9, 9])  
x2 = np.array([1, 3, 2, 2, 8, 6, 7, 6, 7, 1, 2, 1, 3])  
x = np.array(list(zip(x1, x2))).reshape(len(x1), 2) #先将x1和x2用zip组合,然后再转换成list,最后reshape

print (x)

  

2.生成聚类标签:

from sklearn.cluster import KMeans  
kmeans=KMeans(n_clusters=3)   #n_clusters:number of cluster  
kmeans.fit(x)  
print (kmeans.labels_)

  

3.显示聚类效果:

import matplotlib.pyplot as plt  
plt.figure(figsize=(5,5))  
colors = [‘b‘, ‘g‘, ‘r‘]  
markers = [‘o‘, ‘s‘, ‘D‘]  
for i,l in enumerate(kmeans.labels_):  
     plt.plot(x1[i],x2[i],color=colors[l],marker=markers[l],ls=‘None‘)  
plt.show() 

  

技术分享图片

参考: https://blog.csdn.net/qq_34264472/article/details/53217748  (此为python2代码)

Scikit-learn的kmeans聚类

原文:https://www.cnblogs.com/Allen-rg/p/8878019.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!