python kmeans聚类简单介绍和实现代码


Posted in Python onFebruary 23, 2018

一、k均值聚类的简单介绍

假设样本分为c类,每个类均存在一个中心点,通过随机生成c个中心点进行迭代,计算每个样本点到类中心的距离(可以自定义、常用的是欧式距离)  

将该样本点归入到最短距离所在的类,重新计算聚类中心,进行下次的重新划分样本,最终类中心不改变时,聚类完成   

二、伪代码  

三、python代码实现  

#!/usr/bin/env python 
# coding=utf-8 
 
import numpy as np 
import random 
import matplotlib.pyplot as plt 
 
#data:numpy.array dataset 
#k the number of cluster 
def k_means(data,k): 
   
  #random generate cluster_center 
  sample_num=data.shape[0] 
  center_index=random.sample(range(sample_num),k) 
  cluster_cen=data[center_index,:] 
 
  is_change=1 
  cat=np.zeros(sample_num) 
   
 
  while is_change: 
    is_change=0 
 
    for i in range(sample_num): 
      min_distance=100000 
      min_index=0 
 
      for j in range(k): 
        sub_data=data[i,:]-cluster_cen[j,:] 
        distance=np.inner(sub_data,sub_data) 
        if distance<min_distance: 
          min_distance=distance 
          min_index=j+1 
 
      if cat[i]!=min_index: 
        is_change=1 
        cat[i]=min_index 
    for j in range(k): 
      cluster_cen[j]=np.mean(data[cat==(j+1)],axis=0) 
 
  return cat,cluster_cen 
 
 
if __name__=='__main__': 
 
  #generate data 
  cov=[[1,0],[0,1]] 
  mean1=[1,-1] 
  x1=np.random.multivariate_normal(mean1,cov,200) 
 
  mean2=[5.5,-4.5] 
  x2=np.random.multivariate_normal(mean2,cov,200) 
 
  mean3=[1,4] 
  x3=np.random.multivariate_normal(mean3,cov,200) 
 
  mean4=[6,4.5] 
  x4=np.random.multivariate_normal(mean4,cov,200) 
 
  mean5=[9,0.0] 
  x5=np.random.multivariate_normal(mean5,cov,200) 
   
  X=np.vstack((x1,x2,x3,x4,x5)) 
   
  #data distribution 
  fig1=plt.figure(1) 
  p1=plt.scatter(x1[:,0],x1[:,1],marker='o',color='r',label='x1') 
  p2=plt.scatter(x2[:,0],x2[:,1],marker='+',color='m',label='x2') 
  p3=plt.scatter(x3[:,0],x3[:,1],marker='x',color='b',label='x3') 
  p4=plt.scatter(x4[:,0],x4[:,1],marker='*',color='g',label='x4') 
  p5=plt.scatter(x5[:,0],x4[:,1],marker='+',color='y',label='x5') 
  plt.title('original data') 
  plt.legend(loc='upper right') 
   
  cat,cluster_cen=k_means(X,5)    
 
  print 'the number of cluster 1:',sum(cat==1) 
  print 'the number of cluster 2:',sum(cat==2) 
  print 'the number of cluster 3:',sum(cat==3) 
  print 'the number of cluster 4:',sum(cat==4) 
  print 'the number of cluster 5:',sum(cat==5) 
 
   
  fig2=plt.figure(2) 
  for i,m,lo,label in zip(range(5),['o','+','x','*','+'],['r','m','b','g','y'],['x1','x2','x3','x4','x5']): 
 
    p=plt.scatter(X[cat==(i+1),0],X[cat==(i+1),1],marker=m,color=lo,label=label) 
  plt.legend(loc='upper right') 
  plt.title('the clustering result') 
  plt.show()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中list列表的一些进阶使用方法介绍
Aug 15 Python
python添加模块搜索路径方法
Sep 11 Python
selenium python浏览器多窗口处理代码示例
Jan 15 Python
Python实现自动上京东抢手机
Feb 06 Python
Python根据成绩分析系统浅析
Feb 11 Python
Python I/O与进程的详细讲解
Mar 08 Python
python3 selenium自动化测试 强大的CSS定位方法
Aug 23 Python
python中sort和sorted排序的实例方法
Aug 26 Python
python 通过文件夹导入包的操作
Jun 01 Python
利用python下载scihub成文献为PDF操作
Jul 09 Python
七个Python必备的GUI库
Apr 27 Python
python 提取html文本的方法
May 20 Python
python MysqlDb模块安装及其使用详解
Feb 23 #Python
Python实现k-means算法
Feb 23 #Python
python语言中with as的用法使用详解
Feb 23 #Python
python实现定时自动备份文件到其他主机的实例代码
Feb 23 #Python
Python机器学习算法之k均值聚类(k-means)
Feb 23 #Python
python3调用R的示例代码
Feb 23 #Python
python中kmeans聚类实现代码
Feb 23 #Python
You might like
php入门学习知识点一 PHP与MYSql连接与查询
2011/07/14 PHP
使用php伪造referer的方法 利用referer防止图片盗链
2014/01/20 PHP
php通过隐藏表单控件获取到前两个页面的url
2014/09/09 PHP
thinkphp模板继承实例简述
2014/11/26 PHP
基于php实现七牛抓取远程图片
2015/12/01 PHP
PHP中类属性与类静态变量的访问方法示例
2016/07/13 PHP
写了一个layout,拖动条连贯,内容区可为iframe
2007/08/19 Javascript
ASP SQL防注入的方法
2008/12/25 Javascript
jquery.qrcode在线生成二维码使用示例
2013/08/21 Javascript
YUI模块开发原理详解
2013/11/18 Javascript
用正则表达式替换图片地址img标签
2013/11/22 Javascript
Jquery中children与find之间的区别详细解析
2013/11/29 Javascript
浅析webapp框架AngularUI的demo
2014/12/21 Javascript
Vue表单实例代码
2016/09/05 Javascript
vue使用Google地图的实现示例代码
2018/12/19 Javascript
Mpvue中使用Vant Weapp组件库的方法步骤
2019/05/16 Javascript
VueJS 取得 URL 参数值的方法
2019/07/19 Javascript
ES6基础之数组和对象的拓展实例详解
2019/08/22 Javascript
layui 弹出层回调获取弹出层数据的例子
2019/09/02 Javascript
在vue中使用console.log无效的解决
2020/08/09 Javascript
解决pycharm双击但是无法打开的情况
2020/10/31 Javascript
[01:00:53]2018DOTA2亚洲邀请赛3月29日 小组赛B组 iG VS Secret
2018/03/30 DOTA
Python断言assert的用法代码解析
2018/02/03 Python
python自动发送测试报告邮件功能的实现
2019/01/22 Python
用django-allauth实现第三方登录的示例代码
2019/06/24 Python
python 机器学习之支持向量机非线性回归SVR模型
2019/06/26 Python
pytorch 可视化feature map的示例代码
2019/08/20 Python
pandas 中对特征进行硬编码和onehot编码的实现
2019/12/20 Python
python3实现语音转文字(语音识别)和文字转语音(语音合成)
2020/10/14 Python
什么是属性访问器
2015/10/26 面试题
综合素质评价个性发展自我评价
2015/03/06 职场文书
学校中秋节活动总结
2015/03/23 职场文书
2015年医院创卫工作总结
2015/04/22 职场文书
2015年政协委员工作总结
2015/05/20 职场文书
2016国培学习心得体会
2016/01/08 职场文书
入党申请书怎么写?
2019/06/11 职场文书