annotate Marea/marea_cluster.py @ 16:c71ac0bb12de draft

Uploaded
author bimib
date Tue, 01 Oct 2019 06:05:13 -0400
parents 1a0c8c2780f2
children a8825e66c3a0
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
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
5 @author: Narger
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
6 """
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
7
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
8 import sys
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
9 import argparse
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
10 import os
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
11 from sklearn.datasets import make_blobs
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
12 from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
13 from sklearn.metrics import silhouette_samples, silhouette_score, davies_bouldin_score, cluster
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
14 import matplotlib.pyplot as plt
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
15 import scipy.cluster.hierarchy as shc
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
16 import matplotlib.cm as cm
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
17 import numpy as np
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
18 import pandas as pd
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
19
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
20 ################################# process args ###############################
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
21
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
22 def process_args(args):
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
23 parser = argparse.ArgumentParser(usage = '%(prog)s [options]',
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
24 description = 'process some value\'s' +
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
25 ' genes to create class.')
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
26
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
27 parser.add_argument('-ol', '--out_log',
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
28 help = "Output log")
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
29
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
30 parser.add_argument('-in', '--input',
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
31 type = str,
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
32 help = 'input dataset')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
33
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
34 parser.add_argument('-cy', '--cluster_type',
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
35 type = str,
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
36 choices = ['kmeans', 'meanshift', 'dbscan', 'hierarchy'],
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
37 default = 'kmeans',
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
38 help = 'choose clustering algorythm')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
39
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
40 parser.add_argument('-k1', '--k_min',
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
41 type = int,
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
42 default = 2,
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
43 help = 'choose minimun cluster number to be generated')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
44
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
45 parser.add_argument('-k2', '--k_max',
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
46 type = int,
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
47 default = 7,
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
48 help = 'choose maximum cluster number to be generated')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
49
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
50 parser.add_argument('-el', '--elbow',
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
51 type = str,
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
52 default = 'false',
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
53 choices = ['true', 'false'],
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
54 help = 'choose if you want to generate an elbow plot for kmeans')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
55
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
56 parser.add_argument('-si', '--silhouette',
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
57 type = str,
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
58 default = 'false',
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
59 choices = ['true', 'false'],
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
60 help = 'choose if you want silhouette plots')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
61
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
62 parser.add_argument('-db', '--davies',
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
63 type = str,
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
64 default = 'false',
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
65 choices = ['true', 'false'],
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
66 help = 'choose if you want davies bouldin scores')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
67
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
68 parser.add_argument('-td', '--tool_dir',
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
69 type = str,
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
70 required = True,
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
71 help = 'your tool directory')
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
72
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
73 parser.add_argument('-ms', '--min_samples',
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
74 type = int,
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
75 help = 'min samples for dbscan (optional)')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
76
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
77 parser.add_argument('-ep', '--eps',
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
78 type = int,
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
79 help = 'eps for dbscan (optional)')
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
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
110 for key, val in dataset.items():
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
111 l = []
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
112 for i in val:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
113 if i == 'None':
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
114 l.append(None)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
115 else:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
116 l.append(float(i))
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
117
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
118 dataset[key] = l
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
119
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
120 return dataset
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
121
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
122 ############################## write to csv ##################################
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
123
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
124 def write_to_csv (dataset, labels, name):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
125 list_labels = labels
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
126 list_values = dataset
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
127
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
128 list_values = list_values.tolist()
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
129 d = {'Label' : list_labels, 'Value' : list_values}
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
130
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
131 df = pd.DataFrame(d, columns=['Value','Label'])
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
132
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
133 dest = name + '.tsv'
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
134 df.to_csv(dest, sep = '\t', index = False,
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
135 header = ['Value', 'Label'])
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
136
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
137 ########################### trova il massimo in lista ########################
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
138 def max_index (lista):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
139 best = -1
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
140 best_index = 0
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
141 for i in range(len(lista)):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
142 if lista[i] > best:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
143 best = lista [i]
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
144 best_index = i
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
145
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
146 return best_index
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
147
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
148 ################################ kmeans #####################################
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
149
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
150 def kmeans (k_min, k_max, dataset, elbow, silhouette, davies):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
151 if not os.path.exists('clustering/kmeans_output'):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
152 os.makedirs('clustering/kmeans_output')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
153
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
154
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
155 if elbow == 'true':
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
156 elbow = True
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
157 else:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
158 elbow = False
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
159
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
160 if silhouette == 'true':
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
161 silhouette = True
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
162 else:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
163 silhouette = False
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
164
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
165 if davies == 'true':
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
166 davies = True
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
167 else:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
168 davies = False
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
169
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
170
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
171 range_n_clusters = [i for i in range(k_min, k_max+1)]
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
172 distortions = []
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
173 scores = []
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
174 all_labels = []
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
175
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
176 for n_clusters in range_n_clusters:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
177 clusterer = KMeans(n_clusters=n_clusters, random_state=10)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
178 cluster_labels = clusterer.fit_predict(dataset)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
179
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
180 all_labels.append(cluster_labels)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
181 silhouette_avg = silhouette_score(dataset, cluster_labels)
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
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
192 write_to_csv(dataset, all_labels[i], 'clustering/kmeans_output/kmeans_with_' + str(i + k_min) + prefix + '_clusters.tsv')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
193
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
194 if davies:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
195 with np.errstate(divide='ignore', invalid='ignore'):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
196 davies_bouldin = davies_bouldin_score(dataset, all_labels[i])
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
197 warning("\nFor n_clusters = " + str(i + k_min) +
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
198 " The average davies bouldin score is: " + str(davies_bouldin))
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
199
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
200
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
201 if silhouette:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
202 silihouette_draw(dataset, all_labels[i], i + k_min, 'clustering/kmeans_output/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
203
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
204
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
205 if elbow:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
206 elbow_plot(distortions, k_min,k_max)
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
207
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
208
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
209
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
210
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
211
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
212 ############################## elbow_plot ####################################
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
213
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
214 def elbow_plot (distortions, k_min, k_max):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
215 plt.figure(0)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
216 plt.plot(range(k_min, k_max+1), distortions, marker = 'o')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
217 plt.xlabel('Number of cluster')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
218 plt.ylabel('Distortion')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
219 s = 'clustering/kmeans_output/elbow_plot.png'
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
220 fig = plt.gcf()
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
221 fig.set_size_inches(18.5, 10.5, forward = True)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
222 fig.savefig(s, dpi=100)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
223
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
224
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
225 ############################## silhouette plot ###############################
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
226 def silihouette_draw(dataset, labels, n_clusters, path):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
227 silhouette_avg = silhouette_score(dataset, labels)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
228 warning("For n_clusters = " + str(n_clusters) +
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
229 " The average silhouette_score is: " + str(silhouette_avg))
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
230
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
231 plt.close('all')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
232 # Create a subplot with 1 row and 2 columns
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
233 fig, (ax1) = plt.subplots(1, 1)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
234
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
235 fig.set_size_inches(18, 7)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
236
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
237 # The 1st subplot is the silhouette plot
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
238 # The silhouette coefficient can range from -1, 1 but in this example all
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
239 # lie within [-0.1, 1]
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
240 ax1.set_xlim([-1, 1])
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
241 # The (n_clusters+1)*10 is for inserting blank space between silhouette
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
242 # plots of individual clusters, to demarcate them clearly.
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
243 ax1.set_ylim([0, len(dataset) + (n_clusters + 1) * 10])
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
244
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
245 # Compute the silhouette scores for each sample
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
246 sample_silhouette_values = silhouette_samples(dataset, labels)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
247
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
248 y_lower = 10
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
249 for i in range(n_clusters):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
250 # Aggregate the silhouette scores for samples belonging to
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
251 # cluster i, and sort them
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
252 ith_cluster_silhouette_values = \
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
253 sample_silhouette_values[labels == i]
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
254
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
255 ith_cluster_silhouette_values.sort()
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
256
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
257 size_cluster_i = ith_cluster_silhouette_values.shape[0]
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
258 y_upper = y_lower + size_cluster_i
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
259
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
260 color = cm.nipy_spectral(float(i) / n_clusters)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
261 ax1.fill_betweenx(np.arange(y_lower, y_upper),
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
262 0, ith_cluster_silhouette_values,
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
263 facecolor=color, edgecolor=color, alpha=0.7)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
264
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
265 # Label the silhouette plots with their cluster numbers at the middle
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
266 ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
267
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
268 # Compute the new y_lower for next plot
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
269 y_lower = y_upper + 10 # 10 for the 0 samples
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
270
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
271 ax1.set_title("The silhouette plot for the various clusters.")
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
272 ax1.set_xlabel("The silhouette coefficient values")
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
273 ax1.set_ylabel("Cluster label")
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
274
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
275 # The vertical line for average silhouette score of all the values
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
276 ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
277
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
278 ax1.set_yticks([]) # Clear the yaxis labels / ticks
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
279 ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
280
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
281
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
282 plt.suptitle(("Silhouette analysis for clustering on sample data "
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
283 "with n_clusters = " + str(n_clusters) + "\nAverage silhouette_score = " + str(silhouette_avg)), fontsize=12, fontweight='bold')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
284
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
285
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
286 plt.savefig(path, bbox_inches='tight')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
287
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
288 ######################## dbscan ##############################################
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
289
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
290 def dbscan(dataset, eps, min_samples):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
291 if not os.path.exists('clustering/dbscan_output'):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
292 os.makedirs('clustering/dbscan_output')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
293
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
294 if eps is not None:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
295 clusterer = DBSCAN(eps = eps, min_samples = min_samples)
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
296 else:
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
297 clusterer = DBSCAN()
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
298
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
299 clustering = clusterer.fit(dataset)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
300
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
301 core_samples_mask = np.zeros_like(clustering.labels_, dtype=bool)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
302 core_samples_mask[clustering.core_sample_indices_] = True
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
303 labels = clustering.labels_
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
304
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
305 # Number of clusters in labels, ignoring noise if present.
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
306 n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
307
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
308 silhouette_avg = silhouette_score(dataset, labels)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
309 warning("For n_clusters =" + str(n_clusters_) +
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
310 "The average silhouette_score is :" + str(silhouette_avg))
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
311
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
312 ##TODO: PLOT SU DBSCAN (no centers) e HIERARCHICAL
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
313
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
314 # Black removed and is used for noise instead.
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
315 unique_labels = set(labels)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
316 colors = [plt.cm.Spectral(each)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
317 for each in np.linspace(0, 1, len(unique_labels))]
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
318 for k, col in zip(unique_labels, colors):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
319 if k == -1:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
320 # Black used for noise.
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
321 col = [0, 0, 0, 1]
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
322
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
323 class_member_mask = (labels == k)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
324
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
325 xy = dataset[class_member_mask & core_samples_mask]
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
326 plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
327 markeredgecolor='k', markersize=14)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
328
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
329 xy = dataset[class_member_mask & ~core_samples_mask]
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
330 plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
331 markeredgecolor='k', markersize=6)
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
332
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
333 plt.title('Estimated number of clusters: %d' % n_clusters_)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
334 s = 'clustering/dbscan_output/dbscan_plot.png'
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
335 fig = plt.gcf()
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
336 fig.set_size_inches(18.5, 10.5, forward = True)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
337 fig.savefig(s, dpi=100)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
338
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
339
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
340 write_to_csv(dataset, labels, 'clustering/dbscan_output/dbscan_results.tsv')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
341
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
342 ########################## hierachical #######################################
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
343
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
344 def hierachical_agglomerative(dataset, k_min, k_max):
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
345
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
346 if not os.path.exists('clustering/agglomerative_output'):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
347 os.makedirs('clustering/agglomerative_output')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
348
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
349 plt.figure(figsize=(10, 7))
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
350 plt.title("Customer Dendograms")
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
351 shc.dendrogram(shc.linkage(dataset, method='ward'))
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
352 fig = plt.gcf()
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
353 fig.savefig('clustering/agglomerative_output/dendogram.png', dpi=200)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
354
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
355 range_n_clusters = [i for i in range(k_min, k_max+1)]
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
356
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
357 for n_clusters in range_n_clusters:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
358
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
359 cluster = AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean', linkage='ward')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
360 cluster.fit_predict(dataset)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
361 cluster_labels = cluster.labels_
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
362
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
363 silhouette_avg = silhouette_score(dataset, cluster_labels)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
364 warning("For n_clusters =", n_clusters,
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
365 "The average silhouette_score is :", silhouette_avg)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
366
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
367 plt.clf()
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
368 plt.figure(figsize=(10, 7))
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
369 plt.title("Agglomerative Hierarchical Clustering\nwith " + str(n_clusters) + " clusters and " + str(silhouette_avg) + " silhouette score")
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
370 plt.scatter(dataset[:,0], dataset[:,1], c = cluster_labels, cmap='rainbow')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
371 s = 'clustering/agglomerative_output/hierachical_' + str(n_clusters) + '_clusters.png'
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
372 fig = plt.gcf()
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
373 fig.set_size_inches(10, 7, forward = True)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
374 fig.savefig(s, dpi=200)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
375
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
376 write_to_csv(dataset, cluster_labels, 'clustering/agglomerative_output/agglomerative_hierarchical_with_' + str(n_clusters) + '_clusters.tsv')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
377
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
378
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
379
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
380
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
381 ############################# main ###########################################
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
382
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
383
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
384 def main():
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
385 if not os.path.exists('clustering'):
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
386 os.makedirs('clustering')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
387
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
388 args = process_args(sys.argv)
16
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
389
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
390 #Data read
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
391
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
392 X = read_dataset(args.input)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
393 X = pd.DataFrame.to_dict(X, orient='list')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
394 X = rewrite_input(X)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
395 X = pd.DataFrame.from_dict(X, orient = 'index')
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
396
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
397 for i in X.columns:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
398 tmp = X[i][0]
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
399 if tmp == None:
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
400 X = X.drop(columns=[i])
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
401
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
402 X = pd.DataFrame.to_numpy(X)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
403
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
404
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
405 if args.cluster_type == 'kmeans':
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
406 kmeans(args.k_min, args.k_max, X, args.elbow, args.silhouette, args.davies)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
407
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
408 if args.cluster_type == 'dbscan':
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
409 dbscan(X, args.eps, args.min_samples)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
410
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
411 if args.cluster_type == 'hierarchy':
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
412 hierachical_agglomerative(X, args.k_min, args.k_max)
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
413
c71ac0bb12de Uploaded
bimib
parents: 14
diff changeset
414 ##############################################################################
0
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
415
23ac9cf12788 Uploaded
bimib
parents:
diff changeset
416 if __name__ == "__main__":
6
5721182715a7 xml requirement
bimib
parents: 0
diff changeset
417 main()