Python实现k-means算法
作者:the_Chain_Warden 发布时间:2023-07-01 22:06:53
标签:Python,kmeans
本文实例为大家分享了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的运行结果,因为一开始的均值向量是随机的,所以每次运行结果会有不同。
来源:http://blog.csdn.net/WUTab/article/details/54602587


猜你喜欢
- 一、要求 1 创建数据表 CREATE TABLE [dbo].[StuScore]( [stuid] [int] NOT NULL, [s
- 本文实例讲述了JS截取与分割字符串的常用方法。分享给大家供大家参考,具体如下:JS截取字符串可使用 substring()或者slice()
- 一、百度百科1、MySQLMySQL声称自己是最流行的开源数据库。LAMP中的M指的就是MySQL。构建在LAMP上的应用都会使用MySQL
- 本文介绍在Python环境中,实现随机森林(Random Forest,RF)回归与各自变量重要性分析与排序的过程。其中,关于基于MATLA
- 在Python中定义一个数据便在内存中开辟一片空间来存储这个变量的值,这块已经被分配的内存空间便会有一个内存地址。访问这块内存需要用到变量名
- 说明 1. 状态机是一个非常实用的理论。在涉及到复杂的场景,建立状态机模型,能带来极大的方便。比如,网络连接、模型状态、业务逻辑。
- 前言前段时间学习了python的多线程爬虫,当时爬取一个图片网站,开启多线程后,并没有限制线程的数量,也就是说,如果下载1000张图片,会一
- 我们在使用很多新闻系统的时候,都会发现一个问题,尤其是使用 HtmlEdit 从WORD文档中直接拷贝文章(尤其里面有复杂表格和文字)的时候
- 第一步my-default.ini 添加配置:#绑定IPv4和3306端bind-address = 127.0.0.1port = 330
- tensorflow中可以通过配置环境变量 'TF_CPP_MIN_LOG_LEVEL' 的值,控制tensorflow是否
- 以连续3天为例,使用工具:MySQL。1.创建SQL表:create table if not exists orde(id varchar
- date("yyyyMMdd",time()) date() 函数功能:用于格式化时间,返回一个字符串。&nb
- 以这个为例: yyyy-MM-dd HH:mm:ss首先得写好你需要的模板options.sign =
- 自己前端开发中常用到的一些技巧及问题解决方法,会常更新,希望对前端路上的朋友有帮助。1、文章标题列表中日期居右显示的方法(提供了两种方法,使
- 新闻、文章系统中经常会用到的一个功能,添加上一篇,下一篇或相关文章的功能可以增加访客停留的时间。也许新人在做这上一篇、下一篇功能时使用的是I
- 1、代码from aip import AipFaceimport cv2import timeimport base64from PIL
- SQL Server数据库操作中,在2005以上的版本新增加了一个APPLY表运算符的功能。新增的APPLY表运算符把右表表达式应用到左表表
- 子节点部分选中时父节点也选中如果需求是:选中任何一个子节点都默认选择父节点,怎么办?其实,element-ui也提供了方案,常规下,如果子节
- 如下: Warning at /admin/assets/add/ Incorrect string value: '\xE5\x9
- 大家都熟悉迅雷看看里面的电影人气指数这个小图标吧先看看我的效果图再看看迅雷的截图比较好看,是根据电影的人气指数来显示热度,下面我们就来模仿一