最大最小聚类函数代码实现
在这里插入代码片
import math
import random
def Euclidean_distance(list1,list2):
distance=0.0
for i in range(0,len(list1)):
distance=distance+(list1[i]-list2[i])**2;
return math.sqrt(distance)
def Maximum_and_minimum_clustering_algorithm(data,t):
classfiy=[data[0]]
del (data[0])
#选取第二类聚类中心
maxdistance=Euclidean_distance(classfiy[0],data[0])
index=0
for i in range(len(data)):
distance=Euclidean_distance(data[i],classfiy[0])
if maxdistance<distance:
maxdistance = distance
index=i
classfiy.append(data[index])#将最远距离的作为第二个类别
del (data[index])
spay=t*maxdistance
get_new_class(data, classfiy, spay) # 得到所有的聚类中心
#开始进行归并
result = [[] for i in range(len(classfiy))]#用于存放结果
for i in range(len(classfiy)):
result[i].append(classfiy[i])
for i in range(len(data)):
index=0
mindistance=Euclidean_distance(data[i],classfiy[0])
for j in range(len(classfiy)):
distance=Euclidean_distance(data[i],classfiy[j])
if distance<mindistance:
index=j
mindistance=distance
result[j].append(data[i])
for i in range(len(result)):
print("第"+str(i+1)+"类算法")
print(result[i])
def get_new_class(data,classfiy,spay):
if data:
mindistancelist=[]#用于存放每个点距离聚类中心的最小值
for i in range(len(data)):
distancelist=[]
for j in range(len(classfiy)):
distance=Euclidean_distance(data[i],classfiy[j])
distancelist.append(distance)
distancelist.sort()
mindistancelist.append(distancelist[0])
maxdistance=mindistancelist[0]
index=0
for i in range(len(mindistancelist)):
if maxdistance<mindistancelist[i]:
maxdistance=mindistancelist[i]
index=i
if maxdistance>spay:
classfiy.append(data[index])
del (data[index])
get_new_class(data,classfiy,spay)
if __name__ == '__main__':
data = [[random.randint(1, 50) for j in range(0, 2)] for i in range(0, 100)]
Maximum_and_minimum_clustering_algorithm(data,0.2)