-
Notifications
You must be signed in to change notification settings - Fork 0
/
bmglearn.py
552 lines (428 loc) · 16.2 KB
/
bmglearn.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
"""Clustering from scratch
- K-Means
- K-Medoids dengan PAM
- DBScan
- Agglomerative clustering
"""
# Authors: Gilang Ardyamandala Al Assyifa <[email protected]>
# Bobby Indra Nainggolan <[email protected]>
# Mico <[email protected]>
#
# License: MIT License
import numpy as np
from math import inf
import itertools
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import accuracy_score
import scipy as sp
import scipy.stats
from mpl_toolkits.mplot3d import Axes3D
from sklearn.metrics import confusion_matrix
np.set_printoptions(precision=4, suppress = True)
plt.style.use('seaborn-whitegrid')
def plot_confusion_matrix(cm, classes,title='Confusion matrix',cmap=plt.cm.Blues):
"""
Melakukan plotting confusion matrix
Parameters
----------
Returns
-------
"""
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
with plt.xkcd():
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], '.2f'),
horizontalalignment="center",
color="black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
def show_matrix(y_true, y_pred):
"""
Melakukan plotting confusion matrix
Parameters
----------
y_true : array sebenarnya
y_pred : array prediksi
Returns
-------
"""
cnf_matrix = confusion_matrix(y_true, y_pred)
np.set_printoptions(precision=2)
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=[0,1],
title='Confusion Matrix')
plt.show()
def cross_val_check(clf, data, label, k, predict_type='predict'):
"""
Melakukan cross validation
Parameters
----------
clf : Model
data : data
label : label
k : jumlah fold data
Returns
accuracy : array akurasi berukuran k
-------
"""
folds = StratifiedKFold(n_splits=k, random_state=42, shuffle=True)
folds.get_n_splits(data,label)
accuracy = []
for train_index, test_index in folds.split(data, label):
X_train, X_test = data[train_index], data[test_index]
y_train, y_test = label[train_index], label[test_index]
if (predict_type == 'predict'):
clf.fit(X_train)
y_pred = [clf.predict(instance) for instance in X_test]
elif (predict_type == 'fit_predict'):
y_pred = clf.fit_predict(X_test)
cluster_index_combination = [[0,1,2],
[0,2,1],
[2,0,1],
[2,1,0],
[1,2,0],
[1,0,2]]
temp_accuracy_score = []
if(isinstance(clf,DBScan)):
y_pred = []
for i in clf.classifications :
if (i <0 or i > 2) :
y_pred.append(2)
else :
y_pred.append(i)
for c_i in cluster_index_combination:
relabel = np.choose(y_pred,c_i).astype(np.int64)
temp_accuracy_score.append(accuracy_score(y_test, relabel))
else :
for c_i in cluster_index_combination:
relabel = np.choose(y_pred,c_i).astype(np.int64)
temp_accuracy_score.append(accuracy_score(y_test, relabel))
accuracy.append(max(temp_accuracy_score))
plt.title("ACCURACY PLOT")
plt.xlabel("K-th Fold")
plt.ylabel("Accuracy")
plt.xticks(range(k),range(1,k+1))
plt.plot(accuracy, 'o--')
plt.axhline(y=np.mean(accuracy), color='r', linestyle='-')
plt.show()
return accuracy
def mean_confidence_interval(data, confidence=0.95):
"""
Menuliskan mean_convidence interval
Parameters
----------
data : array akurasi
confidence : confidence
Returns
-------
"""
a = 1.0*np.array(data)
n = len(a)
m, se = np.mean(a), scipy.stats.sem(a)
h = se * sp.stats.t._ppf((1+confidence)/2., n-1)
print(round(m,3), "(+/-)", round(h,3))
def euclidean_distance(X, Y):
"""
Menghitung jarak euclidean dari 2 vektor
Parameters
----------
X : array berdimensi n
Y : array berdimensi n
Returns
-------
distance : Jarak euclidean
"""
X = np.array(X)
Y = np.array(Y)
distance = np.sqrt(((X-Y)**2).sum())
return distance
def manhattan_distance(X, Y):
"""
Menghitung jarak manhattan dari 2 vektor
Parameters
----------
X : array berdimensi n
Y : array berdimensi n
Returns
-------
Jarak manhattan
"""
X = np.array(X)
Y = np.array(Y)
distance = np.abs(X-Y).sum()
return distance
def isMember(a, B):
"""
"""
for b in B:
if len(a) == len(b):
countTrue = 0
for i in range(len(a)):
if (a[i] == b[i]):
countTrue +=1
if countTrue == len(a):
return True
return False
class KMeans():
"""
K-Means clustering
Parameters
----------
n_clusters : int, optional, default: 2
Banyaknya kluster yang ingin dibentuk.
tolerance : float, default: 0.0001
Toleransi konvergen.
max_iterations : int, default: 1000
Banyak iterasi maksimum.
Attributes
----------
"""
def __init__(self, n_clusters=2, tolerance=0.0001, max_iterations=1000):
self.k = n_clusters
self.tolerance = tolerance
self.max_iterations = max_iterations
self.labels_ = []
def fit(self, data):
self.centroids = {}
## inisialisasi centroid menggunakan k data pertama
for i in range(self.k):
self.centroids[i] = data[i]
for i in range(self.max_iterations):
self.classifications = {}
for i in range(self.k):
self.classifications[i] = []
for feature in data:
distances = [euclidean_distance(feature, self.centroids[centroid]) for centroid in self.centroids]
classification = distances.index(min(distances))
self.classifications[classification].append(feature)
prev_centroids = dict(self.centroids)
for classification in self.classifications :
self.centroids[classification] = np.average(self.classifications[classification], axis =0)
optimized = True
# melakukan pengecekan apakah sudah konvergen atau belum dengan menggunakan tolerance
for c in self.centroids :
original_centroid = prev_centroids[c]
current_centroid = self.centroids[c]
if np.sum((current_centroid - original_centroid) / original_centroid * 100) > self.tolerance:
optimized = False
# Kalo sudah konvergen, break
if optimized:
self.labels_ = [self.predict(instance) for instance in data]
break
def predict(self, instance) :
distances = [euclidean_distance(instance,self.centroids[centroid]) for centroid in self.centroids]
classification = distances.index(min(distances))
return classification
def fit_predict(self, data) :
self.fit(data)
classifications = [self.predict(instance) for instance in data]
return classifications
def _mDistance(start, end):
return sum(abs(e - s) for s,e in zip(start,end))
def _random(bound, size):
_rv = []
_vis = []
while True:
r = np.random.randint(bound)
if r in _vis:
pass
else:
_vis.append(r)
_rv.append(r)
if len(_rv) == size:
return _rv
class KMedoids():
"""
K-Means clustering
Parameters
----------
n_clusters : int, optional, default: 2
Banyaknya kluster yang ingin dibentuk.
tolerance : float, default: 0.0001
Toleransi konvergen.
max_iterations : int, default: 1000
Banyak iterasi maksimum.
Attributes
----------
labels_ : array
kluster data
medoids_ : array data
data yang merupakan medoid tiap kluster
"""
def __init__(self, n_clusters=2, max_iterations=10, medoid_init=[], strategy='all'):
self.n_clusters = n_clusters
self.max_iterations = max_iterations
self.labels_ = np.array([])
self.medoids_ = np.array([])
self.medoid_init = medoid_init
self.strategy = strategy
self.fit_ = False
def fit(self, data):
if self.medoid_init != []:
self.medoids_ = data[self.medoid_init]
else: #random
random_init = np.random.choice(range(len(data)), self.n_clusters, replace=False)
self.medoids_ = data[random_init]
convergence = False
iteration = 0
error_val = float(inf)
while True:
distance_to_medoid = []
for medoid in self.medoids_:
distance_to_medoid.append(np.abs(medoid - data).sum(1))
distance_to_medoid = np.array(distance_to_medoid)
self.labels_ = np.vectorize(lambda x: np.argmin(distance_to_medoid[:, x]))(range(len(data)))
new_error = 0
for cluster_index, medoid in enumerate(self.medoids_):
new_error += np.abs(medoid, data[self.labels_ == cluster_index]).sum(1).sum()
iteration += 1
convergence = (iteration >= self.max_iterations) or (new_error > error_val)
if convergence:
self.fit_ = True
break
else:
error_val = new_error
if self.strategy == 'one':
cluster_change = np.random.choice(range(self.n_clusters))
self.medoids_[cluster_change] = data[np.random.choice(np.where(self.labels_ == cluster_change)[0])]
elif self.strategy == 'all':
for cluster_index in range(self.n_clusters):
self.medoids_[cluster_index] = data[np.random.choice(np.where(self.labels_ == cluster_index)[0])]
def predict(self, instance):
if self.fit_ == True:
distance_to_medoid = []
for medoid in self.medoids_:
distance_to_medoid.append(np.abs(medoid - instance).sum(1))
distance_to_medoid = np.array(distance_to_medoid)
return np.vectorize(lambda x: np.argmin(distance_to_medoid[:, x]))(range(len(instance)))
else:
print('Belum difit')
def fit_predict(self, data):
self.fit(data)
return self.labels_
def linkage_distance(cluster_A, cluster_B, linkage, distance_function=euclidean_distance):
# A ke kanan, B ke bawah
if linkage != 'average_group':
matric_distance = []
for i in range(len(cluster_A)):
matric_distance.append([])
for j in range(len(cluster_B)):
matric_distance[i].append(distance_function(cluster_A[i], cluster_B[j]))
if linkage == 'single':
return min(min(matric_distance))
elif linkage == 'complete':
return max(max(matric_distance))
elif linkage == 'average':
x = [sum(a) for a in matric_distance]
return min(x) / len(cluster_A)
elif linkage == 'average_group':
return distance_function(np.array(cluster_A).mean(0), np.array(cluster_B).mean(0))
class Agglomerative():
"""
Agglomerative clustering
Parameters
----------
n_clusters : int, optional, default: 2
Banyaknya kluster yang ingin dibentuk.
affinity :
linkage :
Attributes
----------
"""
def __init__(self, n_clusters=2, affinity=linkage_distance, linkage='single'):
self.n_clusters = n_clusters
self.affinity = affinity
self.classifications = []
self.linkage = linkage
self.clusters = []
def fit(self, data):
## jika dilakukan fit ulang, data cluster direset
self.clusters = []
self.classifications = [0]* len(data)
## inisialisasi setiap data menjadi sebuah cluster
for i in data:
self.clusters.append([i])
while len(self.clusters) != self.n_clusters:
distances = [0] * len(self.clusters)
for idx_cluster in range(len(self.clusters)):
distances[idx_cluster] = [self.affinity(self.clusters[idx_cluster], self.clusters[i], self.linkage)
for i in range(len(self.clusters))]
min_distances = [sorted(distance)[1]for distance in distances]
x = min_distances.index(min(min_distances))
y = distances[x].index(sorted(distances[x])[1])
# cluster y dan x digabung ke x
self.clusters[x] = self.clusters[x] + self.clusters[y]
del self.clusters[y]
for i in range(len(data)):
for j in range(len(self.clusters)):
if isMember(np.array(data[i]), self.clusters[j]) :
self.classifications[i] = j
def fit_predict(self, data) :
self.fit(data)
return self.classifications
class DBScan():
"""
DBScan clustering
Parameters
----------
eps : float, optional, default: 0.5
Nilai epsilon penentuan data dalam satu kluster.
minPts : int, default: 5
Banyaknya minimal data untuk membentuk core cluster
distance_function :
Fungsi jarak yang digunakan
Attributes
----------
"""
def __init__(self, eps=0.5, minPts = 5, distance_function = euclidean_distance):
self.eps = eps
self.minPts = minPts
self.classifications = []
self.distance_function = distance_function
def fit(self, data):
# inisialisasi label dengan 0
self.classifications = [0]*len(data)
self.clusterID = 1
## inisialisasi centroid menggunakan k data pertama
for point_id in range(len(data)):
if (self.classifications[point_id] == 0):
if self.canBeExpanded(point_id, data):
self.clusterID += 1
def canBeExpanded(self, point_id, data) :
seeds = self.region_query(point_id, data)
if len(seeds) < self.minPts:
self.classifications[point_id] = -1
return False
else:
self.classifications[point_id] = self.clusterID
for seed_id in seeds :
self.classifications[seed_id] = self.clusterID
while len(seeds) > 0:
current_point = seeds[0]
results = self.region_query(current_point, data)
if len(results) >= self.minPts:
for i in range(len(results)):
result_point = results[i]
if self.classifications[result_point] <= 0 :
if self.classifications[result_point] == 0:
seeds.append(result_point)
self.classifications[result_point] = self.clusterID
seeds = seeds[1:]
return True
def region_query(self, point_id, data):
seeds = []
for i in range(len(data)) :
if self.distance_function(data[point_id], data[i]) <= self.eps:
seeds.append(i)
return seeds
def fit_predict(self, data):
self.fit(data)
return self.classifications