annotate COBRAxy/marea_cluster.py @ 93:7e703e546998 draft

Uploaded
author luca_milaz
date Sun, 13 Oct 2024 11:41:34 +0000
parents 41f35c2f0c7b
children 3fca9b568faf
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
4
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
1 # -*- coding: utf-8 -*-
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
2 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
3 Created on Mon Jun 3 19:51:00 2019
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
4 @author: Narger
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
5 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
6
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
7 import sys
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
8 import argparse
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
9 import os
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
10 import numpy as np
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
11 import pandas as pd
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
12 from sklearn.datasets import make_blobs
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
13 from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
14 from sklearn.metrics import silhouette_samples, silhouette_score, cluster
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
15 import matplotlib
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
16 matplotlib.use('agg')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
17 import matplotlib.pyplot as plt
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
18 import scipy.cluster.hierarchy as shc
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
19 import matplotlib.cm as cm
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
20 from typing import Optional, Dict, List
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
21
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
22 ################################# process args ###############################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
23 def process_args(args :List[str]) -> argparse.Namespace:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
24 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
25 Processes command-line arguments.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
26
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
27 Args:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
28 args (list): List of command-line arguments.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
29
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
30 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
31 Namespace: An object containing parsed arguments.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
32 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
33 parser = argparse.ArgumentParser(usage = '%(prog)s [options]',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
34 description = 'process some value\'s' +
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
35 ' genes to create class.')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
36
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
37 parser.add_argument('-ol', '--out_log',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
38 help = "Output log")
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
39
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
40 parser.add_argument('-in', '--input',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
41 type = str,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
42 help = 'input dataset')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
43
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
44 parser.add_argument('-cy', '--cluster_type',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
45 type = str,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
46 choices = ['kmeans', 'dbscan', 'hierarchy'],
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
47 default = 'kmeans',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
48 help = 'choose clustering algorythm')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
49
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
50 parser.add_argument('-k1', '--k_min',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
51 type = int,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
52 default = 2,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
53 help = 'choose minimun cluster number to be generated')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
54
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
55 parser.add_argument('-k2', '--k_max',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
56 type = int,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
57 default = 7,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
58 help = 'choose maximum cluster number to be generated')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
59
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
60 parser.add_argument('-el', '--elbow',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
61 type = str,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
62 default = 'false',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
63 choices = ['true', 'false'],
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
64 help = 'choose if you want to generate an elbow plot for kmeans')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
65
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
66 parser.add_argument('-si', '--silhouette',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
67 type = str,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
68 default = 'false',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
69 choices = ['true', 'false'],
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
70 help = 'choose if you want silhouette plots')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
71
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
72 parser.add_argument('-td', '--tool_dir',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
73 type = str,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
74 required = True,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
75 help = 'your tool directory')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
76
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
77 parser.add_argument('-ms', '--min_samples',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
78 type = float,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
79 help = 'min samples for dbscan (optional)')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
80
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
81 parser.add_argument('-ep', '--eps',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
82 type = float,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
83 help = 'eps for dbscan (optional)')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
84
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
85 parser.add_argument('-bc', '--best_cluster',
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
86 type = str,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
87 help = 'output of best cluster tsv')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
88
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
89
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
90
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
91 args = parser.parse_args()
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
92 return args
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
93
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
94 ########################### warning ###########################################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
95 def warning(s :str) -> None:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
96 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
97 Log a warning message to an output log file and print it to the console.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
98
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
99 Args:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
100 s (str): The warning message to be logged and printed.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
101
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
102 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
103 None
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
104 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
105 args = process_args(sys.argv)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
106 with open(args.out_log, 'a') as log:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
107 log.write(s + "\n\n")
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
108 print(s)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
109
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
110 ########################## read dataset ######################################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
111 def read_dataset(dataset :str) -> pd.DataFrame:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
112 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
113 Read dataset from a CSV file and return it as a Pandas DataFrame.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
114
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
115 Args:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
116 dataset (str): the path to the dataset to convert into a DataFrame
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
117
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
118 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
119 pandas.DataFrame: The dataset loaded as a Pandas DataFrame.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
120
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
121 Raises:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
122 pandas.errors.EmptyDataError: If the dataset file is empty.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
123 sys.exit: If the dataset file has the wrong format (e.g., fewer than 2 columns)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
124 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
125 try:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
126 dataset = pd.read_csv(dataset, sep = '\t', header = 0)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
127 except pd.errors.EmptyDataError:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
128 sys.exit('Execution aborted: wrong format of dataset\n')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
129 if len(dataset.columns) < 2:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
130 sys.exit('Execution aborted: wrong format of dataset\n')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
131 return dataset
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
132
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
133 ############################ rewrite_input ###################################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
134 def rewrite_input(dataset :pd.DataFrame) -> Dict[str, List[Optional[float]]]:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
135 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
136 Rewrite the dataset as a dictionary of lists instead of as a dictionary of dictionaries.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
137
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
138 Args:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
139 dataset (pandas.DataFrame): The dataset to be rewritten.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
140
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
141 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
142 dict: The rewritten dataset as a dictionary of lists.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
143 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
144 #Riscrivo il dataset come dizionario di liste,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
145 #non come dizionario di dizionari
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
146
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
147 dataset.pop('Reactions', None)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
148
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
149 for key, val in dataset.items():
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
150 l = []
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
151 for i in val:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
152 if i == 'None':
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
153 l.append(None)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
154 else:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
155 l.append(float(i))
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
156
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
157 dataset[key] = l
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
158
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
159 return dataset
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
160
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
161 ############################## write to csv ##################################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
162 def write_to_csv (dataset :pd.DataFrame, labels :List[str], name :str) -> None:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
163 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
164 Write dataset and predicted labels to a CSV file.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
165
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
166 Args:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
167 dataset (pandas.DataFrame): The dataset to be written.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
168 labels (list): The predicted labels for each data point.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
169 name (str): The name of the output CSV file.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
170
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
171 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
172 None
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
173 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
174 #labels = predict
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
175 predict = [x+1 for x in labels]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
176
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
177 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
178
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
179 dest = name
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
180 classe.to_csv(dest, sep = '\t', index = False,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
181 header = ['Patient_ID', 'Class'])
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
182
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
183 ########################### trova il massimo in lista ########################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
184 def max_index (lista :List[int]) -> int:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
185 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
186 Find the index of the maximum value in a list.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
187
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
188 Args:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
189 lista (list): The list in which we search for the index of the maximum value.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
190
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
191 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
192 int: The index of the maximum value in the list.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
193 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
194 best = -1
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
195 best_index = 0
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
196 for i in range(len(lista)):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
197 if lista[i] > best:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
198 best = lista [i]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
199 best_index = i
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
200
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
201 return best_index
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
202
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
203 ################################ kmeans #####################################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
204 def kmeans (k_min: int, k_max: int, dataset: pd.DataFrame, elbow: str, silhouette: str, best_cluster: str) -> None:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
205 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
206 Perform k-means clustering on the given dataset, which is an algorithm used to partition a dataset into groups (clusters) based on their characteristics.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
207 The goal is to divide the data into homogeneous groups, where the elements within each group are similar to each other and different from the elements in other groups.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
208
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
209 Args:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
210 k_min (int): The minimum number of clusters to consider.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
211 k_max (int): The maximum number of clusters to consider.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
212 dataset (pandas.DataFrame): The dataset to perform clustering on.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
213 elbow (str): Whether to generate an elbow plot for kmeans ('true' or 'false').
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
214 silhouette (str): Whether to generate silhouette plots ('true' or 'false').
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
215 best_cluster (str): The file path to save the output of the best cluster.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
216
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
217 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
218 None
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
219 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
220 if not os.path.exists('clustering'):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
221 os.makedirs('clustering')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
222
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
223
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
224 if elbow == 'true':
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
225 elbow = True
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
226 else:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
227 elbow = False
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
228
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
229 if silhouette == 'true':
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
230 silhouette = True
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
231 else:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
232 silhouette = False
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
233
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
234 range_n_clusters = [i for i in range(k_min, k_max+1)]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
235 distortions = []
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
236 scores = []
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
237 all_labels = []
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
238
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
239 clusterer = KMeans(n_clusters=1, random_state=10)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
240 distortions.append(clusterer.fit(dataset).inertia_)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
241
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
242
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
243 for n_clusters in range_n_clusters:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
244 clusterer = KMeans(n_clusters=n_clusters, random_state=10)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
245 cluster_labels = clusterer.fit_predict(dataset)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
246
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
247 all_labels.append(cluster_labels)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
248 if n_clusters == 1:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
249 silhouette_avg = 0
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
250 else:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
251 silhouette_avg = silhouette_score(dataset, cluster_labels)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
252 scores.append(silhouette_avg)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
253 distortions.append(clusterer.fit(dataset).inertia_)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
254
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
255 best = max_index(scores) + k_min
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
256
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
257 for i in range(len(all_labels)):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
258 prefix = ''
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
259 if (i + k_min == best):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
260 prefix = '_BEST'
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
261
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
262 write_to_csv(dataset, all_labels[i], 'clustering/kmeans_with_' + str(i + k_min) + prefix + '_clusters.tsv')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
263
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
264
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
265 if (prefix == '_BEST'):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
266 labels = all_labels[i]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
267 predict = [x+1 for x in labels]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
268 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
269 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
270
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
271
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
272
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
273
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
274 if silhouette:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
275 silhouette_draw(dataset, all_labels[i], i + k_min, 'clustering/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
276
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
277
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
278 if elbow:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
279 elbow_plot(distortions, k_min,k_max)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
280
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
281
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
282
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
283
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
284
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
285 ############################## elbow_plot ####################################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
286 def elbow_plot (distortions: List[float], k_min: int, k_max: int) -> None:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
287 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
288 Generate an elbow plot to visualize the distortion for different numbers of clusters.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
289 The elbow plot is a graphical tool used in clustering analysis to help identifying the appropriate number of clusters by looking for the point where the rate of decrease
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
290 in distortion sharply decreases, indicating the optimal balance between model complexity and clustering quality.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
291
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
292 Args:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
293 distortions (list): List of distortion values for different numbers of clusters.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
294 k_min (int): The minimum number of clusters considered.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
295 k_max (int): The maximum number of clusters considered.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
296
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
297 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
298 None
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
299 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
300 plt.figure(0)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
301 x = list(range(k_min, k_max + 1))
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
302 x.insert(0, 1)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
303 plt.plot(x, distortions, marker = 'o')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
304 plt.xlabel('Number of clusters (k)')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
305 plt.ylabel('Distortion')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
306 s = 'clustering/elbow_plot.png'
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
307 fig = plt.gcf()
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
308 fig.set_size_inches(18.5, 10.5, forward = True)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
309 fig.savefig(s, dpi=100)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
310
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
311
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
312 ############################## silhouette plot ###############################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
313 def silhouette_draw(dataset: pd.DataFrame, labels: List[str], n_clusters: int, path:str) -> None:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
314 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
315 Generate a silhouette plot for the clustering results.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
316 The silhouette coefficient is a measure used to evaluate the quality of clusters obtained from a clustering algorithmand it quantifies how similar an object is to its own cluster compared to other clusters.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
317 The silhouette coefficient ranges from -1 to 1, where:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
318 - A value close to +1 indicates that the object is well matched to its own cluster and poorly matched to neighboring clusters. This implies that the object is in a dense, well-separated cluster.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
319 - A value close to 0 indicates that the object is close to the decision boundary between two neighboring clusters.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
320 - A value close to -1 indicates that the object may have been assigned to the wrong cluster.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
321
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
322 Args:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
323 dataset (pandas.DataFrame): The dataset used for clustering.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
324 labels (list): The cluster labels assigned to each data point.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
325 n_clusters (int): The number of clusters.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
326 path (str): The path to save the silhouette plot image.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
327
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
328 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
329 None
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
330 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
331 if n_clusters == 1:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
332 return None
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
333
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
334 silhouette_avg = silhouette_score(dataset, labels)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
335 warning("For n_clusters = " + str(n_clusters) +
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
336 " The average silhouette_score is: " + str(silhouette_avg))
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
337
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
338 plt.close('all')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
339 # Create a subplot with 1 row and 2 columns
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
340 fig, (ax1) = plt.subplots(1, 1)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
341
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
342 fig.set_size_inches(18, 7)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
343
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
344 # The 1st subplot is the silhouette plot
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
345 # The silhouette coefficient can range from -1, 1 but in this example all
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
346 # lie within [-0.1, 1]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
347 ax1.set_xlim([-1, 1])
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
348 # The (n_clusters+1)*10 is for inserting blank space between silhouette
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
349 # plots of individual clusters, to demarcate them clearly.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
350 ax1.set_ylim([0, len(dataset) + (n_clusters + 1) * 10])
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
351
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
352 # Compute the silhouette scores for each sample
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
353 sample_silhouette_values = silhouette_samples(dataset, labels)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
354
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
355 y_lower = 10
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
356 for i in range(n_clusters):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
357 # Aggregate the silhouette scores for samples belonging to
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
358 # cluster i, and sort them
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
359 ith_cluster_silhouette_values = \
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
360 sample_silhouette_values[labels == i]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
361
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
362 ith_cluster_silhouette_values.sort()
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
363
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
364 size_cluster_i = ith_cluster_silhouette_values.shape[0]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
365 y_upper = y_lower + size_cluster_i
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
366
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
367 color = cm.nipy_spectral(float(i) / n_clusters)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
368 ax1.fill_betweenx(np.arange(y_lower, y_upper),
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
369 0, ith_cluster_silhouette_values,
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
370 facecolor=color, edgecolor=color, alpha=0.7)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
371
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
372 # Label the silhouette plots with their cluster numbers at the middle
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
373 ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
374
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
375 # Compute the new y_lower for next plot
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
376 y_lower = y_upper + 10 # 10 for the 0 samples
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
377
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
378 ax1.set_title("The silhouette plot for the various clusters.")
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
379 ax1.set_xlabel("The silhouette coefficient values")
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
380 ax1.set_ylabel("Cluster label")
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
381
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
382 # The vertical line for average silhouette score of all the values
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
383 ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
384
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
385 ax1.set_yticks([]) # Clear the yaxis labels / ticks
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
386 ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
387
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
388
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
389 plt.suptitle(("Silhouette analysis for clustering on sample data "
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
390 "with n_clusters = " + str(n_clusters) + "\nAverage silhouette_score = " + str(silhouette_avg)), fontsize=12, fontweight='bold')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
391
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
392
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
393 plt.savefig(path, bbox_inches='tight')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
394
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
395 ######################## dbscan ##############################################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
396 def dbscan(dataset: pd.DataFrame, eps: float, min_samples: float, best_cluster: str) -> None:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
397 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
398 Perform DBSCAN clustering on the given dataset, which is a clustering algorithm that groups together closely packed points based on the notion of density.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
399
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
400 Args:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
401 dataset (pandas.DataFrame): The dataset to be clustered.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
402 eps (float): The maximum distance between two samples for one to be considered as in the neighborhood of the other.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
403 min_samples (float): The number of samples in a neighborhood for a point to be considered as a core point.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
404 best_cluster (str): The file path to save the output of the best cluster.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
405
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
406 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
407 None
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
408 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
409 if not os.path.exists('clustering'):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
410 os.makedirs('clustering')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
411
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
412 if eps is not None:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
413 clusterer = DBSCAN(eps = eps, min_samples = min_samples)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
414 else:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
415 clusterer = DBSCAN()
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
416
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
417 clustering = clusterer.fit(dataset)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
418
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
419 core_samples_mask = np.zeros_like(clustering.labels_, dtype=bool)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
420 core_samples_mask[clustering.core_sample_indices_] = True
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
421 labels = clustering.labels_
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
422
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
423 # Number of clusters in labels, ignoring noise if present.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
424 n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
425
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
426
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
427 labels = labels
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
428 predict = [x+1 for x in labels]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
429 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
430 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
431
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
432
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
433 ########################## hierachical #######################################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
434 def hierachical_agglomerative(dataset: pd.DataFrame, k_min: int, k_max: int, best_cluster: str, silhouette: str) -> None:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
435 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
436 Perform hierarchical agglomerative clustering on the given dataset.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
437
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
438 Args:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
439 dataset (pandas.DataFrame): The dataset to be clustered.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
440 k_min (int): The minimum number of clusters to consider.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
441 k_max (int): The maximum number of clusters to consider.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
442 best_cluster (str): The file path to save the output of the best cluster.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
443 silhouette (str): Whether to generate silhouette plots ('true' or 'false').
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
444
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
445 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
446 None
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
447 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
448 if not os.path.exists('clustering'):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
449 os.makedirs('clustering')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
450
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
451 plt.figure(figsize=(10, 7))
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
452 plt.title("Customer Dendograms")
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
453 shc.dendrogram(shc.linkage(dataset, method='ward'), labels=dataset.index.values.tolist())
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
454 fig = plt.gcf()
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
455 fig.savefig('clustering/dendogram.png', dpi=200)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
456
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
457 range_n_clusters = [i for i in range(k_min, k_max+1)]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
458
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
459 scores = []
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
460 labels = []
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
461
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
462 n_classi = dataset.shape[0]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
463
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
464 for n_clusters in range_n_clusters:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
465 cluster = AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean', linkage='ward')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
466 cluster.fit_predict(dataset)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
467 cluster_labels = cluster.labels_
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
468 labels.append(cluster_labels)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
469 write_to_csv(dataset, cluster_labels, 'clustering/hierarchical_with_' + str(n_clusters) + '_clusters.tsv')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
470
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
471 best = max_index(scores) + k_min
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
472
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
473 for i in range(len(labels)):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
474 prefix = ''
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
475 if (i + k_min == best):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
476 prefix = '_BEST'
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
477 if silhouette == 'true':
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
478 silhouette_draw(dataset, labels[i], i + k_min, 'clustering/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
479
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
480 for i in range(len(labels)):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
481 if (i + k_min == best):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
482 labels = labels[i]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
483 predict = [x+1 for x in labels]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
484 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
485 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
486
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
487
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
488 ############################# main ###########################################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
489 def main() -> None:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
490 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
491 Initializes everything and sets the program in motion based on the fronted input arguments.
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
492
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
493 Returns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
494 None
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
495 """
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
496 if not os.path.exists('clustering'):
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
497 os.makedirs('clustering')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
498
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
499 args = process_args(sys.argv)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
500
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
501 #Data read
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
502
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
503 X = read_dataset(args.input)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
504 X = pd.DataFrame.to_dict(X, orient='list')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
505 X = rewrite_input(X)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
506 X = pd.DataFrame.from_dict(X, orient = 'index')
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
507
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
508 for i in X.columns:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
509 tmp = X[i][0]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
510 if tmp == None:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
511 X = X.drop(columns=[i])
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
512
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
513 ## NAN TO HANLDE
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
514
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
515 if args.k_max != None:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
516 numero_classi = X.shape[0]
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
517 while args.k_max >= numero_classi:
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
518 err = 'Skipping k = ' + str(args.k_max) + ' since it is >= number of classes of dataset'
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
519 warning(err)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
520 args.k_max = args.k_max - 1
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
521
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
522
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
523 if args.cluster_type == 'kmeans':
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
524 kmeans(args.k_min, args.k_max, X, args.elbow, args.silhouette, args.best_cluster)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
525
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
526 if args.cluster_type == 'dbscan':
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
527 dbscan(X, args.eps, args.min_samples, args.best_cluster)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
528
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
529 if args.cluster_type == 'hierarchy':
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
530 hierachical_agglomerative(X, args.k_min, args.k_max, args.best_cluster, args.silhouette)
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
531
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
532 ##############################################################################
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
533 if __name__ == "__main__":
41f35c2f0c7b Uploaded
luca_milaz
parents:
diff changeset
534 main()