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',
|
|
75 type = int,
|
|
76 help = 'min samples for dbscan (optional)')
|
|
77
|
|
78 parser.add_argument('-ep', '--eps',
|
|
79 type = int,
|
|
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
|
|
179 for n_clusters in range_n_clusters:
|
|
180 clusterer = KMeans(n_clusters=n_clusters, random_state=10)
|
|
181 cluster_labels = clusterer.fit_predict(dataset)
|
|
182
|
|
183 all_labels.append(cluster_labels)
|
28
|
184 if n_clusters == 1:
|
|
185 silhouette_avg = 0
|
|
186 else:
|
|
187 silhouette_avg = silhouette_score(dataset, cluster_labels)
|
16
|
188 scores.append(silhouette_avg)
|
|
189 distortions.append(clusterer.fit(dataset).inertia_)
|
|
190
|
|
191 best = max_index(scores) + k_min
|
|
192
|
|
193 for i in range(len(all_labels)):
|
|
194 prefix = ''
|
|
195 if (i + k_min == best):
|
|
196 prefix = '_BEST'
|
|
197
|
23
|
198 write_to_csv(dataset, all_labels[i], 'clustering/kmeans_with_' + str(i + k_min) + prefix + '_clusters.tsv')
|
28
|
199
|
|
200
|
|
201 if (prefix == '_BEST'):
|
|
202 labels = all_labels[i]
|
|
203 predict = [x+1 for x in labels]
|
|
204 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
|
|
205 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
|
|
206
|
16
|
207
|
|
208 if davies:
|
|
209 with np.errstate(divide='ignore', invalid='ignore'):
|
|
210 davies_bouldin = davies_bouldin_score(dataset, all_labels[i])
|
|
211 warning("\nFor n_clusters = " + str(i + k_min) +
|
|
212 " The average davies bouldin score is: " + str(davies_bouldin))
|
|
213
|
|
214
|
|
215 if silhouette:
|
23
|
216 silihouette_draw(dataset, all_labels[i], i + k_min, 'clustering/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png')
|
16
|
217
|
|
218
|
|
219 if elbow:
|
|
220 elbow_plot(distortions, k_min,k_max)
|
0
|
221
|
16
|
222
|
|
223
|
|
224
|
0
|
225
|
16
|
226 ############################## elbow_plot ####################################
|
|
227
|
|
228 def elbow_plot (distortions, k_min, k_max):
|
|
229 plt.figure(0)
|
|
230 plt.plot(range(k_min, k_max+1), distortions, marker = 'o')
|
|
231 plt.xlabel('Number of cluster')
|
|
232 plt.ylabel('Distortion')
|
23
|
233 s = 'clustering/elbow_plot.png'
|
16
|
234 fig = plt.gcf()
|
|
235 fig.set_size_inches(18.5, 10.5, forward = True)
|
|
236 fig.savefig(s, dpi=100)
|
|
237
|
|
238
|
|
239 ############################## silhouette plot ###############################
|
|
240 def silihouette_draw(dataset, labels, n_clusters, path):
|
28
|
241 if n_clusters == 1:
|
|
242 return None
|
|
243
|
16
|
244 silhouette_avg = silhouette_score(dataset, labels)
|
|
245 warning("For n_clusters = " + str(n_clusters) +
|
|
246 " The average silhouette_score is: " + str(silhouette_avg))
|
|
247
|
|
248 plt.close('all')
|
|
249 # Create a subplot with 1 row and 2 columns
|
|
250 fig, (ax1) = plt.subplots(1, 1)
|
|
251
|
|
252 fig.set_size_inches(18, 7)
|
|
253
|
|
254 # The 1st subplot is the silhouette plot
|
|
255 # The silhouette coefficient can range from -1, 1 but in this example all
|
|
256 # lie within [-0.1, 1]
|
|
257 ax1.set_xlim([-1, 1])
|
|
258 # The (n_clusters+1)*10 is for inserting blank space between silhouette
|
|
259 # plots of individual clusters, to demarcate them clearly.
|
|
260 ax1.set_ylim([0, len(dataset) + (n_clusters + 1) * 10])
|
|
261
|
|
262 # Compute the silhouette scores for each sample
|
|
263 sample_silhouette_values = silhouette_samples(dataset, labels)
|
|
264
|
|
265 y_lower = 10
|
|
266 for i in range(n_clusters):
|
|
267 # Aggregate the silhouette scores for samples belonging to
|
|
268 # cluster i, and sort them
|
|
269 ith_cluster_silhouette_values = \
|
|
270 sample_silhouette_values[labels == i]
|
|
271
|
|
272 ith_cluster_silhouette_values.sort()
|
|
273
|
|
274 size_cluster_i = ith_cluster_silhouette_values.shape[0]
|
|
275 y_upper = y_lower + size_cluster_i
|
|
276
|
|
277 color = cm.nipy_spectral(float(i) / n_clusters)
|
|
278 ax1.fill_betweenx(np.arange(y_lower, y_upper),
|
|
279 0, ith_cluster_silhouette_values,
|
|
280 facecolor=color, edgecolor=color, alpha=0.7)
|
|
281
|
|
282 # Label the silhouette plots with their cluster numbers at the middle
|
|
283 ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
|
|
284
|
|
285 # Compute the new y_lower for next plot
|
|
286 y_lower = y_upper + 10 # 10 for the 0 samples
|
|
287
|
|
288 ax1.set_title("The silhouette plot for the various clusters.")
|
|
289 ax1.set_xlabel("The silhouette coefficient values")
|
|
290 ax1.set_ylabel("Cluster label")
|
|
291
|
|
292 # The vertical line for average silhouette score of all the values
|
|
293 ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
|
|
294
|
|
295 ax1.set_yticks([]) # Clear the yaxis labels / ticks
|
|
296 ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
|
|
297
|
|
298
|
|
299 plt.suptitle(("Silhouette analysis for clustering on sample data "
|
|
300 "with n_clusters = " + str(n_clusters) + "\nAverage silhouette_score = " + str(silhouette_avg)), fontsize=12, fontweight='bold')
|
|
301
|
|
302
|
|
303 plt.savefig(path, bbox_inches='tight')
|
|
304
|
|
305 ######################## dbscan ##############################################
|
|
306
|
|
307 def dbscan(dataset, eps, min_samples):
|
23
|
308 if not os.path.exists('clustering'):
|
|
309 os.makedirs('clustering')
|
16
|
310
|
|
311 if eps is not None:
|
|
312 clusterer = DBSCAN(eps = eps, min_samples = min_samples)
|
0
|
313 else:
|
16
|
314 clusterer = DBSCAN()
|
|
315
|
|
316 clustering = clusterer.fit(dataset)
|
|
317
|
|
318 core_samples_mask = np.zeros_like(clustering.labels_, dtype=bool)
|
|
319 core_samples_mask[clustering.core_sample_indices_] = True
|
|
320 labels = clustering.labels_
|
0
|
321
|
16
|
322 # Number of clusters in labels, ignoring noise if present.
|
|
323 n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
|
|
324
|
|
325
|
|
326 ##TODO: PLOT SU DBSCAN (no centers) e HIERARCHICAL
|
|
327
|
|
328
|
23
|
329 write_to_csv(dataset, labels, 'clustering/dbscan_results.tsv')
|
16
|
330
|
|
331 ########################## hierachical #######################################
|
|
332
|
|
333 def hierachical_agglomerative(dataset, k_min, k_max):
|
0
|
334
|
23
|
335 if not os.path.exists('clustering'):
|
|
336 os.makedirs('clustering')
|
16
|
337
|
|
338 plt.figure(figsize=(10, 7))
|
|
339 plt.title("Customer Dendograms")
|
|
340 shc.dendrogram(shc.linkage(dataset, method='ward'))
|
|
341 fig = plt.gcf()
|
23
|
342 fig.savefig('clustering/dendogram.png', dpi=200)
|
16
|
343
|
|
344 range_n_clusters = [i for i in range(k_min, k_max+1)]
|
0
|
345
|
16
|
346 for n_clusters in range_n_clusters:
|
|
347
|
|
348 cluster = AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean', linkage='ward')
|
|
349 cluster.fit_predict(dataset)
|
|
350 cluster_labels = cluster.labels_
|
|
351
|
|
352 silhouette_avg = silhouette_score(dataset, cluster_labels)
|
23
|
353 write_to_csv(dataset, cluster_labels, 'clustering/hierarchical_with_' + str(n_clusters) + '_clusters.tsv')
|
|
354 #warning("For n_clusters =", n_clusters,
|
|
355 #"The average silhouette_score is :", silhouette_avg)
|
16
|
356
|
|
357
|
|
358
|
0
|
359
|
16
|
360
|
|
361 ############################# main ###########################################
|
0
|
362
|
|
363
|
|
364 def main():
|
16
|
365 if not os.path.exists('clustering'):
|
|
366 os.makedirs('clustering')
|
|
367
|
0
|
368 args = process_args(sys.argv)
|
16
|
369
|
|
370 #Data read
|
|
371
|
|
372 X = read_dataset(args.input)
|
|
373 X = pd.DataFrame.to_dict(X, orient='list')
|
|
374 X = rewrite_input(X)
|
|
375 X = pd.DataFrame.from_dict(X, orient = 'index')
|
|
376
|
|
377 for i in X.columns:
|
|
378 tmp = X[i][0]
|
|
379 if tmp == None:
|
|
380 X = X.drop(columns=[i])
|
|
381
|
|
382
|
|
383 if args.cluster_type == 'kmeans':
|
28
|
384 kmeans(args.k_min, args.k_max, X, args.elbow, args.silhouette, args.davies, args.best_cluster)
|
16
|
385
|
|
386 if args.cluster_type == 'dbscan':
|
|
387 dbscan(X, args.eps, args.min_samples)
|
|
388
|
|
389 if args.cluster_type == 'hierarchy':
|
|
390 hierachical_agglomerative(X, args.k_min, args.k_max)
|
|
391
|
|
392 ##############################################################################
|
0
|
393
|
|
394 if __name__ == "__main__":
|
28
|
395 main()
|