层次聚类聚合/分裂算法
import numpy as np
import copy
import matplotlib.pyplot as plt
class Hierarchical_cluster:
def __init__(self,k=None,p=2,dis_way='min',c_way='agg'):
self.k = k
self.p = p
self.dis_way = dis_way
self.c_way = c_way
def cauclate_dis(self, x1, x2):
return np.sum(abs(x1 - x2) ** self.p) ** (1 / self.p)
def create_D_matrix(self):
self.D = np.zeros((self.n,self.n))
for i in range(self.n):
for j in range(self.n):
if i==j:
self.D[i][j] = 0
if i>j:
self.D[i][j] = self.cauclate_dis(self.x[i],self.x[j])
self.D[j][i] = self.cauclate_dis(self.x[i],self.x[j])
def cauclate_cluster_dis(self,c1,c2):
if self.dis_way == 'min':
min_ = 999999999
for i in c1:
for j in c2:
min_ = min(min_,self.D[i][j])
return min_
if self.dis_way == 'mean':
mean1 = np.mean([self.x[i] for i in c1],axis=0)
mean2 = np.mean([self.x[i] for i in c2],axis=0)
return self.cauclate_dis(mean1,mean2)
def split_C(self,C):
C1 = []
C2 = []
max_ = 0
for i in C:
for j in C:
if j >= i:
if self.D[i][j] >= max_:
max_ = self.D[i][j]
max_i = i
max_j = j
C1.append(max_i)
C2.append(max_j)
for c in C:
if c == max_i or c == max_j:
continue
elif self.D[max_i][c] >= self.D[max_j][c]:
C2.append(c)
else:
C1.append(c)
return C1, C2
def fit(self,x):
self