forked from DoubleXixi/baodu-qinghua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmeans_test.py
90 lines (78 loc) · 2.84 KB
/
kmeans_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import numpy as np
import random
import sys
'''
Kmeans算法实现
原文链接:https://blog.csdn.net/qingchedeyongqi/article/details/116806277
'''
class KMeansClusterer: # k均值聚类
def __init__(self, ndarray, cluster_num):
self.ndarray = ndarray
self.cluster_num = cluster_num
self.points = self.__pick_start_point(ndarray, cluster_num)
def cluster(self):
result = []
for i in range(self.cluster_num):
result.append([])
for item in self.ndarray:
distance_min = sys.maxsize
index = -1
for i in range(len(self.points)):
distance = self.__distance(item, self.points[i])
if distance < distance_min:
distance_min = distance
index = i
result[index] = result[index] + [item.tolist()]
new_center = []
for item in result:
new_center.append(self.__center(item).tolist())
# 中心点未改变,说明达到稳态,结束递归
if (self.points == new_center).all():
sum = self.__Sort(result)
return result, self.points, sum
self.points = np.array(new_center)
return self.cluster()
def __sumdis(self, result):
# 计算总距离和
sum = 0
for i in range(len(self.points)):
for j in range(len(result[i])):
sum += self.__distance(result[i][j], self.points[i])
return sum
def __Sort(self, result):
# 计算各类元素距离排序
sum = []
for i in range(len(self.points)):
sum1 = []
for j in range(len(result[i])):
sum1.append(self.__distance(result[i][j], self.points[i]))
sum1.sort()
sum.append(sum1)
return sum
def __center(self, list):
# 计算每一列的平均值
return np.array(list).mean(axis=0)
def __distance(self, p1, p2):
# 计算两点间距
tmp = 0
for i in range(len(p1)):
tmp += pow(p1[i] - p2[i], 2)
return pow(tmp, 0.5)
def __pick_start_point(self, ndarray, cluster_num):
if cluster_num < 0 or cluster_num > ndarray.shape[0]:
raise Exception("簇数设置有误")
# 取点的下标
indexes = random.sample(np.arange(0, ndarray.shape[0], step=1).tolist(), cluster_num)
points = []
for index in indexes:
points.append(ndarray[index].tolist())
return np.array(points)
x = np.random.rand(100, 8)
kmeans = KMeansClusterer(x, 10)
result, centers, distances = kmeans.cluster()
#print("结果",result) # 结果
#print("中心",centers) # 中心
y=0
for x in distances:
y+=1
print("距离列表%d:"%y,x) # 距离