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