-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathCluster.py
406 lines (367 loc) · 17.4 KB
/
Cluster.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
"""
@ Filename: Cluster.py
@ Author: Ryuk
@ Create Date: 2019-05-15
@ Update Date: 2019-05-28
@ Description: Implement Cluster
"""
import sys
import numpy as np
import preProcess
import pickle
import random
import matplotlib.pyplot as plt
import operator as op
class KMeans:
def __init__(self, norm_type="Normalization", k=4, distance_type="Euclidean", cluster_type="KMeans++"):
self.norm_type = norm_type
self.k = k
self.distance_type = distance_type
self.cluster_type = cluster_type
self.centers = None # cluster centers
self.distances = None # distance between sample and cluster
'''
Function: calcuateDistance
Description: calcuate the distance between input vector and train data
Input: x1 dataType: ndarray description: input vector
x2 dataType: ndarray description: input vector
Output: d dataType: float description: distance between input vectors
'''
def calculateDistance(self, x1, x2):
d = 0
if self.distance_type == "Euclidean":
d = np.sqrt(np.power(np.sum(x1 - x2, axis=1), 2))
elif self.distance_type == "Cosine":
d = np.dot(x1, x2)/(np.linalg.norm(x1)*np.linalg.norm(x2))
elif self.distance_type == "Manhattan":
d = np.sum(x1 - x2)
else:
print("Error Type!")
sys.exit()
return d
'''
Function: createCenter
Description: create cluster center
Input: train_data dataType: ndarray description: input vector
Output: centers dataType: ndarray description: cluster centers
'''
def createCenter(self, train_data):
feature_dim = np.shape(train_data)[1]
centers = np.zeros([self.k, feature_dim])
for i in range(feature_dim):
min_value = np.min(train_data[:, i])
max_value = np.max(train_data[:, i])
temp = min_value + (max_value - min_value) * np.random.rand(self.k)
centers[:, i] = temp # generate a cluster center
return centers
'''
Function: adjustCluster
Description: adjust cluster when the cluster determined
Input: centers dataType: ndarray description: cluster centers
distances dataType: ndarray description: distance between sample and its corresponding cluster(cluster, distance)
train_data dataType: ndarray description: train data
k dataType: int description: the number of cluster
Output: centers dataType: ndarray description: cluster centers
distances dataType: ndarray description: distance between sample and its corresponding cluster(cluster, distance)
'''
def adjustCluster(self, centers, distances, train_data, k):
sample_num = len(train_data)
flag = True # If True, update cluster_center
while flag:
flag = False
d = np.zeros([sample_num, len(centers)])
for i in range(len(centers)):
# calculate the distance between each sample and each cluster center
d[:, i] = self.calculateDistance(train_data, centers[i])
# find the minimum distance between each sample and each cluster center
old_label = distances[:, 0].copy()
distances[:, 0] = np.argmin(d, axis=1)
distances[:, 1] = np.min(d, axis=1)
if np.sum(old_label - distances[:, 0]) != 0:
flag = True
# update cluster_center by calculating the mean of each cluster
for j in range(k):
current_cluster = train_data[distances[:, 0] == j] # find the samples belong to the j-th cluster center
if len(current_cluster) != 0:
centers[j, :] = np.mean(current_cluster, axis=0)
return centers, distances
'''
Function: kmeans
Description: normal kmeans algorithm
Input: train_data dataType: ndarray description: features
Output: centers dataType: ndarray description: cluster centers
distances dataType: ndarray description: distance between sample and its corresponding cluster(cluster, distance)
'''
def kmeans(self, train_data, k):
sample_num = len(train_data)
distances = np.zeros([sample_num, 2]) # (index, distance)
centers = self.createCenter(train_data)
centers, distances = self.adjustCluster(centers, distances, train_data, self.k)
return centers, distances
'''
Function: biKmeans
Description: binary kmeans algorithm
Input: train_data dataType: ndarray description: features
Output: centers dataType: ndarray description: cluster centers
distances dataType: ndarray description: distance between sample and its corresponding cluster(cluster, distance)
'''
def biKmeans(self, train_data):
sample_num = len(train_data)
distances = np.zeros([sample_num, 2]) # (index, distance)
initial_center = np.mean(train_data, axis=0) # initial cluster #shape (1, feature_dim)
centers = [initial_center] # cluster list
# clustering with the initial cluster center
distances[:, 1] = np.power(self.calculateDistance(train_data, initial_center), 2)
# generate cluster centers
while len(centers) < self.k:
# print(len(centers))
min_SSE = np.inf
best_index = None # index of cluster for best split
best_centers = None # best the cluster center
best_distances = None # the distance between samples and cluster center
# find the best split
for j in range(len(centers)):
centerj_data = train_data[distances[:, 0] == j] # find the samples belong to the j-th center
split_centers, split_distances = self.kmeans(centerj_data, 2) # clustering the samples belong to j-th center into two cluster
split_SSE = np.sum(split_distances[:, 1]) ** 2 # calculate the distance for after clustering
other_distances = distances[distances[:, 0] != j] # the samples don't belong to j-th center
other_SSE = np.sum(other_distances[:, 1]) ** 2 # calculate the distance don't belong to j-th center
# save the best split result
if (split_SSE + other_SSE) < min_SSE:
best_index = j # the best split index
best_centers = split_centers # best cluster centers
best_distances = split_distances # the corresponding distance
min_SSE = split_SSE + other_SSE
# save the spilt data
best_distances[best_distances[:, 0] == 1, 0] = len(centers) # samples of cluster 1 denote as a new cluster
best_distances[best_distances[:, 0] == 0, 0] = best_index # samples of cluster 0 denote as the split-index cluster
centers[best_index] = best_centers[0, :] # update cluster
centers.append(best_centers[1, :]) # add a new cluster
distances[distances[:, 0] == best_index, :] = best_distances # save the distances
centers = np.array(centers) # transform form list to array
return centers, distances
'''
Function: kmeansplusplus
Description: kmeans++ algorithm
Input: train_data dataType: ndarray description: features
Output: centers dataType: ndarray description: cluster centers
distances dataType: ndarray description: distance between sample and its corresponding cluster(cluster, distance)
'''
def kmeansplusplus(self,train_data):
sample_num = len(train_data)
distances = np.zeros([sample_num, 2]) # (index, distance)
# randomly select a sample as the initial cluster
initial_center = train_data[np.random.randint(0, sample_num-1)]
centers = [initial_center]
while len(centers) < self.k:
d = np.zeros([sample_num, len(centers)])
for i in range(len(centers)):
# calculate the distance between each sample and each cluster center
d[:, i] = self.calculateDistance(train_data, centers[i])
# find the minimum distance between each sample and each cluster center
distances[:, 0] = np.argmin(d, axis=1)
distances[:, 1] = np.min(d, axis=1)
# Roulette Wheel Selection
prob = np.power(distances[:, 1], 2)/np.sum(np.power(distances[:, 1], 2))
index = self.rouletteWheelSelection(prob, sample_num)
new_center = train_data[index, :]
centers.append(new_center)
# adjust cluster
centers = np.array(centers) # transform form list to array
centers, distances = self.adjustCluster(centers, distances, train_data, self.k)
return centers, distances
'''
Function: rouletteWheelSelection
Description: Roulette Wheel Selection
Input: prob dataType: ndarray description: features
Output: i dataType: ndarray description: the selected cluster
'''
def rouletteWheelSelection(self, prob, sample_num):
acc_prob = np.zeros(sample_num)
acc_prob[0] = prob[0]
p = random.uniform(0, 1)
for i in range(1, len(prob)):
acc_prob[i] = acc_prob[i-1] + prob[i]
if acc_prob[i] > p:
return i
'''
Function: train
Description: train the model
Input: train_data dataType: ndarray description: features
Output: centers dataType: ndarray description: cluster centers
distances dataType: ndarray description: distance between sample and its corresponding cluster(cluster, distance)
'''
def train(self, train_data, display="True"):
if self.norm_type == "Standardization":
train_data = preProcess.Standardization(train_data)
else:
train_data = preProcess.Normalization(train_data)
if self.cluster_type == "KMeans":
self.centers, self.distances = self.kmeans(train_data, self.k)
elif self.cluster_type == "biKMeans":
self.centers, self.distances = self.biKmeans(train_data)
elif self.cluster_type == "KMeans++":
self.centers, self.distances = self.kmeansplusplus(train_data)
else:
print("Wrong cluster type!")
sys.exit()
if display:
self.plotResult(train_data)
return self.distances[:, 0]
'''
Function: plotResult
Description: show the clustering result
'''
def plotResult(self, train_data):
plt.scatter(train_data[:, 0], train_data[:, 1], c=self.distances[:, 0])
plt.scatter(self.centers[:, 0], self.centers[:, 1], c=['b', 'b', 'b', 'b'], marker="+")
if self.cluster_type == "KMeans":
plt.title('KMeans')
elif self.cluster_type == "biKMeans":
plt.title('biKMeans')
elif self.cluster_type == "KMeans++":
plt.title('KMeans++')
plt.show()
'''
Function: save
Description: save the model as pkl
Input: filename dataType: str description: the path to save model
'''
def save(self, filename):
f = open(filename, 'w')
model = {'centers': self.centers, 'distances': self.distances}
pickle.dump(model, f)
f.close()
'''
Function: load
Description: load the model
Input: filename dataType: str description: the path to save model
Output: self dataType: obj description: the trained model
'''
def load(self, filename):
f = open(filename)
model = pickle.load(f)
self.centers = model['centers']
self.distances = model['distances']
return self
class DBSCAN:
def __init__(self, norm_type="Normalization", distance_type="Euclidean", eps=0.1, m=10):
self.norm_type = norm_type
self.distance_type = distance_type
self.eps = eps # neighbor
self.m = m # the min number of sample in a neighbor
self.label = None
self.neighbor = None
'''
Function: calcuateDistance
Description: calcuate the distance between input vector and train data
Input: x1 dataType: ndarray description: input vector
x2 dataType: ndarray description: input vector
Output: d dataType: float description: distance between input vectors
'''
def calculateDistance(self, x1, x2):
if self.distance_type == "Euclidean":
d = np.sqrt(np.sum(np.power(x1 - x2, 2), axis=1))
#d = np.sqrt(np.sum(np.power(x1 - x2, 2)))
elif self.distance_type == "Cosine":
d = np.dot(x1, x2)/(np.linalg.norm(x1)*np.linalg.norm(x2))
elif self.distance_type == "Manhattan":
d = np.sum(x1 - x2)
else:
print("Error Type!")
sys.exit()
return d
'''
Function: train
Description: train the model
Input: train_data dataType: ndarray description: features
Output: centers dataType: ndarray description: cluster centers
distances dataType: ndarray description: distance between sample and its corresponding cluster(cluster, distance)
'''
def train(self, train_data, display="True"):
# if self.norm_type == "Standardization":
# train_data = preProcess.Standardization(train_data)
# else:
# train_data = preProcess.Normalization(train_data)
# get the initial cluster center
centers = self.getCenters(train_data)
label = {}
sample_num = len(train_data)
initial_centers = centers.copy()
k = 0
unvisited = list(range(sample_num)) # samples which are not visited
while len(centers) > 0:
visited = []
visited.extend(unvisited)
cores = list(centers.keys())
# choose a random cluster center
randNum = np.random.randint(0, len(cores))
core = cores[randNum]
core_neighbor = [] # samples in core's neighbor
core_neighbor.append(core)
unvisited.remove(core)
# merege the samples density-connectivity
while len(core_neighbor) > 0:
Q = core_neighbor[0]
del core_neighbor[0]
if Q in initial_centers.keys():
diff = [sample for sample in initial_centers[Q] if sample in unvisited]
core_neighbor.extend(diff)
unvisited = [sample for sample in unvisited if sample not in diff]
k += 1
label[k] = [val for val in visited if val not in unvisited]
for index in label[k]:
if index in centers.keys():
del centers[index]
labels = np.zeros([sample_num])
for i in range(1, len(label)):
index = label[i]
labels[index] = i
self.label = labels
if display:
self.plotResult(train_data)
return label
'''
Function: getCenters
Description: get initial cluster centers
Input: train_data dataType: ndarray description: training set
Output: neighbor dataType: dict description: cluster and its neighbor (center, neighbor)
'''
def getCenters(self, train_data):
neighbor = {}
for i in range(len(train_data)):
distance = self.calculateDistance(train_data[i], train_data)
index = np.where(distance <= self.eps)[0]
if len(index) > self.m:
neighbor[i] = index
return neighbor
'''
Function: plotResult
Description: show the clustering result
'''
def plotResult(self, train_data):
plt.scatter(train_data[:, 0], train_data[:, 1], c=self.label)
plt.title('DBSCAN')
plt.show()
'''
Function: save
Description: save the model as pkl
Input: filename dataType: str description: the path to save model
'''
def save(self, filename):
f = open(filename, 'w')
model = {'label': self.label, 'neighbor': self.neighbor}
pickle.dump(model, f)
f.close()
'''
Function: load
Description: load the model
Input: filename dataType: str description: the path to save model
Output: self dataType: obj description: the trained model
'''
def load(self, filename):
f = open(filename)
model = pickle.load(f)
self.label = model['label']
self.neighbor = model['neighbor']
return self