python实现k均值算法示例(k均值聚类算法)
时间:2021-04-24 20:27:39
简单实现平面的点K均值分析,使用欧几里得距离,并用pylab展示。
import pylab as pl
#calc Euclid squire
def calc_e_squire(a, b):
return (a[0]- b[0]) ** 2 + (a[1] - b[1]) **2
#init the 20 point
a = [2,4,3,6,7,8,2,3,5,6,12,10,15,16,11,10,19,17,16,13]
b = [5,6,1,4,2,4,3,1,7,9,16,11,19,12,15,14,11,14,11,19]
#define two k_value
k1 = [6,3]
k2 = [6,1]
#defint tow cluster
sse_k1 = []
sse_k2 = []
while True:
sse_k1 = []
sse_k2 = []
for i in range(20):
e_squire1 = calc_e_squire(k1, [a[i], b[i]])
e_squire2 = calc_e_squire(k2, [a[i], b[i]])
if (e_squire1 <= e_squire2):
sse_k1.append(i)
else:
sse_k2.append(i)
#change k_value
k1_x = sum([a[i] for i in sse_k1]) / len(sse_k1)
k1_y = sum([b[i] for i in sse_k1]) / len(sse_k1)
k2_x = sum([a[i] for i in sse_k2]) / len(sse_k2)
k2_y = sum([b[i] for i in sse_k2]) / len(sse_k2)
if k1 != [k1_x, k1_y] or k2 != [k2_x, k2_y]:
k1 = [k1_x, k1_y]
k2 = [k2_x, k2_y]
else:
break
kv1_x = [a[i] for i in sse_k1]
kv1_y = [b[i] for i in sse_k1]
kv2_x = [a[i] for i in sse_k2]
kv2_y = [b[i] for i in sse_k2]
pl.plot(kv1_x, kv1_y, 'o')
pl.plot(kv2_x, kv2_y, 'or')
pl.xlim(1, 20)
pl.ylim(1, 20)
pl.show()


猜你喜欢
CSS样式表中SPAN和DIV的区别

Python使用Pandas库常见操作详解
Python 实现文件的全备份和差异备份详解
python celery分布式任务队列的使用详解

python 通过dict(zip)和{}的方式构造字典的方法
JavaScript基本语法_动力节点Java学院整理
django中的图片验证码功能

Python实现的简单计算器功能详解

Python双版本计算器详解
asp数据转换函数示例
golang连接MongoDB数据库及数据库操作指南
python数字图像处理环境安装与配置过程示例

MySQL开发规范与使用技巧总结
Mysql语句快速复习教程(全)
会员下线加积分,实现原理分享(有时间限制)

SQL Server 复制需要有实际的服务器名称才能连接到服务器
Python爬虫爬取微信朋友圈

Python基础之字符串常见操作经典实例详解
Vue源码之关于vm.$delete()/Vue.use()内部原理详解
