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()
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
网页屏蔽鼠标左右键和键盘按键功能
Python安装依赖(包)模块方法详解
PHP chunk_split()函数讲解
![](https://img.aspxhome.com/file/2023/5/55395_0s.png)
python画条形图实例
![](https://img.aspxhome.com/file/2023/7/98967_0s.jpg)
10个python3常用排序算法详细说明与实例(快速排序,冒泡排序,桶排序,基数排序,堆排序,希尔排序,归并排序,计数排序)
![](https://img.aspxhome.com/file/2023/8/88978_0s.png)
python中的循环结构问题
![](https://img.aspxhome.com/file/2023/2/76162_0s.png)
详解Python中的数据清洗工具flashtext
![](https://img.aspxhome.com/file/2023/5/69645_0s.png)
python项目对接钉钉SDK的实现
![](https://img.aspxhome.com/file/2023/9/88929_0s.jpg)
Python logging日志库空间不足问题解决
![](https://img.aspxhome.com/file/2023/8/105348_0s.png)
PHP curl get post 请求的封装函数示例【get、post、put、delete等请求类型】
Python流程控制 while循环实现解析
![](https://img.aspxhome.com/file/2023/9/86179_0s.jpg)
python中rc1什么意思
python字典按照value排序方法
Pytorch中使用TensorBoard详情
![](https://img.aspxhome.com/file/2023/3/115423_0s.gif)
深度辨析Python的eval()与exec()的方法
js与jquery获取父元素,删除子元素的两种不同方法
asp dictionary对象的用法
仿淘宝星级评分效果
Frontpage2003的怪bug,自动添加“../”的父级目录
![](https://img.aspxhome.com/file/UploadPic/20079/30/2007930133147256s.jpg)