Blame view

volia/clustering.py 9.6 KB
3b960e0f1   quillotm   Clustering comman...
1
2
3
  import argparse
  from os import path, mkdir
  from utils import SubCommandRunner
ef499b777   quillotm   Now we can extrac...
4
  from core.data import read_features, read_lst, read_labels, write_line
3b960e0f1   quillotm   Clustering comman...
5
6
7
  import numpy as np
  from sklearn.cluster import KMeans
  import pickle
9191399c3   quillotm   Clustering and ev...
8
  from clustering_modules.kmeans import kmeans
4152e83df   quillotm   Addind kmeans mah...
9
  from clustering_modules.kmeans_mahalanobis import  kmeansMahalanobis
a9912f135   quillotm   We can now precis...
10
  from clustering_modules.kmeans_multidistance import kmeansMultidistance
9191399c3   quillotm   Clustering and ev...
11
12
  
  from sklearn.preprocessing import LabelEncoder
fea9649a7   quillotm   Add many measures...
13
  from sklearn.metrics import v_measure_score, homogeneity_score, completeness_score
9191399c3   quillotm   Clustering and ev...
14
15
  
  import core.measures
3e2abe83e   quillotm   Multiple output f...
16
  import json
9191399c3   quillotm   Clustering and ev...
17
18
19
  
  
  CLUSTERING_METHODS = {
4152e83df   quillotm   Addind kmeans mah...
20
      "k-means": kmeans(),
4309b4a34   quillotm   Adding constraine...
21
      "k-means-mahalanobis": kmeansMahalanobis(),
a9912f135   quillotm   We can now precis...
22
23
24
      "k-means-mahalanobis-constrained": kmeansMahalanobis(constrained=True),
      "k-means-basic-mahalanobis": kmeansMultidistance(distance="mahalanobis"),
      "k-means-basic-cosine": kmeansMultidistance(distance="cosine")
9191399c3   quillotm   Clustering and ev...
25
  }
a9912f135   quillotm   We can now precis...
26
  KMEANS_METHODS = [key for key in CLUSTERING_METHODS if key.startswith("k-means")]
9191399c3   quillotm   Clustering and ev...
27
28
  EVALUATION_METHODS = {
      "entropy": core.measures.entropy_score,
fea9649a7   quillotm   Add many measures...
29
30
31
32
      "purity": core.measures.purity_score,
      "v-measure": v_measure_score,
      "homogeneity": homogeneity_score,
      "completeness": completeness_score,
9191399c3   quillotm   Clustering and ev...
33
34
35
36
37
38
39
40
  }
  
  
  def disequilibrium_run():
      pass
  
  
  def measure_run(measure: str, features: str, lst: str, truelabels: str, model: str, modeltype: str):
3e2abe83e   quillotm   Multiple output f...
41
42
43
44
45
46
47
48
49
50
      """
  
      @param measure:
      @param features:
      @param lst:
      @param truelabels:
      @param model:
      @param modeltype:
      @return:
      """
9191399c3   quillotm   Clustering and ev...
51
52
      module = CLUSTERING_METHODS[modeltype]
      module.load(model)
9191399c3   quillotm   Clustering and ev...
53

3e2abe83e   quillotm   Multiple output f...
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
      eval = {}
      for ms in measure:
          evaluation = EVALUATION_METHODS[ms]
          feats_dict = read_features(features)
          labels_dict = read_labels(truelabels)
          lst_dict = read_lst(lst)
          lst_keys = [key for key in lst_dict]
          feats = np.asarray([feats_dict[key] for key in lst_keys])
          Y_pred = module.predict(feats)
          Y_truth = [labels_dict[key][0] for key in lst_keys]
  
          le = LabelEncoder()
          le.fit(Y_truth)
          Y_truth = le.transform(Y_truth)
  
          eval[ms] = evaluation(Y_truth, Y_pred)
9191399c3   quillotm   Clustering and ev...
70

3e2abe83e   quillotm   Multiple output f...
71
      print(json.dumps(eval))
9191399c3   quillotm   Clustering and ev...
72

3b960e0f1   quillotm   Clustering comman...
73

ed89325d5   quillotm   Now, we can give ...
74
75
76
77
78
79
80
81
82
  def kmeans_run(features: str,
                 lst: str,
                 k:int,
                 kmax: int,
                 klist,
                 maxiter: int,
                 ninit: int,
                 output: str,
                 tol: float,
a9912f135   quillotm   We can now precis...
83
84
                 modeltype: str,
                 debug: bool = False):
