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
|
36
|
116 dataset.pop('Reactions', None)
|
|
117
|
16
|
118 for key, val in dataset.items():
|
|
119 l = []
|
|
120 for i in val:
|
|
121 if i == 'None':
|
|
122 l.append(None)
|
|
123 else:
|
|
124 l.append(float(i))
|
|
125
|
|
126 dataset[key] = l
|
|
127
|
0
|
128 return dataset
|
|
129
|
16
|
130 ############################## write to csv ##################################
|
0
|
131
|
16
|
132 def write_to_csv (dataset, labels, name):
|
23
|
133 #labels = predict
|
|
134 predict = [x+1 for x in labels]
|
|
135
|
|
136 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
|
0
|
137
|
23
|
138 dest = name
|
|
139 classe.to_csv(dest, sep = '\t', index = False,
|
|
140 header = ['Patient_ID', 'Class'])
|
28
|
141
|
16
|
142 ########################### trova il massimo in lista ########################
|
|
143 def max_index (lista):
|
|
144 best = -1
|
|
145 best_index = 0
|
|
146 for i in range(len(lista)):
|
|
147 if lista[i] > best:
|
|
148 best = lista [i]
|
|
149 best_index = i
|
|
150
|
|
151 return best_index
|
|
152
|
|
153 ################################ kmeans #####################################
|
|
154
|
28
|
155 def kmeans (k_min, k_max, dataset, elbow, silhouette, davies, best_cluster):
|
23
|
156 if not os.path.exists('clustering'):
|
|
157 os.makedirs('clustering')
|
16
|
158
|
|
159
|
|
160 if elbow == 'true':
|
|
161 elbow = True
|
|
162 else:
|
|
163 elbow = False
|
|
164
|
|
165 if silhouette == 'true':
|
|
166 silhouette = True
|
|
167 else:
|
|
168 silhouette = False
|
|
169
|
|
170 if davies == 'true':
|
|
171 davies = True
|
|
172 else:
|
|
173 davies = False
|
|
174
|
0
|
175
|
16
|
176 range_n_clusters = [i for i in range(k_min, k_max+1)]
|
|
177 distortions = []
|
|
178 scores = []
|
|
179 all_labels = []
|
|
180
|
31
|
181 clusterer = KMeans(n_clusters=1, random_state=10)
|
|
182 distortions.append(clusterer.fit(dataset).inertia_)
|
|
183
|
|
184
|
16
|
185 for n_clusters in range_n_clusters:
|
|
186 clusterer = KMeans(n_clusters=n_clusters, random_state=10)
|
|
187 cluster_labels = clusterer.fit_predict(dataset)
|
|
188
|
|
189 all_labels.append(cluster_labels)
|
28
|
190 if n_clusters == 1:
|
|
191 silhouette_avg = 0
|
|
192 else:
|
|
193 silhouette_avg = silhouette_score(dataset, cluster_labels)
|
16
|
194 scores.append(silhouette_avg)
|
|
195 distortions.append(clusterer.fit(dataset).inertia_)
|
|
196
|
|
197 best = max_index(scores) + k_min
|
|
198
|
|
199 for i in range(len(all_labels)):
|
|
200 prefix = ''
|
|
201 if (i + k_min == best):
|
|
202 prefix = '_BEST'
|
|
203
|
23
|
204 write_to_csv(dataset, all_labels[i], 'clustering/kmeans_with_' + str(i + k_min) + prefix + '_clusters.tsv')
|
28
|
205
|
|
206
|
|
207 if (prefix == '_BEST'):
|
|
208 labels = all_labels[i]
|
|
209 predict = [x+1 for x in labels]
|
|
210 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
|
|
211 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
|
|
212
|
34
|
213
|
16
|
214
|
|
215
|
|
216 if silhouette:
|
23
|
217 silihouette_draw(dataset, all_labels[i], i + k_min, 'clustering/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png')
|
16
|
218
|
|
219
|
|
220 if elbow:
|
|
221 elbow_plot(distortions, k_min,k_max)
|
0
|
222
|
16
|
223
|
|
224
|
|
225
|
0
|
226
|
16
|
227 ############################## elbow_plot ####################################
|
|
228
|
|
229 def elbow_plot (distortions, k_min, k_max):
|
|
230 plt.figure(0)
|
31
|
231 x = list(range(k_min, k_max + 1))
|
|
232 x.insert(0, 1)
|
|
233 plt.plot(x, distortions, marker = 'o')
|
|
234 plt.xlabel('Number of clusters (k)')
|
16
|
235 plt.ylabel('Distortion')
|
23
|
236 s = 'clustering/elbow_plot.png'
|
16
|
237 fig = plt.gcf()
|
|
238 fig.set_size_inches(18.5, 10.5, forward = True)
|
|
239 fig.savefig(s, dpi=100)
|
|
240
|
|
241
|
|
242 ############################## silhouette plot ###############################
|
|
243 def silihouette_draw(dataset, labels, n_clusters, path):
|
28
|
244 if n_clusters == 1:
|
|
245 return None
|
|
246
|
16
|
247 silhouette_avg = silhouette_score(dataset, labels)
|
|
248 warning("For n_clusters = " + str(n_clusters) +
|
|
249 " The average silhouette_score is: " + str(silhouette_avg))
|
|
250
|
|
251 plt.close('all')
|
|
252 # Create a subplot with 1 row and 2 columns
|
|
253 fig, (ax1) = plt.subplots(1, 1)
|
|
254
|
|
255 fig.set_size_inches(18, 7)
|
|
256
|
|
257 # The 1st subplot is the silhouette plot
|
|
258 # The silhouette coefficient can range from -1, 1 but in this example all
|
|
259 # lie within [-0.1, 1]
|
|
260 ax1.set_xlim([-1, 1])
|
|
261 # The (n_clusters+1)*10 is for inserting blank space between silhouette
|
|
262 # plots of individual clusters, to demarcate them clearly.
|
|
263 ax1.set_ylim([0, len(dataset) + (n_clusters + 1) * 10])
|
|
264
|
|
265 # Compute the silhouette scores for each sample
|
|
266 sample_silhouette_values = silhouette_samples(dataset, labels)
|
|
267
|
|
268 y_lower = 10
|
|
269 for i in range(n_clusters):
|
|
270 # Aggregate the silhouette scores for samples belonging to
|
|
271 # cluster i, and sort them
|
|
272 ith_cluster_silhouette_values = \
|
|
273 sample_silhouette_values[labels == i]
|
|
274
|
|
275 ith_cluster_silhouette_values.sort()
|
|
276
|
|
277 size_cluster_i = ith_cluster_silhouette_values.shape[0]
|
|
278 y_upper = y_lower + size_cluster_i
|
|
279
|
|
280 color = cm.nipy_spectral(float(i) / n_clusters)
|
|
281 ax1.fill_betweenx(np.arange(y_lower, y_upper),
|
|
282 0, ith_cluster_silhouette_values,
|
|
283 facecolor=color, edgecolor=color, alpha=0.7)
|
|
284
|
|
285 # Label the silhouette plots with their cluster numbers at the middle
|
|
286 ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
|
|
287
|
|
288 # Compute the new y_lower for next plot
|
|
289 y_lower = y_upper + 10 # 10 for the 0 samples
|
|
290
|
|
291 ax1.set_title("The silhouette plot for the various clusters.")
|
|
292 ax1.set_xlabel("The silhouette coefficient values")
|
|
293 ax1.set_ylabel("Cluster label")
|
|
294
|
|
295 # The vertical line for average silhouette score of all the values
|
|
296 ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
|
|
297
|
|
298 ax1.set_yticks([]) # Clear the yaxis labels / ticks
|
|
299 ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
|
|
300
|
|
301
|
|
302 plt.suptitle(("Silhouette analysis for clustering on sample data "
|
|
303 "with n_clusters = " + str(n_clusters) + "\nAverage silhouette_score = " + str(silhouette_avg)), fontsize=12, fontweight='bold')
|
|
304
|
|
305
|
|
306 plt.savefig(path, bbox_inches='tight')
|
|
307
|
|
308 ######################## dbscan ##############################################
|
|
309
|
33
|
310 def dbscan(dataset, eps, min_samples, best_cluster):
|
23
|
311 if not os.path.exists('clustering'):
|
|
312 os.makedirs('clustering')
|
16
|
313
|
|
314 if eps is not None:
|
|
315 clusterer = DBSCAN(eps = eps, min_samples = min_samples)
|
0
|
316 else:
|
16
|
317 clusterer = DBSCAN()
|
|
318
|
|
319 clustering = clusterer.fit(dataset)
|
|
320
|
|
321 core_samples_mask = np.zeros_like(clustering.labels_, dtype=bool)
|
|
322 core_samples_mask[clustering.core_sample_indices_] = True
|
|
323 labels = clustering.labels_
|
0
|
324
|
16
|
325 # Number of clusters in labels, ignoring noise if present.
|
|
326 n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
|
|
327
|
|
328
|
33
|
329 labels = labels
|
|
330 predict = [x+1 for x in labels]
|
|
331 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
|
|
332 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
|
|
333
|
16
|
334
|
|
335 ########################## hierachical #######################################
|
|
336
|
34
|
337 def hierachical_agglomerative(dataset, k_min, k_max, best_cluster, silhouette):
|
0
|
338
|
23
|
339 if not os.path.exists('clustering'):
|
|
340 os.makedirs('clustering')
|
16
|
341
|
|
342 plt.figure(figsize=(10, 7))
|
|
343 plt.title("Customer Dendograms")
|
|
344 shc.dendrogram(shc.linkage(dataset, method='ward'))
|
|
345 fig = plt.gcf()
|
23
|
346 fig.savefig('clustering/dendogram.png', dpi=200)
|
16
|
347
|
|
348 range_n_clusters = [i for i in range(k_min, k_max+1)]
|
0
|
349
|
33
|
350 scores = []
|
|
351 labels = []
|
34
|
352
|
33
|
353 for n_clusters in range_n_clusters:
|
16
|
354 cluster = AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean', linkage='ward')
|
|
355 cluster.fit_predict(dataset)
|
|
356 cluster_labels = cluster.labels_
|
33
|
357 labels.append(cluster_labels)
|
23
|
358 write_to_csv(dataset, cluster_labels, 'clustering/hierarchical_with_' + str(n_clusters) + '_clusters.tsv')
|
33
|
359
|
|
360 best = max_index(scores) + k_min
|
34
|
361
|
|
362 for i in range(len(labels)):
|
|
363 prefix = ''
|
|
364 if (i + k_min == best):
|
|
365 prefix = '_BEST'
|
|
366 if silhouette == 'true':
|
|
367 silihouette_draw(dataset, labels[i], i + k_min, 'clustering/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png')
|
33
|
368
|
|
369 for i in range(len(labels)):
|
|
370 if (i + k_min == best):
|
|
371 labels = labels[i]
|
|
372 predict = [x+1 for x in labels]
|
|
373 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
|
|
374 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
|
34
|
375
|
16
|
376
|
|
377 ############################# main ###########################################
|
0
|
378
|
|
379
|
|
380 def main():
|
16
|
381 if not os.path.exists('clustering'):
|
|
382 os.makedirs('clustering')
|
|
383
|
0
|
384 args = process_args(sys.argv)
|
16
|
385
|
|
386 #Data read
|
|
387
|
|
388 X = read_dataset(args.input)
|
|
389 X = pd.DataFrame.to_dict(X, orient='list')
|
|
390 X = rewrite_input(X)
|
|
391 X = pd.DataFrame.from_dict(X, orient = 'index')
|
|
392
|
|
393 for i in X.columns:
|
|
394 tmp = X[i][0]
|
|
395 if tmp == None:
|
|
396 X = X.drop(columns=[i])
|
|
397
|
|
398
|
|
399 if args.cluster_type == 'kmeans':
|
28
|
400 kmeans(args.k_min, args.k_max, X, args.elbow, args.silhouette, args.davies, args.best_cluster)
|
16
|
401
|
|
402 if args.cluster_type == 'dbscan':
|
33
|
403 dbscan(X, args.eps, args.min_samples, args.best_cluster)
|
16
|
404
|
|
405 if args.cluster_type == 'hierarchy':
|
34
|
406 hierachical_agglomerative(X, args.k_min, args.k_max, args.best_cluster, args.silhouette)
|
16
|
407
|
|
408 ##############################################################################
|
0
|
409
|
|
410 if __name__ == "__main__":
|
28
|
411 main()
|