annotate marea_cluster.py @ 38:4e1b466935cd draft

Uploaded
author bimib
date Mon, 25 Nov 2019 12:02:28 -0500
parents
children
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
38
4e1b466935cd Uploaded
bimib
parents:
diff changeset
1 # -*- coding: utf-8 -*-
4e1b466935cd Uploaded
bimib
parents:
diff changeset
2 """
4e1b466935cd Uploaded
bimib
parents:
diff changeset
3 Created on Mon Jun 3 19:51:00 2019
4e1b466935cd Uploaded
bimib
parents:
diff changeset
4 @author: Narger
4e1b466935cd Uploaded
bimib
parents:
diff changeset
5 """
4e1b466935cd Uploaded
bimib
parents:
diff changeset
6
4e1b466935cd Uploaded
bimib
parents:
diff changeset
7 import sys
4e1b466935cd Uploaded
bimib
parents:
diff changeset
8 import argparse
4e1b466935cd Uploaded
bimib
parents:
diff changeset
9 import os
4e1b466935cd Uploaded
bimib
parents:
diff changeset
10 from sklearn.datasets import make_blobs
4e1b466935cd Uploaded
bimib
parents:
diff changeset
11 from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
4e1b466935cd Uploaded
bimib
parents:
diff changeset
12 from sklearn.metrics import silhouette_samples, silhouette_score, davies_bouldin_score, cluster
4e1b466935cd Uploaded
bimib
parents:
diff changeset
13 import matplotlib
4e1b466935cd Uploaded
bimib
parents:
diff changeset
14 matplotlib.use('agg')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
15 import matplotlib.pyplot as plt
4e1b466935cd Uploaded
bimib
parents:
diff changeset
16 import scipy.cluster.hierarchy as shc
4e1b466935cd Uploaded
bimib
parents:
diff changeset
17 import matplotlib.cm as cm
4e1b466935cd Uploaded
bimib
parents:
diff changeset
18 import numpy as np
4e1b466935cd Uploaded
bimib
parents:
diff changeset
19 import pandas as pd
4e1b466935cd Uploaded
bimib
parents:
diff changeset
20
4e1b466935cd Uploaded
bimib
parents:
diff changeset
21 ################################# process args ###############################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
22
4e1b466935cd Uploaded
bimib
parents:
diff changeset
23 def process_args(args):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
24 parser = argparse.ArgumentParser(usage = '%(prog)s [options]',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
25 description = 'process some value\'s' +
4e1b466935cd Uploaded
bimib
parents:
diff changeset
26 ' genes to create class.')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
27
4e1b466935cd Uploaded
bimib
parents:
diff changeset
28 parser.add_argument('-ol', '--out_log',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
29 help = "Output log")
4e1b466935cd Uploaded
bimib
parents:
diff changeset
30
4e1b466935cd Uploaded
bimib
parents:
diff changeset
31 parser.add_argument('-in', '--input',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
32 type = str,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
33 help = 'input dataset')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
34
4e1b466935cd Uploaded
bimib
parents:
diff changeset
35 parser.add_argument('-cy', '--cluster_type',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
36 type = str,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
37 choices = ['kmeans', 'dbscan', 'hierarchy'],
4e1b466935cd Uploaded
bimib
parents:
diff changeset
38 default = 'kmeans',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
39 help = 'choose clustering algorythm')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
40
4e1b466935cd Uploaded
bimib
parents:
diff changeset
41 parser.add_argument('-k1', '--k_min',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
42 type = int,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
43 default = 2,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
44 help = 'choose minimun cluster number to be generated')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
45
4e1b466935cd Uploaded
bimib
parents:
diff changeset
46 parser.add_argument('-k2', '--k_max',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
47 type = int,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
48 default = 7,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
49 help = 'choose maximum cluster number to be generated')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
50
4e1b466935cd Uploaded
bimib
parents:
diff changeset
51 parser.add_argument('-el', '--elbow',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
52 type = str,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
53 default = 'false',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
54 choices = ['true', 'false'],
4e1b466935cd Uploaded
bimib
parents:
diff changeset
55 help = 'choose if you want to generate an elbow plot for kmeans')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
56
4e1b466935cd Uploaded
bimib
parents:
diff changeset
57 parser.add_argument('-si', '--silhouette',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
58 type = str,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
59 default = 'false',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
60 choices = ['true', 'false'],
4e1b466935cd Uploaded
bimib
parents:
diff changeset
61 help = 'choose if you want silhouette plots')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
62
4e1b466935cd Uploaded
bimib
parents:
diff changeset
63 parser.add_argument('-td', '--tool_dir',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
64 type = str,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
65 required = True,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
66 help = 'your tool directory')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
67
4e1b466935cd Uploaded
bimib
parents:
diff changeset
68 parser.add_argument('-ms', '--min_samples',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
69 type = float,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
70 help = 'min samples for dbscan (optional)')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
71
4e1b466935cd Uploaded
bimib
parents:
diff changeset
72 parser.add_argument('-ep', '--eps',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
73 type = float,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
74 help = 'eps for dbscan (optional)')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
75
4e1b466935cd Uploaded
bimib
parents:
diff changeset
76 parser.add_argument('-bc', '--best_cluster',
4e1b466935cd Uploaded
bimib
parents:
diff changeset
77 type = str,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
78 help = 'output of best cluster tsv')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
79
4e1b466935cd Uploaded
bimib
parents:
diff changeset
80
4e1b466935cd Uploaded
bimib
parents:
diff changeset
81
4e1b466935cd Uploaded
bimib
parents:
diff changeset
82 args = parser.parse_args()
4e1b466935cd Uploaded
bimib
parents:
diff changeset
83 return args
4e1b466935cd Uploaded
bimib
parents:
diff changeset
84
4e1b466935cd Uploaded
bimib
parents:
diff changeset
85 ########################### warning ###########################################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
86
4e1b466935cd Uploaded
bimib
parents:
diff changeset
87 def warning(s):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
88 args = process_args(sys.argv)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
89 with open(args.out_log, 'a') as log:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
90 log.write(s + "\n\n")
4e1b466935cd Uploaded
bimib
parents:
diff changeset
91 print(s)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
92
4e1b466935cd Uploaded
bimib
parents:
diff changeset
93 ########################## read dataset ######################################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
94
4e1b466935cd Uploaded
bimib
parents:
diff changeset
95 def read_dataset(dataset):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
96 try:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
97 dataset = pd.read_csv(dataset, sep = '\t', header = 0)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
98 except pd.errors.EmptyDataError:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
99 sys.exit('Execution aborted: wrong format of dataset\n')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
100 if len(dataset.columns) < 2:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
101 sys.exit('Execution aborted: wrong format of dataset\n')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
102 return dataset
4e1b466935cd Uploaded
bimib
parents:
diff changeset
103
4e1b466935cd Uploaded
bimib
parents:
diff changeset
104 ############################ rewrite_input ###################################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
105
4e1b466935cd Uploaded
bimib
parents:
diff changeset
106 def rewrite_input(dataset):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
107 #Riscrivo il dataset come dizionario di liste,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
108 #non come dizionario di dizionari
4e1b466935cd Uploaded
bimib
parents:
diff changeset
109
4e1b466935cd Uploaded
bimib
parents:
diff changeset
110 dataset.pop('Reactions', None)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
111
4e1b466935cd Uploaded
bimib
parents:
diff changeset
112 for key, val in dataset.items():
4e1b466935cd Uploaded
bimib
parents:
diff changeset
113 l = []
4e1b466935cd Uploaded
bimib
parents:
diff changeset
114 for i in val:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
115 if i == 'None':
4e1b466935cd Uploaded
bimib
parents:
diff changeset
116 l.append(None)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
117 else:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
118 l.append(float(i))
4e1b466935cd Uploaded
bimib
parents:
diff changeset
119
4e1b466935cd Uploaded
bimib
parents:
diff changeset
120 dataset[key] = l
4e1b466935cd Uploaded
bimib
parents:
diff changeset
121
4e1b466935cd Uploaded
bimib
parents:
diff changeset
122 return dataset
4e1b466935cd Uploaded
bimib
parents:
diff changeset
123
4e1b466935cd Uploaded
bimib
parents:
diff changeset
124 ############################## write to csv ##################################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
125
4e1b466935cd Uploaded
bimib
parents:
diff changeset
126 def write_to_csv (dataset, labels, name):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
127 #labels = predict
4e1b466935cd Uploaded
bimib
parents:
diff changeset
128 predict = [x+1 for x in labels]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
129
4e1b466935cd Uploaded
bimib
parents:
diff changeset
130 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
131
4e1b466935cd Uploaded
bimib
parents:
diff changeset
132 dest = name
4e1b466935cd Uploaded
bimib
parents:
diff changeset
133 classe.to_csv(dest, sep = '\t', index = False,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
134 header = ['Patient_ID', 'Class'])
4e1b466935cd Uploaded
bimib
parents:
diff changeset
135
4e1b466935cd Uploaded
bimib
parents:
diff changeset
136 ########################### trova il massimo in lista ########################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
137 def max_index (lista):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
138 best = -1
4e1b466935cd Uploaded
bimib
parents:
diff changeset
139 best_index = 0
4e1b466935cd Uploaded
bimib
parents:
diff changeset
140 for i in range(len(lista)):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
141 if lista[i] > best:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
142 best = lista [i]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
143 best_index = i
4e1b466935cd Uploaded
bimib
parents:
diff changeset
144
4e1b466935cd Uploaded
bimib
parents:
diff changeset
145 return best_index
4e1b466935cd Uploaded
bimib
parents:
diff changeset
146
4e1b466935cd Uploaded
bimib
parents:
diff changeset
147 ################################ kmeans #####################################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
148
4e1b466935cd Uploaded
bimib
parents:
diff changeset
149 def kmeans (k_min, k_max, dataset, elbow, silhouette, best_cluster):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
150 if not os.path.exists('clustering'):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
151 os.makedirs('clustering')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
152
4e1b466935cd Uploaded
bimib
parents:
diff changeset
153
4e1b466935cd Uploaded
bimib
parents:
diff changeset
154 if elbow == 'true':
4e1b466935cd Uploaded
bimib
parents:
diff changeset
155 elbow = True
4e1b466935cd Uploaded
bimib
parents:
diff changeset
156 else:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
157 elbow = False
4e1b466935cd Uploaded
bimib
parents:
diff changeset
158
4e1b466935cd Uploaded
bimib
parents:
diff changeset
159 if silhouette == 'true':
4e1b466935cd Uploaded
bimib
parents:
diff changeset
160 silhouette = True
4e1b466935cd Uploaded
bimib
parents:
diff changeset
161 else:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
162 silhouette = False
4e1b466935cd Uploaded
bimib
parents:
diff changeset
163
4e1b466935cd Uploaded
bimib
parents:
diff changeset
164 range_n_clusters = [i for i in range(k_min, k_max+1)]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
165 distortions = []
4e1b466935cd Uploaded
bimib
parents:
diff changeset
166 scores = []
4e1b466935cd Uploaded
bimib
parents:
diff changeset
167 all_labels = []
4e1b466935cd Uploaded
bimib
parents:
diff changeset
168
4e1b466935cd Uploaded
bimib
parents:
diff changeset
169 clusterer = KMeans(n_clusters=1, random_state=10)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
170 distortions.append(clusterer.fit(dataset).inertia_)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
171
4e1b466935cd Uploaded
bimib
parents:
diff changeset
172
4e1b466935cd Uploaded
bimib
parents:
diff changeset
173 for n_clusters in range_n_clusters:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
174 clusterer = KMeans(n_clusters=n_clusters, random_state=10)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
175 cluster_labels = clusterer.fit_predict(dataset)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
176
4e1b466935cd Uploaded
bimib
parents:
diff changeset
177 all_labels.append(cluster_labels)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
178 if n_clusters == 1:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
179 silhouette_avg = 0
4e1b466935cd Uploaded
bimib
parents:
diff changeset
180 else:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
181 silhouette_avg = silhouette_score(dataset, cluster_labels)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
182 scores.append(silhouette_avg)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
183 distortions.append(clusterer.fit(dataset).inertia_)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
184
4e1b466935cd Uploaded
bimib
parents:
diff changeset
185 best = max_index(scores) + k_min
4e1b466935cd Uploaded
bimib
parents:
diff changeset
186
4e1b466935cd Uploaded
bimib
parents:
diff changeset
187 for i in range(len(all_labels)):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
188 prefix = ''
4e1b466935cd Uploaded
bimib
parents:
diff changeset
189 if (i + k_min == best):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
190 prefix = '_BEST'
4e1b466935cd Uploaded
bimib
parents:
diff changeset
191
4e1b466935cd Uploaded
bimib
parents:
diff changeset
192 write_to_csv(dataset, all_labels[i], 'clustering/kmeans_with_' + str(i + k_min) + prefix + '_clusters.tsv')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
193
4e1b466935cd Uploaded
bimib
parents:
diff changeset
194
4e1b466935cd Uploaded
bimib
parents:
diff changeset
195 if (prefix == '_BEST'):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
196 labels = all_labels[i]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
197 predict = [x+1 for x in labels]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
198 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
199 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
4e1b466935cd Uploaded
bimib
parents:
diff changeset
200
4e1b466935cd Uploaded
bimib
parents:
diff changeset
201
4e1b466935cd Uploaded
bimib
parents:
diff changeset
202
4e1b466935cd Uploaded
bimib
parents:
diff changeset
203
4e1b466935cd Uploaded
bimib
parents:
diff changeset
204 if silhouette:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
205 silihouette_draw(dataset, all_labels[i], i + k_min, 'clustering/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
206
4e1b466935cd Uploaded
bimib
parents:
diff changeset
207
4e1b466935cd Uploaded
bimib
parents:
diff changeset
208 if elbow:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
209 elbow_plot(distortions, k_min,k_max)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
210
4e1b466935cd Uploaded
bimib
parents:
diff changeset
211
4e1b466935cd Uploaded
bimib
parents:
diff changeset
212
4e1b466935cd Uploaded
bimib
parents:
diff changeset
213
4e1b466935cd Uploaded
bimib
parents:
diff changeset
214
4e1b466935cd Uploaded
bimib
parents:
diff changeset
215 ############################## elbow_plot ####################################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
216
4e1b466935cd Uploaded
bimib
parents:
diff changeset
217 def elbow_plot (distortions, k_min, k_max):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
218 plt.figure(0)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
219 x = list(range(k_min, k_max + 1))
4e1b466935cd Uploaded
bimib
parents:
diff changeset
220 x.insert(0, 1)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
221 plt.plot(x, distortions, marker = 'o')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
222 plt.xlabel('Number of clusters (k)')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
223 plt.ylabel('Distortion')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
224 s = 'clustering/elbow_plot.png'
4e1b466935cd Uploaded
bimib
parents:
diff changeset
225 fig = plt.gcf()
4e1b466935cd Uploaded
bimib
parents:
diff changeset
226 fig.set_size_inches(18.5, 10.5, forward = True)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
227 fig.savefig(s, dpi=100)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
228
4e1b466935cd Uploaded
bimib
parents:
diff changeset
229
4e1b466935cd Uploaded
bimib
parents:
diff changeset
230 ############################## silhouette plot ###############################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
231 def silihouette_draw(dataset, labels, n_clusters, path):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
232 if n_clusters == 1:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
233 return None
4e1b466935cd Uploaded
bimib
parents:
diff changeset
234
4e1b466935cd Uploaded
bimib
parents:
diff changeset
235 silhouette_avg = silhouette_score(dataset, labels)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
236 warning("For n_clusters = " + str(n_clusters) +
4e1b466935cd Uploaded
bimib
parents:
diff changeset
237 " The average silhouette_score is: " + str(silhouette_avg))
4e1b466935cd Uploaded
bimib
parents:
diff changeset
238
4e1b466935cd Uploaded
bimib
parents:
diff changeset
239 plt.close('all')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
240 # Create a subplot with 1 row and 2 columns
4e1b466935cd Uploaded
bimib
parents:
diff changeset
241 fig, (ax1) = plt.subplots(1, 1)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
242
4e1b466935cd Uploaded
bimib
parents:
diff changeset
243 fig.set_size_inches(18, 7)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
244
4e1b466935cd Uploaded
bimib
parents:
diff changeset
245 # The 1st subplot is the silhouette plot
4e1b466935cd Uploaded
bimib
parents:
diff changeset
246 # The silhouette coefficient can range from -1, 1 but in this example all
4e1b466935cd Uploaded
bimib
parents:
diff changeset
247 # lie within [-0.1, 1]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
248 ax1.set_xlim([-1, 1])
4e1b466935cd Uploaded
bimib
parents:
diff changeset
249 # The (n_clusters+1)*10 is for inserting blank space between silhouette
4e1b466935cd Uploaded
bimib
parents:
diff changeset
250 # plots of individual clusters, to demarcate them clearly.
4e1b466935cd Uploaded
bimib
parents:
diff changeset
251 ax1.set_ylim([0, len(dataset) + (n_clusters + 1) * 10])
4e1b466935cd Uploaded
bimib
parents:
diff changeset
252
4e1b466935cd Uploaded
bimib
parents:
diff changeset
253 # Compute the silhouette scores for each sample
4e1b466935cd Uploaded
bimib
parents:
diff changeset
254 sample_silhouette_values = silhouette_samples(dataset, labels)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
255
4e1b466935cd Uploaded
bimib
parents:
diff changeset
256 y_lower = 10
4e1b466935cd Uploaded
bimib
parents:
diff changeset
257 for i in range(n_clusters):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
258 # Aggregate the silhouette scores for samples belonging to
4e1b466935cd Uploaded
bimib
parents:
diff changeset
259 # cluster i, and sort them
4e1b466935cd Uploaded
bimib
parents:
diff changeset
260 ith_cluster_silhouette_values = \
4e1b466935cd Uploaded
bimib
parents:
diff changeset
261 sample_silhouette_values[labels == i]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
262
4e1b466935cd Uploaded
bimib
parents:
diff changeset
263 ith_cluster_silhouette_values.sort()
4e1b466935cd Uploaded
bimib
parents:
diff changeset
264
4e1b466935cd Uploaded
bimib
parents:
diff changeset
265 size_cluster_i = ith_cluster_silhouette_values.shape[0]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
266 y_upper = y_lower + size_cluster_i
4e1b466935cd Uploaded
bimib
parents:
diff changeset
267
4e1b466935cd Uploaded
bimib
parents:
diff changeset
268 color = cm.nipy_spectral(float(i) / n_clusters)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
269 ax1.fill_betweenx(np.arange(y_lower, y_upper),
4e1b466935cd Uploaded
bimib
parents:
diff changeset
270 0, ith_cluster_silhouette_values,
4e1b466935cd Uploaded
bimib
parents:
diff changeset
271 facecolor=color, edgecolor=color, alpha=0.7)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
272
4e1b466935cd Uploaded
bimib
parents:
diff changeset
273 # Label the silhouette plots with their cluster numbers at the middle
4e1b466935cd Uploaded
bimib
parents:
diff changeset
274 ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
4e1b466935cd Uploaded
bimib
parents:
diff changeset
275
4e1b466935cd Uploaded
bimib
parents:
diff changeset
276 # Compute the new y_lower for next plot
4e1b466935cd Uploaded
bimib
parents:
diff changeset
277 y_lower = y_upper + 10 # 10 for the 0 samples
4e1b466935cd Uploaded
bimib
parents:
diff changeset
278
4e1b466935cd Uploaded
bimib
parents:
diff changeset
279 ax1.set_title("The silhouette plot for the various clusters.")
4e1b466935cd Uploaded
bimib
parents:
diff changeset
280 ax1.set_xlabel("The silhouette coefficient values")
4e1b466935cd Uploaded
bimib
parents:
diff changeset
281 ax1.set_ylabel("Cluster label")
4e1b466935cd Uploaded
bimib
parents:
diff changeset
282
4e1b466935cd Uploaded
bimib
parents:
diff changeset
283 # The vertical line for average silhouette score of all the values
4e1b466935cd Uploaded
bimib
parents:
diff changeset
284 ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
4e1b466935cd Uploaded
bimib
parents:
diff changeset
285
4e1b466935cd Uploaded
bimib
parents:
diff changeset
286 ax1.set_yticks([]) # Clear the yaxis labels / ticks
4e1b466935cd Uploaded
bimib
parents:
diff changeset
287 ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
4e1b466935cd Uploaded
bimib
parents:
diff changeset
288
4e1b466935cd Uploaded
bimib
parents:
diff changeset
289
4e1b466935cd Uploaded
bimib
parents:
diff changeset
290 plt.suptitle(("Silhouette analysis for clustering on sample data "
4e1b466935cd Uploaded
bimib
parents:
diff changeset
291 "with n_clusters = " + str(n_clusters) + "\nAverage silhouette_score = " + str(silhouette_avg)), fontsize=12, fontweight='bold')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
292
4e1b466935cd Uploaded
bimib
parents:
diff changeset
293
4e1b466935cd Uploaded
bimib
parents:
diff changeset
294 plt.savefig(path, bbox_inches='tight')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
295
4e1b466935cd Uploaded
bimib
parents:
diff changeset
296 ######################## dbscan ##############################################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
297
4e1b466935cd Uploaded
bimib
parents:
diff changeset
298 def dbscan(dataset, eps, min_samples, best_cluster):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
299 if not os.path.exists('clustering'):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
300 os.makedirs('clustering')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
301
4e1b466935cd Uploaded
bimib
parents:
diff changeset
302 if eps is not None:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
303 clusterer = DBSCAN(eps = eps, min_samples = min_samples)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
304 else:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
305 clusterer = DBSCAN()
4e1b466935cd Uploaded
bimib
parents:
diff changeset
306
4e1b466935cd Uploaded
bimib
parents:
diff changeset
307 clustering = clusterer.fit(dataset)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
308
4e1b466935cd Uploaded
bimib
parents:
diff changeset
309 core_samples_mask = np.zeros_like(clustering.labels_, dtype=bool)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
310 core_samples_mask[clustering.core_sample_indices_] = True
4e1b466935cd Uploaded
bimib
parents:
diff changeset
311 labels = clustering.labels_
4e1b466935cd Uploaded
bimib
parents:
diff changeset
312
4e1b466935cd Uploaded
bimib
parents:
diff changeset
313 # Number of clusters in labels, ignoring noise if present.
4e1b466935cd Uploaded
bimib
parents:
diff changeset
314 n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
315
4e1b466935cd Uploaded
bimib
parents:
diff changeset
316
4e1b466935cd Uploaded
bimib
parents:
diff changeset
317 labels = labels
4e1b466935cd Uploaded
bimib
parents:
diff changeset
318 predict = [x+1 for x in labels]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
319 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
320 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
4e1b466935cd Uploaded
bimib
parents:
diff changeset
321
4e1b466935cd Uploaded
bimib
parents:
diff changeset
322
4e1b466935cd Uploaded
bimib
parents:
diff changeset
323 ########################## hierachical #######################################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
324
4e1b466935cd Uploaded
bimib
parents:
diff changeset
325 def hierachical_agglomerative(dataset, k_min, k_max, best_cluster, silhouette):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
326
4e1b466935cd Uploaded
bimib
parents:
diff changeset
327 if not os.path.exists('clustering'):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
328 os.makedirs('clustering')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
329
4e1b466935cd Uploaded
bimib
parents:
diff changeset
330 plt.figure(figsize=(10, 7))
4e1b466935cd Uploaded
bimib
parents:
diff changeset
331 plt.title("Classes Dendogram")
4e1b466935cd Uploaded
bimib
parents:
diff changeset
332 shc.dendrogram(shc.linkage(dataset, method='ward'), labels=dataset.index.values.tolist())
4e1b466935cd Uploaded
bimib
parents:
diff changeset
333 fig = plt.gcf()
4e1b466935cd Uploaded
bimib
parents:
diff changeset
334 fig.savefig('clustering/dendogram.png', dpi=200)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
335
4e1b466935cd Uploaded
bimib
parents:
diff changeset
336 range_n_clusters = [i for i in range(k_min, k_max+1)]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
337
4e1b466935cd Uploaded
bimib
parents:
diff changeset
338 scores = []
4e1b466935cd Uploaded
bimib
parents:
diff changeset
339 labels = []
4e1b466935cd Uploaded
bimib
parents:
diff changeset
340
4e1b466935cd Uploaded
bimib
parents:
diff changeset
341 for n_clusters in range_n_clusters:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
342 cluster = AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean', linkage='ward')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
343 cluster.fit_predict(dataset)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
344 cluster_labels = cluster.labels_
4e1b466935cd Uploaded
bimib
parents:
diff changeset
345 labels.append(cluster_labels)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
346 write_to_csv(dataset, cluster_labels, 'clustering/hierarchical_with_' + str(n_clusters) + '_clusters.tsv')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
347
4e1b466935cd Uploaded
bimib
parents:
diff changeset
348 best = max_index(scores) + k_min
4e1b466935cd Uploaded
bimib
parents:
diff changeset
349
4e1b466935cd Uploaded
bimib
parents:
diff changeset
350 for i in range(len(labels)):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
351 prefix = ''
4e1b466935cd Uploaded
bimib
parents:
diff changeset
352 if (i + k_min == best):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
353 prefix = '_BEST'
4e1b466935cd Uploaded
bimib
parents:
diff changeset
354 if silhouette == 'true':
4e1b466935cd Uploaded
bimib
parents:
diff changeset
355 silihouette_draw(dataset, labels[i], i + k_min, 'clustering/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
356
4e1b466935cd Uploaded
bimib
parents:
diff changeset
357 for i in range(len(labels)):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
358 if (i + k_min == best):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
359 labels = labels[i]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
360 predict = [x+1 for x in labels]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
361 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
362 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
4e1b466935cd Uploaded
bimib
parents:
diff changeset
363
4e1b466935cd Uploaded
bimib
parents:
diff changeset
364
4e1b466935cd Uploaded
bimib
parents:
diff changeset
365 ############################# main ###########################################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
366
4e1b466935cd Uploaded
bimib
parents:
diff changeset
367
4e1b466935cd Uploaded
bimib
parents:
diff changeset
368 def main():
4e1b466935cd Uploaded
bimib
parents:
diff changeset
369 if not os.path.exists('clustering'):
4e1b466935cd Uploaded
bimib
parents:
diff changeset
370 os.makedirs('clustering')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
371
4e1b466935cd Uploaded
bimib
parents:
diff changeset
372 args = process_args(sys.argv)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
373
4e1b466935cd Uploaded
bimib
parents:
diff changeset
374 #Data read
4e1b466935cd Uploaded
bimib
parents:
diff changeset
375
4e1b466935cd Uploaded
bimib
parents:
diff changeset
376 X = read_dataset(args.input)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
377 X = pd.DataFrame.to_dict(X, orient='list')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
378 X = rewrite_input(X)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
379 X = pd.DataFrame.from_dict(X, orient = 'index')
4e1b466935cd Uploaded
bimib
parents:
diff changeset
380
4e1b466935cd Uploaded
bimib
parents:
diff changeset
381 for i in X.columns:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
382 tmp = X[i][0]
4e1b466935cd Uploaded
bimib
parents:
diff changeset
383 if tmp == None:
4e1b466935cd Uploaded
bimib
parents:
diff changeset
384 X = X.drop(columns=[i])
4e1b466935cd Uploaded
bimib
parents:
diff changeset
385
4e1b466935cd Uploaded
bimib
parents:
diff changeset
386
4e1b466935cd Uploaded
bimib
parents:
diff changeset
387 if args.cluster_type == 'kmeans':
4e1b466935cd Uploaded
bimib
parents:
diff changeset
388 kmeans(args.k_min, args.k_max, X, args.elbow, args.silhouette, args.best_cluster)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
389
4e1b466935cd Uploaded
bimib
parents:
diff changeset
390 if args.cluster_type == 'dbscan':
4e1b466935cd Uploaded
bimib
parents:
diff changeset
391 dbscan(X, args.eps, args.min_samples, args.best_cluster)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
392
4e1b466935cd Uploaded
bimib
parents:
diff changeset
393 if args.cluster_type == 'hierarchy':
4e1b466935cd Uploaded
bimib
parents:
diff changeset
394 hierachical_agglomerative(X, args.k_min, args.k_max, args.best_cluster, args.silhouette)
4e1b466935cd Uploaded
bimib
parents:
diff changeset
395
4e1b466935cd Uploaded
bimib
parents:
diff changeset
396 ##############################################################################
4e1b466935cd Uploaded
bimib
parents:
diff changeset
397
4e1b466935cd Uploaded
bimib
parents:
diff changeset
398 if __name__ == "__main__":
4e1b466935cd Uploaded
bimib
parents:
diff changeset
399 main()