3b960e0f1   quillotm   Clustering comman...
85
86
87
88
89
90
91
92
      """
  
      @param features: output features
      @param lst: list file
      @param k: k (kmin if kmax specified)
      @param kmax: maximum k to compute
      @param klist: list of k values to compute, ignore k value
      @param output: output file if kmax not specified, else, output directory
4152e83df   quillotm   Addind kmeans mah...
93
      @param mahalanobis: distance option of k-means.
3b960e0f1   quillotm   Clustering comman...
94
      """
660d9960f   quillotm   Adding n init par...
95
96
97
98
99
      json_content = locals().copy()
  
      def fit_model(k: int, output_file):
          if debug:
              print(f"Computing clustering with k={k}")
a9912f135   quillotm   We can now precis...
100
          model = CLUSTERING_METHODS[modeltype]
660d9960f   quillotm   Adding n init par...
101
102
103
104
105
106
107
108
          model.fit(X, k, tol, ninit, maxiter, debug)
          model.save(output_file)
          json_content["models"].append({
              "model_file": output_file,
              "k": k,
          })
  
      json_content["models"] = []
9191399c3   quillotm   Clustering and ev...
109
      # -- READ FILES --
3b960e0f1   quillotm   Clustering comman...
110
111
112
113
114
115
116
117
118
119
120
121
122
      features_dict = read_features(features)
      lst_dict = read_lst(lst)
      X = np.asarray([features_dict[x] for x in lst_dict])
  
      # Exception cases
      if kmax is None and klist is None and path.isdir(output):
          raise Exception("The \"output\" is an existing directory while the system is waiting the path of a file.")
  
      if (kmax is not None or klist is not None) and path.isfile(output):
          raise Exception("The \"output\" is an existing file while the system is waiting the path of a directory.")
  
      # Mono value case
      if kmax is None and klist is None:
660d9960f   quillotm   Adding n init par...
123
          fit_model(k, output)
3b960e0f1   quillotm   Clustering comman...
124
125
126
127
128
129
130
  
      # Multi values case with kmax
      if kmax is not None:
          if not path.isdir(output):
              mkdir(output)
          Ks = range(k, kmax + 1)
          for i in Ks:
660d9960f   quillotm   Adding n init par...
131
              fit_model(i, path.join(output, "clustering_" + str(i) + ".pkl"))
3b960e0f1   quillotm   Clustering comman...
132
133
134
135
136
137
138
  
      # Second multi values case with klist
      if klist is not None:
          if not path.isdir(output):
              mkdir(output)
          for k in klist:
              k = int(k)
