16
|
1 # -*- coding: utf-8 -*-
|
|
2 """
|
|
3 Created on Mon Jun 3 19:51:00 2019
|
|
4
|
|
5 @author: Narger
|
|
6 """
|
|
7
|
0
|
8 import sys
|
|
9 import argparse
|
16
|
10 import os
|
|
11 from sklearn.datasets import make_blobs
|
|
12 from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
|
|
13 from sklearn.metrics import silhouette_samples, silhouette_score, davies_bouldin_score, cluster
|
0
|
14 import matplotlib.pyplot as plt
|
16
|
15 import scipy.cluster.hierarchy as shc
|
|
16 import matplotlib.cm as cm
|
|
17 import numpy as np
|
|
18 import pandas as pd
|
0
|
19
|
16
|
20 ################################# process args ###############################
|
0
|
21
|
|
22 def process_args(args):
|
|
23 parser = argparse.ArgumentParser(usage = '%(prog)s [options]',
|
|
24 description = 'process some value\'s' +
|
|
25 ' genes to create class.')
|
16
|
26
|
|
27 parser.add_argument('-ol', '--out_log',
|
|
28 help = "Output log")
|
|
29
|
|
30 parser.add_argument('-in', '--input',
|
0
|
31 type = str,
|
16
|
32 help = 'input dataset')
|
|
33
|
|
34 parser.add_argument('-cy', '--cluster_type',
|
0
|
35 type = str,
|
16
|
36 choices = ['kmeans', 'meanshift', 'dbscan', 'hierarchy'],
|
|
37 default = 'kmeans',
|
|
38 help = 'choose clustering algorythm')
|
|
39
|
|
40 parser.add_argument('-k1', '--k_min',
|
|
41 type = int,
|
|
42 default = 2,
|
|
43 help = 'choose minimun cluster number to be generated')
|
|
44
|
|
45 parser.add_argument('-k2', '--k_max',
|
0
|
46 type = int,
|
16
|
47 default = 7,
|
|
48 help = 'choose maximum cluster number to be generated')
|
|
49
|
|
50 parser.add_argument('-el', '--elbow',
|
|
51 type = str,
|
|
52 default = 'false',
|
|
53 choices = ['true', 'false'],
|
|
54 help = 'choose if you want to generate an elbow plot for kmeans')
|
|
55
|
|
56 parser.add_argument('-si', '--silhouette',
|
0
|
57 type = str,
|
16
|
58 default = 'false',
|
|
59 choices = ['true', 'false'],
|
|
60 help = 'choose if you want silhouette plots')
|
|
61
|
|
62 parser.add_argument('-db', '--davies',
|
0
|
63 type = str,
|
16
|
64 default = 'false',
|
|
65 choices = ['true', 'false'],
|
|
66 help = 'choose if you want davies bouldin scores')
|
|
67
|
0
|
68 parser.add_argument('-td', '--tool_dir',
|
|
69 type = str,
|
|
70 required = True,
|
|
71 help = 'your tool directory')
|
16
|
72
|
|
73 parser.add_argument('-ms', '--min_samples',
|
|
74 type = int,
|
|
75 help = 'min samples for dbscan (optional)')
|
|
76
|
|
77 parser.add_argument('-ep', '--eps',
|
|
78 type = int,
|
|
79 help = 'eps for dbscan (optional)')
|
|
80
|
|
81
|
0
|
82 args = parser.parse_args()
|
|
83 return args
|
|
84
|
|
85 ########################### warning ###########################################
|
|
86
|
|
87 def warning(s):
|
|
88 args = process_args(sys.argv)
|
|
89 with open(args.out_log, 'a') as log:
|
16
|
90 log.write(s + "\n\n")
|
|
91 print(s)
|
0
|
92
|
16
|
93 ########################## read dataset ######################################
|
|
94
|
|
95 def read_dataset(dataset):
|
0
|
96 try:
|
16
|
97 dataset = pd.read_csv(dataset, sep = '\t', header = 0)
|
0
|
98 except pd.errors.EmptyDataError:
|
16
|
99 sys.exit('Execution aborted: wrong format of dataset\n')
|
0
|
100 if len(dataset.columns) < 2:
|
16
|
101 sys.exit('Execution aborted: wrong format of dataset\n')
|
|
102 return dataset
|
|
103
|
|
104 ############################ rewrite_input ###################################
|
|
105
|
|
106 def rewrite_input(dataset):
|
|
107 #Riscrivo il dataset come dizionario di liste,
|
|
108 #non come dizionario di dizionari
|
|
109
|
|
110 for key, val in dataset.items():
|
|
111 l = []
|
|
112 for i in val:
|
|
113 if i == 'None':
|
|
114 l.append(None)
|
|
115 else:
|
|
116 l.append(float(i))
|
|
117
|
|
118 dataset[key] = l
|
|
119
|
0
|
120 return dataset
|
|
121
|
16
|
122 ############################## write to csv ##################################
|
0
|
123
|
16
|
124 def write_to_csv (dataset, labels, name):
|
|
125 list_labels = labels
|
|
126 list_values = dataset
|
0
|
127
|
16
|
128 list_values = list_values.tolist()
|
|
129 d = {'Label' : list_labels, 'Value' : list_values}
|
0
|
130
|
16
|
131 df = pd.DataFrame(d, columns=['Value','Label'])
|
0
|
132
|
16
|
133 dest = name + '.tsv'
|
|
134 df.to_csv(dest, sep = '\t', index = False,
|
|
135 header = ['Value', 'Label'])
|
|
136
|
|
137 ########################### trova il massimo in lista ########################
|
|
138 def max_index (lista):
|
|
139 best = -1
|
|
140 best_index = 0
|
|
141 for i in range(len(lista)):
|
|
142 if lista[i] > best:
|
|
143 best = lista [i]
|
|
144 best_index = i
|
|
145
|
|
146 return best_index
|
|
147
|
|
148 ################################ kmeans #####################################
|
|
149
|
|
150 def kmeans (k_min, k_max, dataset, elbow, silhouette, davies):
|
|
151 if not os.path.exists('clustering/kmeans_output'):
|
|
152 os.makedirs('clustering/kmeans_output')
|
|
153
|
|
154
|
|
155 if elbow == 'true':
|
|
156 elbow = True
|
|
157 else:
|
|
158 elbow = False
|
|
159
|
|
160 if silhouette == 'true':
|
|
161 silhouette = True
|
|
162 else:
|
|
163 silhouette = False
|
|
164
|
|
165 if davies == 'true':
|
|
166 davies = True
|
|
167 else:
|
|
168 davies = False
|
|
169
|
0
|
170
|
16
|
171 range_n_clusters = [i for i in range(k_min, k_max+1)]
|
|
172 distortions = []
|
|
173 scores = []
|
|
174 all_labels = []
|
|
175
|
|
176 for n_clusters in range_n_clusters:
|
|
177 clusterer = KMeans(n_clusters=n_clusters, random_state=10)
|
|
178 cluster_labels = clusterer.fit_predict(dataset)
|
|
179
|
|
180 all_labels.append(cluster_labels)
|
|
181 silhouette_avg = silhouette_score(dataset, cluster_labels)
|
|
182 scores.append(silhouette_avg)
|
|
183 distortions.append(clusterer.fit(dataset).inertia_)
|
|
184
|
|
185 best = max_index(scores) + k_min
|
|
186
|
|
187 for i in range(len(all_labels)):
|
|
188 prefix = ''
|
|
189 if (i + k_min == best):
|
|
190 prefix = '_BEST'
|
|
191
|
|
192 write_to_csv(dataset, all_labels[i], 'clustering/kmeans_output/kmeans_with_' + str(i + k_min) + prefix + '_clusters.tsv')
|
|
193
|
|
194 if davies:
|
|
195 with np.errstate(divide='ignore', invalid='ignore'):
|
|
196 davies_bouldin = davies_bouldin_score(dataset, all_labels[i])
|
|
197 warning("\nFor n_clusters = " + str(i + k_min) +
|
|
198 " The average davies bouldin score is: " + str(davies_bouldin))
|
|
199
|
|
200
|
|
201 if silhouette:
|
|
202 silihouette_draw(dataset, all_labels[i], i + k_min, 'clustering/kmeans_output/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png')
|
|
203
|
|
204
|
|
205 if elbow:
|
|
206 elbow_plot(distortions, k_min,k_max)
|
0
|
207
|
16
|
208
|
|
209
|
|
210
|
0
|
211
|
16
|
212 ############################## elbow_plot ####################################
|
|
213
|
|
214 def elbow_plot (distortions, k_min, k_max):
|
|
215 plt.figure(0)
|
|
216 plt.plot(range(k_min, k_max+1), distortions, marker = 'o')
|
|
217 plt.xlabel('Number of cluster')
|
|
218 plt.ylabel('Distortion')
|
|
219 s = 'clustering/kmeans_output/elbow_plot.png'
|
|
220 fig = plt.gcf()
|
|
221 fig.set_size_inches(18.5, 10.5, forward = True)
|
|
222 fig.savefig(s, dpi=100)
|
|
223
|
|
224
|
|
225 ############################## silhouette plot ###############################
|
|
226 def silihouette_draw(dataset, labels, n_clusters, path):
|
|
227 silhouette_avg = silhouette_score(dataset, labels)
|
|
228 warning("For n_clusters = " + str(n_clusters) +
|
|
229 " The average silhouette_score is: " + str(silhouette_avg))
|
|
230
|
|
231 plt.close('all')
|
|
232 # Create a subplot with 1 row and 2 columns
|
|
233 fig, (ax1) = plt.subplots(1, 1)
|
|
234
|
|
235 fig.set_size_inches(18, 7)
|
|
236
|
|
237 # The 1st subplot is the silhouette plot
|
|
238 # The silhouette coefficient can range from -1, 1 but in this example all
|
|
239 # lie within [-0.1, 1]
|
|
240 ax1.set_xlim([-1, 1])
|
|
241 # The (n_clusters+1)*10 is for inserting blank space between silhouette
|
|
242 # plots of individual clusters, to demarcate them clearly.
|
|
243 ax1.set_ylim([0, len(dataset) + (n_clusters + 1) * 10])
|
|
244
|
|
245 # Compute the silhouette scores for each sample
|
|
246 sample_silhouette_values = silhouette_samples(dataset, labels)
|
|
247
|
|
248 y_lower = 10
|
|
249 for i in range(n_clusters):
|
|
250 # Aggregate the silhouette scores for samples belonging to
|
|
251 # cluster i, and sort them
|
|
252 ith_cluster_silhouette_values = \
|
|
253 sample_silhouette_values[labels == i]
|
|
254
|
|
255 ith_cluster_silhouette_values.sort()
|
|
256
|
|
257 size_cluster_i = ith_cluster_silhouette_values.shape[0]
|
|
258 y_upper = y_lower + size_cluster_i
|
|
259
|
|
260 color = cm.nipy_spectral(float(i) / n_clusters)
|
|
261 ax1.fill_betweenx(np.arange(y_lower, y_upper),
|
|
262 0, ith_cluster_silhouette_values,
|
|
263 facecolor=color, edgecolor=color, alpha=0.7)
|
|
264
|
|
265 # Label the silhouette plots with their cluster numbers at the middle
|
|
266 ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
|
|
267
|
|
268 # Compute the new y_lower for next plot
|
|
269 y_lower = y_upper + 10 # 10 for the 0 samples
|
|
270
|
|
271 ax1.set_title("The silhouette plot for the various clusters.")
|
|
272 ax1.set_xlabel("The silhouette coefficient values")
|
|
273 ax1.set_ylabel("Cluster label")
|
|
274
|
|
275 # The vertical line for average silhouette score of all the values
|
|
276 ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
|
|
277
|
|
278 ax1.set_yticks([]) # Clear the yaxis labels / ticks
|
|
279 ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
|
|
280
|
|
281
|
|
282 plt.suptitle(("Silhouette analysis for clustering on sample data "
|
|
283 "with n_clusters = " + str(n_clusters) + "\nAverage silhouette_score = " + str(silhouette_avg)), fontsize=12, fontweight='bold')
|
|
284
|
|
285
|
|
286 plt.savefig(path, bbox_inches='tight')
|
|
287
|
|
288 ######################## dbscan ##############################################
|
|
289
|
|
290 def dbscan(dataset, eps, min_samples):
|
|
291 if not os.path.exists('clustering/dbscan_output'):
|
|
292 os.makedirs('clustering/dbscan_output')
|
|
293
|
|
294 if eps is not None:
|
|
295 clusterer = DBSCAN(eps = eps, min_samples = min_samples)
|
0
|
296 else:
|
16
|
297 clusterer = DBSCAN()
|
|
298
|
|
299 clustering = clusterer.fit(dataset)
|
|
300
|
|
301 core_samples_mask = np.zeros_like(clustering.labels_, dtype=bool)
|
|
302 core_samples_mask[clustering.core_sample_indices_] = True
|
|
303 labels = clustering.labels_
|
0
|
304
|
16
|
305 # Number of clusters in labels, ignoring noise if present.
|
|
306 n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
|
|
307
|
|
308 silhouette_avg = silhouette_score(dataset, labels)
|
|
309 warning("For n_clusters =" + str(n_clusters_) +
|
|
310 "The average silhouette_score is :" + str(silhouette_avg))
|
|
311
|
|
312 ##TODO: PLOT SU DBSCAN (no centers) e HIERARCHICAL
|
0
|
313
|
16
|
314 # Black removed and is used for noise instead.
|
|
315 unique_labels = set(labels)
|
|
316 colors = [plt.cm.Spectral(each)
|
|
317 for each in np.linspace(0, 1, len(unique_labels))]
|
|
318 for k, col in zip(unique_labels, colors):
|
|
319 if k == -1:
|
|
320 # Black used for noise.
|
|
321 col = [0, 0, 0, 1]
|
|
322
|
|
323 class_member_mask = (labels == k)
|
|
324
|
|
325 xy = dataset[class_member_mask & core_samples_mask]
|
|
326 plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
|
|
327 markeredgecolor='k', markersize=14)
|
|
328
|
|
329 xy = dataset[class_member_mask & ~core_samples_mask]
|
|
330 plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
|
|
331 markeredgecolor='k', markersize=6)
|
0
|
332
|
16
|
333 plt.title('Estimated number of clusters: %d' % n_clusters_)
|
|
334 s = 'clustering/dbscan_output/dbscan_plot.png'
|
|
335 fig = plt.gcf()
|
|
336 fig.set_size_inches(18.5, 10.5, forward = True)
|
|
337 fig.savefig(s, dpi=100)
|
|
338
|
|
339
|
|
340 write_to_csv(dataset, labels, 'clustering/dbscan_output/dbscan_results.tsv')
|
|
341
|
|
342 ########################## hierachical #######################################
|
|
343
|
|
344 def hierachical_agglomerative(dataset, k_min, k_max):
|
0
|
345
|
16
|
346 if not os.path.exists('clustering/agglomerative_output'):
|
|
347 os.makedirs('clustering/agglomerative_output')
|
|
348
|
|
349 plt.figure(figsize=(10, 7))
|
|
350 plt.title("Customer Dendograms")
|
|
351 shc.dendrogram(shc.linkage(dataset, method='ward'))
|
|
352 fig = plt.gcf()
|
|
353 fig.savefig('clustering/agglomerative_output/dendogram.png', dpi=200)
|
|
354
|
|
355 range_n_clusters = [i for i in range(k_min, k_max+1)]
|
0
|
356
|
16
|
357 for n_clusters in range_n_clusters:
|
|
358
|
|
359 cluster = AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean', linkage='ward')
|
|
360 cluster.fit_predict(dataset)
|
|
361 cluster_labels = cluster.labels_
|
|
362
|
|
363 silhouette_avg = silhouette_score(dataset, cluster_labels)
|
|
364 warning("For n_clusters =", n_clusters,
|
|
365 "The average silhouette_score is :", silhouette_avg)
|
|
366
|
|
367 plt.clf()
|
|
368 plt.figure(figsize=(10, 7))
|
|
369 plt.title("Agglomerative Hierarchical Clustering\nwith " + str(n_clusters) + " clusters and " + str(silhouette_avg) + " silhouette score")
|
|
370 plt.scatter(dataset[:,0], dataset[:,1], c = cluster_labels, cmap='rainbow')
|
|
371 s = 'clustering/agglomerative_output/hierachical_' + str(n_clusters) + '_clusters.png'
|
|
372 fig = plt.gcf()
|
|
373 fig.set_size_inches(10, 7, forward = True)
|
|
374 fig.savefig(s, dpi=200)
|
|
375
|
|
376 write_to_csv(dataset, cluster_labels, 'clustering/agglomerative_output/agglomerative_hierarchical_with_' + str(n_clusters) + '_clusters.tsv')
|
|
377
|
|
378
|
0
|
379
|
16
|
380
|
|
381 ############################# main ###########################################
|
0
|
382
|
|
383
|
|
384 def main():
|
16
|
385 if not os.path.exists('clustering'):
|
|
386 os.makedirs('clustering')
|
|
387
|
0
|
388 args = process_args(sys.argv)
|
16
|
389
|
|
390 #Data read
|
|
391
|
|
392 X = read_dataset(args.input)
|
|
393 X = pd.DataFrame.to_dict(X, orient='list')
|
|
394 X = rewrite_input(X)
|
|
395 X = pd.DataFrame.from_dict(X, orient = 'index')
|
|
396
|
|
397 for i in X.columns:
|
|
398 tmp = X[i][0]
|
|
399 if tmp == None:
|
|
400 X = X.drop(columns=[i])
|
|
401
|
|
402 X = pd.DataFrame.to_numpy(X)
|
|
403
|
|
404
|
|
405 if args.cluster_type == 'kmeans':
|
|
406 kmeans(args.k_min, args.k_max, X, args.elbow, args.silhouette, args.davies)
|
|
407
|
|
408 if args.cluster_type == 'dbscan':
|
|
409 dbscan(X, args.eps, args.min_samples)
|
|
410
|
|
411 if args.cluster_type == 'hierarchy':
|
|
412 hierachical_agglomerative(X, args.k_min, args.k_max)
|
|
413
|
|
414 ##############################################################################
|
0
|
415
|
|
416 if __name__ == "__main__":
|
6
|
417 main()
|