Python实现k-means算法


Posted in Python onFebruary 23, 2018

本文实例为大家分享了Python实现k-means算法的具体代码,供大家参考,具体内容如下

这也是周志华《机器学习》的习题9.4。

数据集是西瓜数据集4.0,如下

编号,密度,含糖率
1,0.697,0.46
2,0.774,0.376
3,0.634,0.264
4,0.608,0.318
5,0.556,0.215
6,0.403,0.237
7,0.481,0.149
8,0.437,0.211
9,0.666,0.091
10,0.243,0.267
11,0.245,0.057
12,0.343,0.099
13,0.639,0.161
14,0.657,0.198
15,0.36,0.37
16,0.593,0.042
17,0.719,0.103
18,0.359,0.188
19,0.339,0.241
20,0.282,0.257
21,0.784,0.232
22,0.714,0.346
23,0.483,0.312
24,0.478,0.437
25,0.525,0.369
26,0.751,0.489
27,0.532,0.472
28,0.473,0.376
29,0.725,0.445
30,0.446,0.459

算法很简单,就不解释了,代码也不复杂,直接放上来:

# -*- coding: utf-8 -*- 
"""Excercise 9.4"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sys
import random

data = pd.read_csv(filepath_or_buffer = '../dataset/watermelon4.0.csv', sep = ',')[["密度","含糖率"]].values

########################################## K-means ####################################### 
k = int(sys.argv[1])
#Randomly choose k samples from data as mean vectors
mean_vectors = random.sample(data,k)

def dist(p1,p2):
  return np.sqrt(sum((p1-p2)*(p1-p2)))
while True:
  print mean_vectors
  clusters = map ((lambda x:[x]), mean_vectors) 
  for sample in data:
    distances = map((lambda m: dist(sample,m)), mean_vectors) 
    min_index = distances.index(min(distances))
    clusters[min_index].append(sample)
  new_mean_vectors = []
  for c,v in zip(clusters,mean_vectors):
    new_mean_vector = sum(c)/len(c)
    #If the difference betweenthe new mean vector and the old mean vector is less than 0.0001
    #then do not updata the mean vector
    if all(np.divide((new_mean_vector-v),v) < np.array([0.0001,0.0001]) ):
      new_mean_vectors.append(v)  
    else:
      new_mean_vectors.append(new_mean_vector)  
  if np.array_equal(mean_vectors,new_mean_vectors):
    break
  else:
    mean_vectors = new_mean_vectors 

#Show the clustering result
total_colors = ['r','y','g','b','c','m','k']
colors = random.sample(total_colors,k)
for cluster,color in zip(clusters,colors):
  density = map(lambda arr:arr[0],cluster)
  sugar_content = map(lambda arr:arr[1],cluster)
  plt.scatter(density,sugar_content,c = color)
plt.show()

运行方式:在命令行输入 python k_means.py 4。其中4就是k。
下面是k分别等于3,4,5的运行结果,因为一开始的均值向量是随机的,所以每次运行结果会有不同。

Python实现k-means算法

Python实现k-means算法

Python实现k-means算法

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

Python 相关文章推荐
非递归的输出1-N的全排列实例(推荐)
Apr 11 Python
python3.4用循环往mysql5.7中写数据并输出的实现方法
Jun 20 Python
Python 将pdf转成图片的方法
Apr 23 Python
python数字图像处理实现直方图与均衡化
May 04 Python
python实现事件驱动
Nov 21 Python
Linux下远程连接Jupyter+pyspark部署教程
Jun 21 Python
django fernet fields字段加密实践详解
Aug 12 Python
python如何将两个txt文件内容合并
Oct 18 Python
Python matplotlib模块及柱状图用法解析
Aug 10 Python
详解Django ORM引发的数据库N+1性能问题
Oct 12 Python
python 模拟登录B站的示例代码
Dec 15 Python
Python字典和列表性能之间的比较
Jun 07 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
python实现SOM算法
Feb 23 #Python
python实现k-means聚类算法
Feb 23 #Python
You might like
全新的PDO数据库操作类php版(仅适用Mysql)
2012/07/22 PHP
如何利用PHP执行.SQL文件
2013/07/05 PHP
PHP中对缓冲区的控制实现代码
2013/09/29 PHP
php下载excel无法打开的解决方法
2013/12/24 PHP
PHP提示Cannot modify header information - headers already sent by解决方法
2014/09/22 PHP
php实现只保留mysql中最新1000条记录
2015/06/18 PHP
juqery 学习之三 选择器 子元素与表单
2010/11/25 Javascript
JQuery设置时间段下拉选择实例
2014/12/30 Javascript
实现无刷新联动例子汇总
2015/05/20 Javascript
jquery点击缩略图切换视频播放特效代码分享
2015/09/15 Javascript
JS DOM实现鼠标滑动图片效果
2020/09/17 Javascript
jQuery实现的简单百分比进度条效果示例
2016/08/01 Javascript
Node.js的环境安装配置(使用nvm方式)
2016/10/11 Javascript
运用jQuery写的验证表单(实例讲解)
2017/07/06 jQuery
收集前端面试题之url、href、src
2018/03/22 Javascript
微信小程序实现自定义picker选择器弹窗内容
2020/05/26 Javascript
js实现内置计时器
2019/12/16 Javascript
关于vue 结合原生js 解决echarts resize问题
2020/07/26 Javascript
vue项目接口管理,所有接口都在apis文件夹中统一管理操作
2020/08/13 Javascript
[01:35]2018年度CS GO最佳战队-完美盛典
2018/12/17 DOTA
[56:48]FNATIC vs EG 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/16 DOTA
[41:11]完美世界DOTA2联赛PWL S2 Inki vs Magma 第一场 11.22
2020/11/24 DOTA
python uuid模块使用实例
2015/04/08 Python
在windows下快速搭建web.py开发框架方法
2016/04/22 Python
python自定义函数实现一个数的三次方计算方法
2019/01/20 Python
Python 微信之获取好友昵称并制作wordcloud的实例
2019/02/21 Python
python 模拟贷款卡号生成规则过程解析
2019/08/30 Python
Keras 数据增强ImageDataGenerator多输入多输出实例
2020/07/03 Python
解决Pyinstaller打包软件失败的一个坑
2021/03/04 Python
利用html5的websocket实现websocket聊天室
2013/12/12 HTML / CSS
英国骑行、跑步、游泳、铁人三项运动装备专卖店:Wiggle
2016/08/23 全球购物
安全责任书模板
2014/07/22 职场文书
放飞梦想演讲稿600字
2014/08/26 职场文书
镇政府副镇长群众路线专题民主生活会对照检查材料
2014/09/19 职场文书
领导干部失职检讨书
2015/05/05 职场文书
Python使用pyecharts控件绘制图表
2022/06/05 Python