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
0
投稿
猜你喜欢
- 博主最近需要做一个物流信息查询,就去网上搜索一个快递鸟的API接口,返回值是以JSON格式,只需要返回是转成数组就能轻松实现各种实例了。下图
- 微信小程序全称微信公众平台·小程序,原名微信公众平台·应用号(简称微信应用号)声明•微信小程序开发工具类似于一个轻量级的IDE集成开发环境,
- 请问如何用OleDbDataAdapter来对数据库进行删除、修改和添加?OleDbDataAdapter是DataSet和数据源之间建立联
- Python中的penpyxl是一个第三方库,可以处理xlsx格式的Excel文件。pip install openpyxl安装。penpy
- 换脸!这段时间,deepfakes搞得火热,比方说把《射雕英雄传》里的朱茵换成了杨幂,看下面的图!毫无违和感!其实早在之前,基于AI换脸的技
- tkinter禁用(只读)下拉列表Comboboxtkinter将下拉列表框Combobox控件的状态设置为只读,也就是不可编辑状态:# 定
- 上次帮朋友写过的一个简单切换效果,超级简单,但也比较适用.因为用到了CSS Sprite技术,DEMO中附带了IE6兼容png的JS.核心J
- 问题描述:在画时间序列ACF时,调用from statsmodels.graphics.tsaplots import plot_acf,
- 想要在准备查询混合数据库系统时将SQL Server转换为 XQuery 和进行反向转换吗?了解如何开发 Web 服务来从SQL Serve
- 在本篇文章当中主要给大家介绍一个我们在使用类的时候经常使用但是却很少在意的黑科技——描述器,在本篇文
- 词云图from pyecharts.charts import WordClouddef word1(): words= [ &
- 这个目前还是有个别无法显示,翻了下msdn貌似没看到更好的解决方案,暂时放弃继续研究,有晓得完全解决的朋友不妨回复说一声。 先附bat创建畸
- 如何在线删除表或索引? <%Set conn1 = Server.CreateObject(&
- MS SQL基本语法及实例操作 一:建表并初始化 ============================ create database
- 首先,啰嗦几句废话如下: (1)触发器(trigger)是个特殊的存储过程,它的执行并不需要我们去显式调用,而是由一些事件触发,这有点类似C
- 点击顶部的“SQL”标签进入sql命令输入界面。输入以下命令:update mysql.user set password=PASSWORD
- 本文实例讲述了Python实现将HTML转换成doc格式文件的方法。分享给大家供大家参考,具体如下:网页上的一些文章,因为有格式的原因,它们
- 概述Python是个非常受欢迎的编程语言,随着近些年机器学习、云计算等技术的发展,Python的职位需求越来越高。下面我收集了10个Pyth
- 地址:https://youzan.github.io/vant/#/zh-CN/intro一.引入Vant组件库1.首先运行 npm in
- 1.获取所有数据库名: SELECT Name FROM Master..SysDatabases ORDER BY Name 2.获取所有