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
|
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
|
|
313 def dbscan(dataset, eps, min_samples):
|
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
|
|
334
|
23
|
335 write_to_csv(dataset, labels, 'clustering/dbscan_results.tsv')
|
16
|
336
|
|
337 ########################## hierachical #######################################
|
|
338
|
|
339 def hierachical_agglomerative(dataset, k_min, k_max):
|
0
|
340
|
23
|
341 if not os.path.exists('clustering'):
|
|
342 os.makedirs('clustering')
|
16
|
343
|
|
344 plt.figure(figsize=(10, 7))
|
|
345 plt.title("Customer Dendograms")
|
|
346 shc.dendrogram(shc.linkage(dataset, method='ward'))
|
|
347 fig = plt.gcf()
|
23
|
348 fig.savefig('clustering/dendogram.png', dpi=200)
|
16
|
349
|
|
350 range_n_clusters = [i for i in range(k_min, k_max+1)]
|
0
|
351
|
16
|
352 for n_clusters in range_n_clusters:
|
|
353
|
|
354 cluster = AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean', linkage='ward')
|
|
355 cluster.fit_predict(dataset)
|
|
356 cluster_labels = cluster.labels_
|
|
357
|
|
358 silhouette_avg = silhouette_score(dataset, cluster_labels)
|
23
|
359 write_to_csv(dataset, cluster_labels, 'clustering/hierarchical_with_' + str(n_clusters) + '_clusters.tsv')
|
|
360 #warning("For n_clusters =", n_clusters,
|
|
361 #"The average silhouette_score is :", silhouette_avg)
|
16
|
362
|
|
363
|
|
364
|
0
|
365
|
16
|
366
|
|
367 ############################# main ###########################################
|
0
|
368
|
|
369
|
|
370 def main():
|
16
|
371 if not os.path.exists('clustering'):
|
|
372 os.makedirs('clustering')
|
|
373
|
0
|
374 args = process_args(sys.argv)
|
16
|
375
|
|
376 #Data read
|
|
377
|
|
378 X = read_dataset(args.input)
|
|
379 X = pd.DataFrame.to_dict(X, orient='list')
|
|
380 X = rewrite_input(X)
|
|
381 X = pd.DataFrame.from_dict(X, orient = 'index')
|
|
382
|
|
383 for i in X.columns:
|
|
384 tmp = X[i][0]
|
|
385 if tmp == None:
|
|
386 X = X.drop(columns=[i])
|
|
387
|
|
388
|
|
389 if args.cluster_type == 'kmeans':
|
28
|
390 kmeans(args.k_min, args.k_max, X, args.elbow, args.silhouette, args.davies, args.best_cluster)
|
16
|
391
|
|
392 if args.cluster_type == 'dbscan':
|
|
393 dbscan(X, args.eps, args.min_samples)
|
|
394
|
|
395 if args.cluster_type == 'hierarchy':
|
|
396 hierachical_agglomerative(X, args.k_min, args.k_max)
|
|
397
|
|
398 ##############################################################################
|
0
|
399
|
|
400 if __name__ == "__main__":
|
28
|
401 main()
|