ML之HierarchicalClustering:自定义HierarchicalClustering层次聚类算法

简介: ML之HierarchicalClustering:自定义HierarchicalClustering层次聚类算法

输出结果

更新中

实现代码

# -*- encoding=utf-8 -*-

from numpy import *

class cluster_node:  #定义cluster_node类,类似Java中的构造函数

   def __init__(self,vec,left=None,right=None,distance=0.0,id=None,count=1):

       self.left=left  

       self.right=right

       self.vec=vec

       self.id=id

       self.distance=distance

       self.count=count #only used for weighted average

def L2dist(v1,v2):  

   return sqrt(sum((v1-v2)**2))

 

def L1dist(v1,v2):  

   return sum(abs(v1-v2))

def hcluster(features,distance=L2dist):

   #cluster the rows of the "features" matrix

   distances={}    

   currentclustid=-1

   # clusters are initially just the individual rows

   clust=[cluster_node(array(features[i]),id=i) for i in range(len(features))]

   while len(clust)>1:  

       lowestpair=(0,1)

       closest=distance(clust[0].vec,clust[1].vec)

 

       for i in range(len(clust)):

           for j in range(i+1,len(clust)):

               # distances is the cache of distance calculations

               if (clust[i].id,clust[j].id) not in distances:

                   distances[(clust[i].id,clust[j].id)]=distance(clust[i].vec,clust[j].vec)

     

               d=distances[(clust[i].id,clust[j].id)]  

     

               if d<closest:  

                   closest=d

                   lowestpair=(i,j)

     

       mergevec=[(clust[lowestpair[0]].vec[i]+clust[lowestpair[1]].vec[i])/2.0 \

           for i in range(len(clust[0].vec))]

     

       newcluster=cluster_node(array(mergevec),left=clust[lowestpair[0]],

                            right=clust[lowestpair[1]],

                            distance=closest,id=currentclustid)

     

       currentclustid-=1  

       del clust[lowestpair[1]]

       del clust[lowestpair[0]]

       clust.append(newcluster)

   return clust[0]

def extract_clusters(clust,dist):  #(clust上边的树形结构,dist阈值)

   # extract list of sub-tree clusters from hcluster tree with distance<dist

   clusters = {}

   if clust.distance<dist:

       # we have found a cluster subtree

       return [clust]

   else:

       # check the right and left branches

       cl = []  

       cr = []

       if clust.left!=None:  

           cl = extract_clusters(clust.left,dist=dist)

       if clust.right!=None:

           cr = extract_clusters(clust.right,dist=dist)

       return cl+cr  

     

def get_cluster_elements(clust):  #用于取出算好聚类的元素

   # return ids for elements in a cluster sub-tree

   if clust.id>=0:  

       # positive id means that this is a leaf

       return [clust.id]

   else:

       # check the right and left branches

       cl = []

       cr = []

       if clust.left!=None:

           cl = get_cluster_elements(clust.left)

       if clust.right!=None:

           cr = get_cluster_elements(clust.right)

       return cl+cr

def printclust(clust,labels=None,n=0):  #将值打印出来

   # indent to make a hierarchy layout

   for i in range(n): print (' '),

   if clust.id<0:

       # negative id means that this is branch

       print ('-')

   else:          

       # positive id means that this is an endpoint

       if labels==None: print (clust.id)

       else: print (labels[clust.id])

 

   if clust.left!=None: printclust(clust.left,labels=labels,n=n+1)

   if clust.right!=None: printclust(clust.right,labels=labels,n=n+1)

def getheight(clust):  #树的高度,递归方法

   # Is this an endpoint? Then the height is just 1

   if clust.left==None and clust.right==None: return 1

 

   # Otherwise the height is the same of the heights of

   # each branch

   return getheight(clust.left)+getheight(clust.right)

def getdepth(clust):   #树的深度,递归方法

   if clust.left==None and clust.right==None: return 0

 

   return max(getdepth(clust.left),getdepth(clust.right))+clust.distance

   

   


相关文章
|
5月前
|
算法 数据可视化 数据挖掘
使用Python实现层次聚类算法
使用Python实现层次聚类算法
71 1
|
5月前
|
算法
自定义UUID算法
自定义UUID算法
43 0
|
5月前
|
算法 数据挖掘 Python
【数据挖掘】层次聚类DIANA、AGNES算法讲解及实战应用(图文解释 超详细)
【数据挖掘】层次聚类DIANA、AGNES算法讲解及实战应用(图文解释 超详细)
371 0
|
5月前
|
机器学习/深度学习 算法 数据挖掘
【Python机器学习】层次聚类AGNES、二分K-Means算法的讲解及实战演示(图文解释 附源码)
【Python机器学习】层次聚类AGNES、二分K-Means算法的讲解及实战演示(图文解释 附源码)
173 0
|
5月前
|
算法 安全 Java
性能工具之 JMeter 自定义 Java Sampler 支持国密 SM2 算法
【4月更文挑战第28天】性能工具之 JMeter 自定义 Java Sampler 支持国密 SM2 算法
144 1
性能工具之 JMeter 自定义 Java Sampler 支持国密 SM2 算法
|
4月前
|
负载均衡 算法 Nacos
SpringCloud之LoadBalancer自定义负载均衡算法,基于nacos权重
ReactorLoadBalancer接口,实现自定义负载算法需要实现该接口,并实现choose逻辑,选取对应的节点。
309 0
|
5月前
|
负载均衡 算法 Java
Ribbon自定义负载均衡算法
Ribbon自定义负载均衡算法
46 1
|
5月前
|
机器学习/深度学习 算法 数据挖掘
【Python机器学习专栏】层次聚类算法的原理与应用
【4月更文挑战第30天】层次聚类是数据挖掘中的聚类技术,无需预设簇数量,能生成数据的层次结构。分为凝聚(自下而上)和分裂(自上而下)两类,常用凝聚层次聚类有最短/最长距离、群集平均和Ward方法。优点是自动确定簇数、提供层次结构,适合小到中型数据集;缺点是计算成本高、过程不可逆且对异常值敏感。在Python中可使用`scipy.cluster.hierarchy`进行实现。尽管有局限,层次聚类仍是各领域强大的分析工具。
257 3
|
5月前
|
机器学习/深度学习 数据采集 SQL
R语言K-Means(K均值聚类)和层次聚类算法对微博用户特征数据研究
R语言K-Means(K均值聚类)和层次聚类算法对微博用户特征数据研究
|
5月前
|
算法 云计算 索引
生成UUID和自定义UUID算法
生成UUID和自定义UUID算法
337 0
下一篇
无影云桌面