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