Python实现简单层次聚类算法以及可视化
作者:York1996 时间:2023-09-04 00:16:21
本文实例为大家分享了Python实现简单层次聚类算法,以及可视化,供大家参考,具体内容如下
基本的算法思路就是:把当前组间距离最小的两组合并成一组。
算法的差异在算法如何确定组件的距离,一般有最大距离,最小距离,平均距离,马氏距离等等。
代码如下:
import numpy as np
import data_helper
np.random.seed(1)
def get_raw_data(n):
_data=np.random.rand(n,2)
#生成数据的格式是n个(x,y)
_groups={idx:[[x,y]] for idx,(x,y) in enumerate(_data)}
return _groups
def cal_distance(cluster1,cluster2):
#采用最小距离作为聚类标准
_min_distance=10000
for x1,y1 in cluster1:
for x2,y2 in cluster2:
_distance=(x1-x2)**2+(y1-y2)**2
if _distance<_min_distance:
_min_distance=_distance
return _distance
groups=get_raw_data(10)
count=0
while len(groups)!=1:#判断是不是所有的数据是不是归为了同一类
min_distance=10000
len_groups=len(groups)
for i in groups.keys():
for j in groups.keys():
if i>=j:
continue
distance=cal_distance(groups[i],groups[j])
if distance<min_distance:
min_distance=distance
min_i=i
min_j=j#这里的j>i
groups[min_i].extend(groups.pop(min_j))
data_helper.draw_data(groups)
#一共n个簇,共迭代n-1次
运行的效果就是迭代一次,组数就会少一次,调用画图方法,同一组的数据被显示为一个颜色。
来源:https://blog.csdn.net/york1996/article/details/86652330
标签:python,层次聚类算法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python next()和iter()函数原理解析
2023-04-05 21:58:50
Python中异常捕获与处理的方法总结
2023-12-10 07:48:24
![](https://img.aspxhome.com/file/2023/8/95898_0s.png)
浅谈优化Django ORM中的性能问题
2022-04-08 13:24:27
Python实现的几个常用排序算法实例
2021-08-13 07:42:54
python实现猜数游戏(保存游戏记录)
2022-08-31 09:39:54
关于ASP循环表格的问题之解答[比较详细]
2011-04-08 11:14:00
python文件处理笔记之文本文件
2022-10-30 22:38:32
![](https://img.aspxhome.com/file/2023/1/93841_0s.png)
python打包exe开机自动启动的实例(windows)
2023-11-08 06:34:00
D3.js实现拓扑图的示例代码
2024-05-09 10:20:06
![](https://img.aspxhome.com/file/2023/9/126869_0s.png)
Python MySQL数据库基本操作及项目示例详解
2024-01-13 06:15:27
Python 3中print函数的使用方法总结
2021-12-21 00:37:18
在python中实现导入一个需要传参的模块
2022-04-08 18:48:24
![](https://img.aspxhome.com/file/2023/4/111994_0s.png)
js实现向右横向滑出的二级菜单效果
2024-04-17 10:34:44
![](https://img.aspxhome.com/file/2023/9/136229_0s.jpg)
python 美化输出信息的实例
2022-04-15 09:53:54
![](https://img.aspxhome.com/file/2023/7/79757_0s.jpg)
PyQt5固定窗口大小的方法
2021-05-18 12:34:43
![](https://img.aspxhome.com/file/2023/0/99040_0s.jpg)
Python中的变量与常量
2022-01-14 22:26:43
![](https://img.aspxhome.com/file/2023/7/101197_0s.jpg)
Nginx搭建HTTPS服务器和强制使用HTTPS访问的方法
2021-06-26 12:42:36
![](https://img.aspxhome.com/file/2023/7/120297_0s.jpg)
Go语言配置数据库连接池的实现
2024-01-20 00:51:49
php中session使用示例
2024-04-30 08:46:58
网页中英文混排行高不等问题
2008-08-26 17:03:00
![](https://img.aspxhome.com/file/UploadPic/20088/26/200882617519588s.jpg)