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字典DICT类型合并详解
Aug 17 Python
Python编程实现正则删除命令功能
Aug 30 Python
Windows系统下PhantomJS的安装和基本用法
Oct 21 Python
Python实现截取PDF文件中的几页代码实例
Mar 11 Python
python fuzzywuzzy模块模糊字符串匹配详细用法
Aug 29 Python
numpy实现神经网络反向传播算法的步骤
Dec 24 Python
python 实现list或string按指定分段
Dec 25 Python
pytorch: Parameter 的数据结构实例
Dec 31 Python
TensorFlow tf.nn.max_pool实现池化操作方式
Jan 04 Python
Python3加密解密库Crypto的RSA加解密和签名/验签实现方法实例
Feb 11 Python
OpenCV灰度化之后图片为绿色的解决
Dec 01 Python
Python开发.exe小工具的详细步骤
Jan 27 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新建类问题分析及解决思路
2015/11/19 PHP
php7 图形用户界面GUI 开发示例
2020/02/22 PHP
基于jQuery的树控件实现代码(asp.net+json)
2010/07/11 Javascript
jQuery 取值、赋值的基本方法整理
2014/03/31 Javascript
js判断变量初始化的三种形式及推荐用的形式
2014/07/22 Javascript
JavaScript获取图片真实大小代码实例
2014/09/24 Javascript
Jquery结合HTML5实现文件上传
2015/06/25 Javascript
jQuery实现浮动层随浏览器滚动条滚动的方法
2015/09/22 Javascript
js实现的奥运倒计时时钟效果代码
2015/12/09 Javascript
vue.js利用defineProperty实现数据的双向绑定
2017/04/28 Javascript
angular+webpack2实战例子
2017/05/23 Javascript
微信小程使用swiper组件实现图片轮播切换显示功能【附源码下载】
2017/12/12 Javascript
Vue实现点击当前元素以外的地方隐藏当前元素(实现思路)
2019/12/04 Javascript
[02:28]DOTA2英雄基础教程 灰烬之灵
2013/12/19 DOTA
Python中的os.path路径模块中的操作方法总结
2016/07/07 Python
使用python调用zxing库生成二维码图片详解
2017/01/10 Python
浅谈pandas用groupby后对层级索引levels的处理方法
2018/11/06 Python
pyqt5实现俄罗斯方块游戏
2019/01/11 Python
python实现比较类的两个instance(对象)是否相等的方法分析
2019/06/26 Python
Python进程间通信 multiProcessing Queue队列实现详解
2019/09/23 Python
python中pandas库中DataFrame对行和列的操作使用方法示例
2020/06/14 Python
Python虚拟环境库virtualenvwrapper安装及使用
2020/06/17 Python
css3进行截取替代js的substring
2013/09/02 HTML / CSS
AmazeUI图片轮播效果的示例代码
2020/08/20 HTML / CSS
巴西儿童时尚购物网站:Dinda
2019/08/14 全球购物
C语言面试题
2015/10/30 面试题
护理学中专毕业生求职信
2013/11/11 职场文书
办公室副主任岗位职责
2013/11/25 职场文书
创业计划书的内容步骤和要领
2014/01/04 职场文书
初三物理教学反思
2014/01/21 职场文书
合作协议书范文
2014/08/20 职场文书
致800米运动员广播稿(10篇)
2014/10/17 职场文书
职工的安全责任书范文!
2019/07/02 职场文书
导游词之襄阳古城
2019/09/27 职场文书
解决SpringBoot文件上传临时目录找不到的问题
2021/07/01 Java/Android
http通过StreamingHttpResponse完成连续的数据传输长链接方式
2022/02/12 Python