91758e85f   quillotm   Solve an issue (i...
139
              fit_model(k, path.join(output, "clustering_" + str(k) + ".pkl"))
660d9960f   quillotm   Adding n init par...
140

ef499b777   quillotm   Now we can extrac...
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
      print(json.dumps(json_content))
  
  
  def extract_run(features, lst, model, modeltype, outfile):
      feats_dict = read_features(features)
      lst_dict = read_lst(lst)
      lst_keys = [key for key in lst_dict]
      feats = np.asarray([feats_dict[key] for key in lst_keys])
  
      module = CLUSTERING_METHODS[modeltype]
      module.load(model)
      Y_pred = module.predict(feats)
      with open(outfile, "w") as f:
          for i, key in enumerate(lst_keys):
              write_line(key, Y_pred[i], f)
      json_output = {
          "outfile": outfile
      }
      print(json.dumps(json_output))
ed89325d5   quillotm   Now, we can give ...
160

3b960e0f1   quillotm   Clustering comman...
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
  
  if __name__ == "__main__":
      # Main parser
      parser = argparse.ArgumentParser(description="Clustering methods to apply")
      subparsers = parser.add_subparsers(title="action")
  
      # kmeans
      parser_kmeans = subparsers.add_parser(
          "kmeans", help="Compute clustering using k-means algorithm")
  
      parser_kmeans.add_argument("--features", required=True, type=str, help="Features file (works with list)")
      parser_kmeans.add_argument("--lst", required=True, type=str, help="List file (.lst)")
      parser_kmeans.add_argument("-k", default=2, type=int,
                                 help="number of clusters to compute. It is kmin if kmax is specified.")
      parser_kmeans.add_argument("--kmax", default=None, type=int, help="if specified, k is kmin.")
      parser_kmeans.add_argument("--klist", nargs="+",
                                 help="List of k values to test. As kmax, activate the multi values mod.")
ed89325d5   quillotm   Now, we can give ...
178
179
180
181
182
183
184
185
186
187
188
189
190
      parser_kmeans.add_argument("--maxiter",
                                 type=int,
                                 default=300,
                                 help="Max number of iteration before stoping if not converging")
      parser_kmeans.add_argument("--ninit",
                                 type=int,
                                 default=10,
                                 help="Number of time the k-means algorithm will be run with different centroid seeds.")
      parser_kmeans.add_argument("--tol",
                                 type=float,
                                 default=0.0001,
                                 help="Tolerance to finish of distance between centroids and their updates.")
      parser_kmeans.add_argument("--debug", action="store_true")
4152e83df   quillotm   Addind kmeans mah...
191
192
193
      parser_kmeans.add_argument("--output",
                                 default=".kmeans",
                                 help="output file if only k. Output directory if multiple kmax specified.")
a9912f135   quillotm   We can now precis...
194
195
196
197
      parser_kmeans.add_argument("--modeltype",
                                  required=True,
                                  choices=KMEANS_METHODS,
                                  help="type of model for learning")
3b960e0f1   quillotm   Clustering comman...
198
      parser_kmeans.set_defaults(which="kmeans")
9191399c3   quillotm   Clustering and ev...
199
200
201
202
203
204
      # measure
      parser_measure = subparsers.add_parser(
          "measure", help="compute the entropy")
  
      parser_measure.add_argument("--measure",
                                  required=True,
3e2abe83e   quillotm   Multiple output f...
205
                                  nargs="+",
9191399c3   quillotm   Clustering and ev...
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
                                  choices=[key for key in EVALUATION_METHODS],
                                  help="...")
      parser_measure.add_argument("--features", required=True, type=str, help="...")
      parser_measure.add_argument("--lst", required=True, type=str, help="...")
      parser_measure.add_argument("--truelabels", required=True, type=str, help="...")
      parser_measure.add_argument("--model", required=True, type=str, help="...")
      parser_measure.add_argument("--modeltype",
                                  required=True,
                                  choices=[key for key in CLUSTERING_METHODS],
                                  help="type of model for learning")
      parser_measure.set_defaults(which="measure")
  
      # disequilibrium
      parser_disequilibrium = subparsers.add_parser(
          "disequilibrium", help="...")
  
      parser_disequilibrium.add_argument("--features", required=True, type=str, help="...")
      parser_disequilibrium.add_argument("--lstrain", required=True, type=str, help="...")
      parser_disequilibrium.add_argument("--lstest", required=True, type=str, help="...")
      parser_disequilibrium.add_argument("--model", required=True, type=str, help="...")
a9912f135   quillotm   We can now precis...
226
      parser_disequilibrium.add_argument("--modeltype",
9191399c3   quillotm   Clustering and ev...
227
228
229
                                  required=True,
                                  choices=["kmeans", "2", "3"],
                                  help="...")
e82889087   quillotm   Adding default va...
230
      parser_disequilibrium.set_defaults(which="disequilibrium")
9191399c3   quillotm   Clustering and ev...
231

ef499b777   quillotm   Now we can extrac...
232
233
234
235
236
237
238
239
240
241
242
243
244
      # Extract
      parser_extract = subparsers.add_parser(
          "extract", help="extract cluster labels")
  
      parser_extract.add_argument("--features", required=True, type=str, help="...")
      parser_extract.add_argument("--lst", required=True, type=str, help="...")
      parser_extract.add_argument("--model", required=True, type=str, help="...")
      parser_extract.add_argument("--modeltype",
                                  required=True,
                                  choices=[key for key in CLUSTERING_METHODS],
                                  help="type of model for learning")
      parser_extract.add_argument("--outfile", required=True, type=str, help="...")
      parser_extract.set_defaults(which="extract")
3b960e0f1   quillotm   Clustering comman...
245
246
247
248
249
      # Parse
      args = parser.parse_args()
  
      # Run commands
      runner = SubCommandRunner({
9191399c3   quillotm   Clustering and ev...
250
251
          "kmeans": kmeans_run,
          "measure": measure_run,
ef499b777   quillotm   Now we can extrac...
252
253
          "disequilibrium": disequilibrium_run,
          "extract": extract_run
3b960e0f1   quillotm   Clustering comman...
254
      })
9191399c3   quillotm   Clustering and ev...
255
      runner.run(args.which, args.__dict__, remove="which")