-
Notifications
You must be signed in to change notification settings - Fork 3
/
g_centroid_neural_networks.py
433 lines (312 loc) · 13.8 KB
/
g_centroid_neural_networks.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
#================================================================
#
# Copyright (C) 2021 Tran Le Anh (Lean Tran)
#
# Editor : Sublime Text
# Application : G - Centroid Neural Networks
# Author : tranleanh
# Created date: 2021-01-16 02:20
# Description : Public
# Version : 1.0
#
#================================================================
import numpy as np
from matplotlib import pyplot as plt
def remove_element(L,arr):
ind = 0
size = len(L)
while ind != size and not np.array_equal(L[ind],arr):
ind += 1
if ind != size:
L.pop(ind)
else:
raise ValueError('array not found in list.')
# Centroid Neural Networks
def centroid_neural_network(X, n_clusters=10, max_iteration = 100, epsilon=0.05):
'''
Centroid Neural Networks:
X: input data
n_clusters: num of clusters
max_iteration
Variables:
centroids: final centroids
w: final weights
cluster_indices: len = len(data), labels
cluster_elements: len = len(centroids), to store elements in each cluster
'''
centroid_X = np.average(X[:, -len(X[0]):], axis=0)
epsilon = 0.05
w1 = centroid_X + epsilon
w2 = centroid_X - epsilon
w = []
w.append(w1)
w.append(w2)
########## EPOCH 0 ##########
initial_clusters = 2
# Create an array to store elements in each cluster
cluster_elements = []
for cluster in range(initial_clusters):
cluster_i = []
cluster_elements.append(cluster_i)
cluster_lengths = np.zeros(initial_clusters, dtype=int)
# Create an array to label for each element
cluster_indices = []
for i in range(len(X)):
x = X[i]
distances = []
for w_i in w:
dist = np.linalg.norm(x-w_i)
distances.append(dist)
# find winner neuron
index = np.argmin(distances)
# add cluster index of data x to a list
cluster_indices.append(index)
# update winner neuron
w[index] = w[index] + 1/(1+cluster_lengths[index])*(x - w[index])
# append data to cluster
cluster_elements[index].append(x)
cluster_lengths[index] += 1
centroids = []
for elements in cluster_elements:
elements = np.array(elements)
centroid_i = np.average(elements[:, -len(elements[0]):], axis=0)
centroids.append(centroid_i)
########## EPOCH 1+ - INCREASE NUM OF CLUSERS ##########
num_of_all_clusters = n_clusters
epochs = max_iteration
for epoch in range(epochs):
loser = 0
for i in range(len(X)):
x = X[i]
distances = []
for w_i in w:
dist = np.linalg.norm(x-w_i)
distances.append(dist)
# find winner neuron of x
current_cluster_index = np.argmin(distances)
# what was the winner for x in previous epoch
x_th = i
previous_cluster_index = cluster_indices[x_th]
# check if current neuron is a loser
if previous_cluster_index != current_cluster_index:
# update winner neuron
w[current_cluster_index] = w[current_cluster_index] + (x - w[current_cluster_index])/(cluster_lengths[current_cluster_index]+1)
# update loser neuron
w[previous_cluster_index] = w[previous_cluster_index] - (x - w[previous_cluster_index])/(cluster_lengths[previous_cluster_index]-1)
# add and remove data to cluster
cluster_elements[current_cluster_index] = list(cluster_elements[current_cluster_index])
cluster_elements[current_cluster_index].append(x)
remove_element(cluster_elements[previous_cluster_index], x)
# update cluster index
cluster_indices[x_th] = current_cluster_index
cluster_lengths[current_cluster_index] += 1
cluster_lengths[previous_cluster_index] -= 1
loser += 1
centroids = []
for elements in cluster_elements:
elements = np.array(elements)
centroid_i = np.average(elements[:, -len(elements[0]):], axis=0)
centroids.append(centroid_i)
print(epoch+1)
if loser == 0:
if len(w) == num_of_all_clusters:
print("Reach the Desired Number of Clusters. Stop at Epoch ", epoch+1)
break
else:
all_error = []
for i in range(len(centroids)):
# calculate error
error = 0
for x in cluster_elements[i]:
dist_e = np.linalg.norm(x-centroids[i])
error += dist_e
all_error.append(error)
splitted_index = np.argmax(all_error)
new_w = w[splitted_index] + epsilon
w.append(new_w)
new_cluster_thing = []
new_cluster_thing = np.array(new_cluster_thing)
cluster_elements.append(new_cluster_thing)
cluster_lengths = list(cluster_lengths)
cluster_lengths.append(0)
cluster_lengths = np.array(cluster_lengths)
return centroids, w, cluster_indices, cluster_elements
# Centroid Neural Networks with Detected Weights
def centroid_neural_network_detected_weights(input_data, detected_weights, n_clusters, epochs = 10):
X = input_data
w = detected_weights
initial_clusters = len(w)
cluster_elements = []
for cluster in range(initial_clusters):
cluster_i = []
cluster_elements.append(cluster_i)
cluster_lengths = np.zeros(initial_clusters, dtype=int)
cluster_indices = []
for i in range(len(X)):
x = X[i]
distances = []
for w_i in w:
dist = np.linalg.norm(x-w_i)
distances.append(dist)
# find winner neuron
index = np.argmin(distances)
# add cluster index of data x to a list
cluster_indices.append(index)
# update winner neuron
w[index] = w[index] + 1/(1+cluster_lengths[index])*(x - w[index])
# append data to cluster
cluster_elements[index].append(x)
cluster_lengths[index] += 1
centroids = []
for elements in cluster_elements:
elements = np.array(elements)
centroid_i = np.average(elements[:, -len(elements[0]):], axis=0)
centroids.append(centroid_i)
for epoch in range(epochs):
loser = 0
for i in range(len(X)):
x = X[i]
distances = []
for w_i in w:
dist = np.linalg.norm(x-w_i)
distances.append(dist)
# find winner neuron of x
current_cluster_index = np.argmin(distances)
# what was the winner for x in previous epoch
x_th = i
previous_cluster_index = cluster_indices[x_th]
# check if current neuron is a loser
if previous_cluster_index != current_cluster_index:
# update winner neuron
w[current_cluster_index] = w[current_cluster_index] + (x - w[current_cluster_index])/(cluster_lengths[current_cluster_index]+1)
# update loser neuron
w[previous_cluster_index] = w[previous_cluster_index] - (x - w[previous_cluster_index])/(cluster_lengths[previous_cluster_index]-1)
# add and remove data to cluster
cluster_elements[current_cluster_index] = list(cluster_elements[current_cluster_index])
cluster_elements[current_cluster_index].append(x)
remove_element(cluster_elements[previous_cluster_index], x)
# update cluster index
cluster_indices[x_th] = current_cluster_index
cluster_lengths[current_cluster_index] += 1
cluster_lengths[previous_cluster_index] -= 1
loser += 1
centroids = []
for elements in cluster_elements:
elements = np.array(elements)
centroid_i = np.average(elements[:, -len(elements[0]):], axis=0)
centroids.append(centroid_i)
print(epoch+1, len(centroids))
if loser == 0:
if len(w) == n_clusters:
print("Reach the Desired Number of Clusters. Stop at Epoch ", epoch+1)
break
else:
all_error = []
for i in range(len(centroids)):
# calculate error
error = 0
for x in cluster_elements[i]:
dist_e = np.linalg.norm(x-centroids[i])
error += dist_e
all_error.append(error)
splitted_index = np.argmax(all_error)
new_w = w[splitted_index] + epsilon
w.append(new_w)
new_cluster_thing = []
new_cluster_thing = np.array(new_cluster_thing)
cluster_elements.append(new_cluster_thing)
cluster_lengths = list(cluster_lengths)
cluster_lengths.append(0)
cluster_lengths = np.array(cluster_lengths)
return centroids, w, cluster_indices, cluster_elements
# G-CNN
def g_centroid_neural_network(input_data, num_clusters, num_subdata = 10, max_iteration = 50, epsilon = 0.05):
X = input_data
new_data = []
for i in range(num_subdata):
subdata = []
for j in range(len(X)//num_subdata):
x_i = X[(len(X)//num_subdata)*i + j]
subdata.append(x_i)
new_data.append(subdata)
new_data = np.array(new_data)
# print(np.array(new_data).shape)
centroids = []
w = []
cluster_indices = []
cluster_elements = []
for i in range(len(new_data)):
subdata_i = new_data[i]
centroids_, w_, cluster_indices_, cluster_elements_ = centroid_neural_network(subdata_i, num_clusters, max_iteration, epsilon)
centroids.append(centroids_)
w.append(w_)
cluster_indices.append(cluster_indices_)
cluster_elements.append(cluster_elements_)
# Create New Data with Detected Centroids
gen2_data = []
for centroids_i in centroids:
for centroid_ii in centroids_i:
gen2_data.append(centroid_ii)
gen2_data = np.array(gen2_data)
# Run G-CNN one more time
centroids_2, w_2, cluster_indices_2, cluster_elements_2 = centroid_neural_network(gen2_data, num_clusters, max_iteration, epsilon)
# Run G-CNN last time
detected_weights = centroids_2
centroids, weights, cluster_indices, cluster_elements = centroid_neural_network_detected_weights(X, detected_weights, num_clusters, max_iteration)
print("Reach the Desired Number of Clusters. Stop!")
return centroids, weights, cluster_indices, cluster_elements
# G-CNN v2
def g_centroid_neural_network_2(input_data, num_clusters, num_subdata = 10, max_iteration = 50, epsilon = 0.05):
X = input_data
new_data = []
for i in range(num_subdata):
subdata = []
for j in range(len(X)//num_subdata):
x_i = X[(len(X)//num_subdata)*i + j]
subdata.append(x_i)
new_data.append(subdata)
new_data = np.array(new_data)
# print(np.array(new_data).shape)
centroids = []
w = []
cluster_indices = []
cluster_elements = []
for i in range(len(new_data)):
subdata_i = new_data[i]
if i == 0:
centroids_, w_, cluster_indices_, cluster_elements_ = centroid_neural_network(subdata_i, num_clusters, max_iteration, epsilon)
else:
detected_weights = w[0]
centroids_, w_, cluster_indices_, cluster_elements_ = centroid_neural_network_detected_weights(subdata_i, detected_weights, num_clusters,max_iteration)
centroids.append(centroids_)
w.append(w_)
cluster_indices.append(cluster_indices_)
cluster_elements.append(cluster_elements_)
# Create New Data with Detected Centroids
gen2_data = []
for centroids_i in centroids:
for centroid_ii in centroids_i:
gen2_data.append(centroid_ii)
gen2_data = np.array(gen2_data)
centroids_2, w_2, cluster_indices_2, cluster_elements_2 = centroid_neural_network(gen2_data, num_clusters, max_iteration, epsilon)
# Run G-CNN one more time
detected_weights = centroids_2
centroids, weights, cluster_indices, cluster_elements = centroid_neural_network_detected_weights(X, detected_weights, num_clusters, max_iteration)
print("Reach the Desired Number of Clusters. Stop!")
return centroids, weights, cluster_indices, cluster_elements
def plot_cnn_result(input_data, centroids, cluster_indices, figure_size=(8,8)):
X = input_data
num_clusters = len(centroids)
plt.figure(figsize=figure_size)
cnn_cluster_elements = []
for i in range(num_clusters):
display = []
for x_th in range(len(X)):
if cluster_indices[x_th] == i:
display.append(X[x_th])
cnn_cluster_elements.append(display)
display = np.array(display)
plt.scatter(display[:,0], display[:,1])
plt.scatter(centroids[i][0], centroids[i][1], s=200, c='red')
plt.text(centroids[i][0], centroids[i][1], f"Cluster {i}", fontsize=14)
plt.show()