annotate cobraxy-9688ad27287b/COBRAxy/marea_cluster.py @ 91:f4f93df8c221 draft

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