annotate marea-1.0.1/marea_cluster.py @ 15:d0e7f14b773f draft

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