annotate Marea/marea_cluster.py @ 68:aa09186cbc9f draft

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