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 相关文章推荐
Python中的if、else、elif语句用法简明讲解
Mar 11 Python
Python自动发邮件脚本
Mar 31 Python
python数字图像处理之高级滤波代码详解
Nov 23 Python
python获取交互式ssh shell的方法
Feb 14 Python
Python 串口读写的实现方法
Jun 12 Python
使用Python实现跳一跳自动跳跃功能
Jul 10 Python
用python的turtle模块实现给女票画个小心心
Nov 23 Python
在 Pycharm 安装使用black的方法详解
Apr 02 Python
使用pandas库对csv文件进行筛选保存
May 25 Python
matplotlib教程——强大的python作图工具库
Oct 15 Python
利用python 下载bilibili视频
Nov 13 Python
python uuid生成唯一id或str的最简单案例
Jan 13 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
php smarty模版引擎中的缓存应用
2009/12/02 PHP
浅谈Coreseek、Sphinx-for-chinaese、Sphinx+Scws的区别
2016/12/15 PHP
PHP htmlspecialchars()函数用法与实例讲解
2019/03/08 PHP
js编码之encodeURIComponent使用介绍(asp,php)
2012/03/01 Javascript
你必须知道的JavaScript 中字符串连接的性能的一些问题
2013/05/07 Javascript
javascript操作Cookie(设置、读取、删除)方法详解
2015/03/18 Javascript
如何根据百度地图计算出两地之间的驾驶距离(两种语言js和C#)
2015/10/29 Javascript
location.hash保存页面状态的技巧
2016/04/28 Javascript
实例讲解Jquery中隐藏hide、显示show、切换toggle的用法
2016/05/13 Javascript
JavaScript必知必会(二) null 和undefined
2016/06/08 Javascript
微信小程序 教程之模块化
2016/10/17 Javascript
Bootstarp基本模版学习教程
2017/02/01 Javascript
JavaScript简单拖拽效果(1)
2017/05/17 Javascript
Vue2.0 slot分发内容与props验证的方法
2017/12/12 Javascript
基于three.js编写的一个项目类示例代码
2018/01/05 Javascript
jquery根据name取得select选中的值实例(超简单)
2018/01/25 jQuery
详解mpvue小程序中怎么引入iconfont字体图标
2018/10/01 Javascript
Vue.js watch监视属性知识点总结
2019/11/11 Javascript
微信小程序实现音频文件播放进度的实例代码
2020/03/02 Javascript
Vue实现开关按钮拖拽效果
2020/09/22 Javascript
python创建只读属性对象的方法(ReadOnlyObject)
2013/02/10 Python
Python读csv文件去掉一列后再写入新的文件实例
2017/12/28 Python
详解python 注释、变量、类型
2018/08/10 Python
Python第三方Window模块文件的几种安装方法
2018/11/22 Python
Python使用scrapy爬取阳光热线问政平台过程解析
2019/08/14 Python
用python爬取历史天气数据的方法示例
2019/12/30 Python
Python读写压缩文件的方法
2020/07/30 Python
使用Python爬取Json数据的示例代码
2020/12/07 Python
Python排序函数的使用方法详解
2020/12/11 Python
整理的15个非常有用的 HTML5 开发教程和速查手册
2011/10/18 HTML / CSS
HTML5手机端弹出遮罩菜单特效代码
2016/01/27 HTML / CSS
英文简历自荐信范文
2013/12/11 职场文书
工厂厂长的职责
2013/12/12 职场文书
大学生求职意向书
2015/05/11 职场文书
七个Python必备的GUI库
2021/04/27 Python
Win11 21h2可以升级22h2吗?看看你的电脑符不符合要求
2022/07/07 数码科技