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