-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClustering.py
More file actions
498 lines (354 loc) · 17.1 KB
/
Copy pathClustering.py
File metadata and controls
498 lines (354 loc) · 17.1 KB
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
import numpy as np
import pandas as pd
from dask.distributed import Client
import joblib
import time
from sklearn.preprocessing import StandardScaler, PowerTransformer
from sklearn import cluster
from sklearn.mixture import GaussianMixture
from kmodes.kprototypes import KPrototypes # Assuming you are using singleodes for KPrototypes
from stepmix.stepmix import StepMix # Gaussian Mixture Models Clustering
from snn import SNN
from stepmix.utils import get_mixed_descriptor
from sklearn import metrics
class Clustering:
###### CLUSTERING
# Construct an object that will perform various clustering techniques on the data
def __init__(self, data):
# data is the input data
self.data = data # Defines the input data field
self.num = data.shape[0]
## Cluster Evaluation
def cluster_evaluation(name, estimator, labels, data, metric):
if hasattr(estimator, 'labels_'):
y_pred = estimator.labels_.astype(int)
elif hasattr(estimator, 'predict'):
y_pred = estimator.predict(data)
else:
y_pred = estimator
print('% s %8.3f %8.3f %8.3f \t %8.3f %8.3f %8.3f'
% (name,
metrics.silhouette_score(data, y_pred, metric=metric, sample_size = 300),
metrics.calinski_harabasz_score(data, y_pred),
metrics.davies_bouldin_score(data, y_pred),
metrics.adjusted_rand_score(labels, y_pred),
metrics.adjusted_mutual_info_score(labels, y_pred),
metrics.v_measure_score(labels, y_pred)))
### Prototype-Based Clustering
#### K-means Clustering
def makeKmeans(self, X, num_clusters):
try:
# Perform k-means Clustering
print('\n Start k-means Clustering')
time_start = time.time()
k_means = cluster.KMeans(n_clusters = num_clusters)
k_means.fit(X)
labels = k_means.labels_
print('k-means done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
km_result = pd.DataFrame(labels, index = X.index, columns=['Cluster ID Kmeans'])
#Prints the count of each cluster group
print(km_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return km_result
#### K-prototypes Clustering for mixed data
def makeKprototype(self, X, num_clusters, cat_cols):
try:
client = Client(processes=False) # create local cluster
# Perform k-prototypes Clustering
print('\n Start k-prototypes Clustering')
time_start = time.time()
data_1 = X
kprot_data = data_1.copy()
#Pre-processing
for c in data_1.select_dtypes(exclude='object').columns:
pt = PowerTransformer()
kprot_data[c] = pt.fit_transform(np.array(kprot_data[c]).reshape(-1, 1))
categorical_columns = cat_cols #make sure to specify correct indices like [1, 2, 3]
#Actual clustering
kprot = KPrototypes(n_clusters= num_clusters, init='Cao', n_jobs = -1)
with joblib.parallel_backend('dask'):
kprot_labels = kprot.fit_predict(kprot_data, categorical=categorical_columns)
print('k-Prototype done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
kprot_result = pd.DataFrame(kprot_labels, index = X.index, columns=['Cluster ID kprot'])
#Prints the count of each cluster group
print(kprot_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return kprot_result
#### Gaussian Mixture Models Clustering for Mixed Data
def makeGMM(self, mixed_data, mixed_descriptor):
try:
# Perform Gaussian Mixture Model Clustering with mixed data types
print('\n Start Gaussian Mixture Models Clustering')
time_start = time.time()
# Mixed-type mixture model
gmm = StepMix(n_components=3, measurement=mixed_descriptor, verbose=0, random_state=123)
# Fit model
gmm.fit(mixed_data)
#predictions from gmm
labels = gmm.predict(mixed_data)
print('GMM done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
gmm_result = pd.DataFrame(labels, index = self.data.index, columns=['Cluster ID GMM'])
#Prints the count of each cluster group
print(gmm_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return gmm_result
#### Gaussian Mixture Models Clustering for Numeric Data
def makegmm(self, X, n_components):
try:
# Perform Gaussian Mixture Model Clustering with mixed data types
print('\n Start Gaussian Mixture Models Clustering')
time_start = time.time()
# Mixture model
gmm = GaussianMixture(n_components = n_components)
# Fit model
gmm.fit(X)
#predictions from gmm
labels = gmm.predict(X)
print('GMM done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
gmm_result = pd.DataFrame(labels, index = self.data.index, columns=['Cluster ID GMM'])
#Prints the count of each cluster group
print(gmm_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return gmm_result
#### BIRCH Clustering
def makeBirch(self, X, n_clusters):
try:
# Perform Gaussian Mixture Model Clustering with mixed data types
print('\n Start BIRCH Clustering')
time_start = time.time()
# Mixture model
bir = cluster.Birch(threshold=0.5, n_clusters = n_clusters)
# Fit model
bir.fit(X)
#predictions from gmm
labels = bir.predict(X)
print('BIRCH done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
bir_result = pd.DataFrame(labels, index = self.data.index, columns=['Cluster ID Birch'])
#Prints the count of each cluster group
print(bir_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return bir_result
### Graph-Based Clustering
#### Agglomerative / Hierarchical Clustering
##### Single Link (MIN)
def makeSingle(self, X, num_clusters, metric):
try:
client = Client(processes=False) # create local cluster
# Perform k-means Clustering
print('\n Start Single Link (MIN) Clustering')
time_start = time.time()
single_clst = cluster.AgglomerativeClustering(n_clusters = num_clusters, metric=metric, linkage='single')
with joblib.parallel_backend('dask'):
single_clst.fit(X)
single_labels = single_clst.labels_
print('Single Hierarchical done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
single_result = pd.DataFrame(single_labels, index = self.data.index, columns=['Cluster ID Single'])
#Prints the count of each cluster group
print(single_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return single_result
##### Average Link
def makeAverage(self, X, num_clusters,metric):
try:
client = Client(processes=False) # create local cluster
# Perform k-means Clustering
print('\n Start Average Link (MIN) Clustering')
time_start = time.time()
avg_clst = cluster.AgglomerativeClustering(n_clusters = num_clusters, metric=metric, linkage='average')
with joblib.parallel_backend('dask'):
avg_clst.fit(X)
avg_labels = avg_clst.labels_
print('Average Hierarchical done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
avg_result = pd.DataFrame(avg_labels, index = self.data.index, columns=['Cluster ID avg'])
#Prints the count of each cluster group
print( avg_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return avg_result
##### Complete Link
def makeComplete(self, X, num_clusters,metric):
try:
client = Client(processes=False) # create local cluster
# Perform k-means Clustering
print('\n Start Complete Link (MIN) Clustering')
time_start = time.time()
cmp_clst = cluster.AgglomerativeClustering(n_clusters = num_clusters, metric=metric, linkage='complete')
with joblib.parallel_backend('dask'):
cmp_clst.fit(X)
cmp_labels = cmp_clst.labels_
print('Complete Hierarchical done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
cmp_result = pd.DataFrame(cmp_labels, index = self.data.index, columns=['Cluster ID compl'])
#Prints the count of each cluster group
print(cmp_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return cmp_result
#### Spectral Clustering [Elliptical and 2D Data]
def makeSpeclut(self, X, num_clusters, num_neighbors,metric):
try:
client = Client(processes=False) # create local cluster
# Perform Spectral Clustering
print('\n Start Spectral Clustering')
time_start = time.time()
# training spectral clustering model
spectral = cluster.SpectralClustering(n_clusters = num_clusters, random_state=1, affinity=metric, n_neighbors = num_neighbors, n_jobs= -1)
with joblib.parallel_backend('dask'):
spectral.fit(X)
#predictions from spectral
labels = spectral.labels_
print('Spectral Clustering done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
spectral_result = pd.DataFrame(labels, index = self.data.index, columns=['Cluster ID SPC'])
#Prints the count of each cluster group
print(spectral_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return spectral_result
### Density-Based Clustering
#### DBSCAN
def makedbscan(self, X, epsilon, minimum_samples,metric):
try:
client = Client(processes=False) # create local cluster
# Perform DBSCAN Clustering
print('\n Start DBSCAN Clustering')
time_start = time.time()
# training optics clustering model
db = cluster.DBSCAN(eps=epsilon, min_samples=minimum_samples, metric=metric, n_jobs = -1)
with joblib.parallel_backend('dask'):
db.fit(X)
#predictions from optics
labels = db.labels_
print('DBSCAN Clustering done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
db_result = pd.DataFrame(labels, index = self.data.index, columns=['Cluster ID DBSCAN'])
#Prints the count of each cluster group
print(db_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return db_result
#### HDBSCAN
def makehdbscan(self, X, clust_size = 5, minimum_samples = None, metric ='euclidean'):
try:
client = Client(processes=False) # create local cluster
# Perform HDBSCAN Clustering
print('\n Start HDBSCAN Clustering')
time_start = time.time()
# training optics clustering model
hdb = cluster.HDBSCAN(min_cluster_size=clust_size, min_samples=minimum_samples, metric=metric, n_jobs = -1)
with joblib.parallel_backend('dask'):
hdb.fit(X)
#predictions from optics
labels = hdb.labels_
print('DBSCAN Clustering done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
hdb_result = pd.DataFrame(labels, index = self.data.index, columns=['Cluster ID HDBSCAN'])
#Prints the count of each cluster group
print(hdb_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return hdb_result
#### OPTICS
def makeoptics(self, X, clust_size, minimum_samples, metric):
try:
client = Client(processes=False) # create local cluster
# Perform OPTICS Clustering
print('\n Start OPTICS Clustering')
time_start = time.time()
# training optics clustering model
opt = cluster.OPTICS(min_samples=minimum_samples, min_cluster_size = clust_size, metric=metric, n_jobs = -1)
with joblib.parallel_backend('dask'):
opt.fit(X)
#predictions from optics
labels = opt.labels_
print('OPTICS Clustering done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
opt_result = pd.DataFrame(labels, index = self.data.index, columns=['Cluster ID OPTICS'])
#Prints the count of each cluster group
print(opt_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return opt_result
def makeSNN(self, X, num_neighbor, min_shared_neigh_prop):
try:
client = Client(processes=False) # create local cluster
# Perform Shared Nearest Neighbors (SNN) Clustering
print('\n Start SNN Clustering')
time_start = time.time()
# training snn clustering model predictions
snn = SNN(neighbor_num=num_neighbor, min_shared_neighbor_proportion=min_shared_neigh_prop) # Change neighbor_num to be < sample size
with joblib.parallel_backend('dask'):
snn_labels = snn.fit_predict(X)
snn_result = pd.DataFrame(snn_labels, index = self.data.index, columns=['Cluster ID SNN'])
print('SNN done! Time elapsed: {} seconds'.format(time.time()-time_start))
print('Dataset size of: ', self.num)
#Prints the count of each cluster group
print(snn_result.value_counts(sort=False))
except MemoryError:
print(MemoryError)
except Exception as error:
print(error)
print(error.__doc__)
else:
return snn_result