Python實現(xiàn)簡單層次聚類算法以及可視化
更新時間:2019年03月18日 09:45:09 作者:York1996
這篇文章主要為大家詳細介紹了Python實現(xiàn)簡單層次聚類算法以及可視化,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Python實現(xiàn)簡單層次聚類算法,以及可視化,供大家參考,具體內(nèi)容如下
基本的算法思路就是:把當前組間距離最小的兩組合并成一組。
算法的差異在算法如何確定組件的距離,一般有最大距離,最小距離,平均距離,馬氏距離等等。
代碼如下:
import numpy as np
import data_helper
np.random.seed(1)
def get_raw_data(n):
_data=np.random.rand(n,2)
#生成數(shù)據(jù)的格式是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:#判斷是不是所有的數(shù)據(jù)是不是歸為了同一類
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次
運行的效果就是迭代一次,組數(shù)就會少一次,調(diào)用畫圖方法,同一組的數(shù)據(jù)被顯示為一個顏色。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Django 返回json數(shù)據(jù)的實現(xiàn)示例
這篇文章主要介紹了Django 返回json數(shù)據(jù)的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03
基于Python執(zhí)行dos命令并獲取輸出的結(jié)果
這篇文章主要介紹了基于Python執(zhí)行dos命令并獲取輸出的結(jié)果,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12

