Blame view

bin/regroup-measures.py 4.35 KB
ee5cc2a7e   Mathias Quillot   Regroup all measu...
1
2
  '''
  Regroup results into one file and a plot.
ce4a6b1b9   Mathias Quillot   Plot 4 figures in...
3
4
  TODO: Mettre en valeur les valeurs maximales
  TODO: Sauvegarder les valeurs quelques part pour qu'on puisse facilement les retrouver.
ee5cc2a7e   Mathias Quillot   Regroup all measu...
5
6
7
8
9
10
11
  '''
  
  import numpy as np
  import matplotlib.pyplot as plt
  import argparse
  import os
  import json
ce4a6b1b9   Mathias Quillot   Plot 4 figures in...
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  def plot_values_clusters(values, title, xlabel, ylabel):
      values = np.asarray(values)
      x = np.arange(len(values)) + 2
      x_ticks = np.arange(len(values), step=10) + 2
      y = values
      plt.scatter(x, y, s=1)
      plt.xticks(x_ticks)
      plt.title(title)
      plt.xlabel(xlabel)
      plt.ylabel(ylabel)
  
  
  def save_plot(filepath):
      plt.savefig(filepath)
      plt.close()
  
  
  def save_results(outfile, measures, titles):
      with open(outfile, "w") as f:
          f.write(",".join(titles) + "
  ")
          n = len(measures[0])
          for i in range(n):
              f.write(",".join([str(ms[i]) for ms in measures]) + "
  ")
ee5cc2a7e   Mathias Quillot   Regroup all measu...
37
38
39
40
  
  # -- PARSER
  parser = argparse.ArgumentParser(description="")
  parser.add_argument("expdir", type=str, help="Directory of experiment")
ce4a6b1b9   Mathias Quillot   Plot 4 figures in...
41
42
43
44
  parser.add_argument("--measurefile", type=str, default="measures.json", 
                      help="Measure file it searchs in folders")
  parser.add_argument("--suffix", type=str, default="", 
                      help="suffix of saved files")
ee5cc2a7e   Mathias Quillot   Regroup all measu...
45
46
47
  
  args = parser.parse_args()
  EXP_DIR = args.expdir
ce4a6b1b9   Mathias Quillot   Plot 4 figures in...
48
  MEASURE_FILE = args.measurefile
ee5cc2a7e   Mathias Quillot   Regroup all measu...
49
  SUFFIX = args.suffix
ce4a6b1b9   Mathias Quillot   Plot 4 figures in...
50
51
  # EXP_DIR="exp/kmeans_teacher_1/pvector-1"
  RESULTS_DIR = os.path.join(EXP_DIR, "res")
ee5cc2a7e   Mathias Quillot   Regroup all measu...
52
53
54
55
56
57
58
59
  
  # -- CONFIG
  kmin = 2
  kmax = 100
  
  
  # -- CREATE FOLDER
  if not os.path.exists(RESULTS_DIR):
ce4a6b1b9   Mathias Quillot   Plot 4 figures in...
60
      os.makedirs(RESULTS_DIR)
ee5cc2a7e   Mathias Quillot   Regroup all measu...
61
62
63
64
65
66
  
  # -- BEGIN REGROUPMENT
  
  subsets = ["train", "val"]
  
  disequilibriums = []
ce4a6b1b9   Mathias Quillot   Plot 4 figures in...
67

ee5cc2a7e   Mathias Quillot   Regroup all measu...
68
  def init_measures():
ce4a6b1b9   Mathias Quillot   Plot 4 figures in...
69
70
71
72
73
74
75
76
77
      measures = {}
  
      for subset in subsets:
          measures[subset] = {}
          measures[subset]["entropy"] = []
          measures[subset]["vscore"] = []
          measures[subset]["homogeneity"] = []
          measures[subset]["completeness"] = []
      return measures
ee5cc2a7e   Mathias Quillot   Regroup all measu...
78

ee5cc2a7e   Mathias Quillot   Regroup all measu...
79
80
81
82
  
  measures = init_measures()
  
  for kfold in range(1, 5):
ce4a6b1b9   Mathias Quillot   Plot 4 figures in...
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
      print("Regrouping on kfold: " + str(kfold))
      # -- REGROUP MEASURES INTO LISTS
      for k in range(kmin, kmax+1):
          measures_file = os.path.join(EXP_DIR, str(kfold), str(k), MEASURE_FILE)
          with open(measures_file, 'r') as f:
              meas_data = json.load(f)
          disequilibriums.append(meas_data["disequilibrium"])
          for subset in subsets:
              measures[subset]["entropy"].append(
                  meas_data[subset]["entropy"])
              measures[subset]["vscore"].append(
                  meas_data[subset]["vscore"])
              measures[subset]["homogeneity"].append(
                  meas_data[subset]["homogeneity"])
              measures[subset]["completeness"].append(
                  meas_data[subset]["completeness"])
  
      # -- PLOT AND SAVE MEASURES FOR A SPECIFIC SUBSET
      for subset in subsets:
          # Plot all measures
          outf = "measures_" + str(subset) + "_" + str(kfold) + str(SUFFIX) + ".pdf"
  
          fig = plt.figure(1)
          for i, measure in enumerate(measures[subset]):
  
              plt.subplot(220 + i + 1)
  
              plot_values_clusters(
                  measures[subset][measure],
                  measure.capitalize() + " " + str(subset) + " set " + str(kfold),
                  "N clusters",
                  measure.capitalize())
          plt.subplots_adjust(hspace=0.5, wspace=0.3)
          save_plot(os.path.join(RESULTS_DIR, outf))
  
          # Save all measures on a csv file
          save_results(
              os.path.join(RESULTS_DIR, "measures_" + str(subset) + "_" + str(kfold) + str(SUFFIX) + ".csv"), 
              [
                  measures[subset]["entropy"],
                  measures[subset]["homogeneity"],
                  measures[subset]["completeness"],
                  measures[subset]["vscore"]
              ],
              [
                  "entropy",
                  "homogeneity",
                  "completeness",
                  "vscore"
              ]
          )
  
      # PLOT AND SAVE FOR DISEQUILIBRIUM
      plot_values_clusters(
          disequilibriums,
          "Disequilibrium set " + str(kfold),
          "N clusters",
          "Disequilibrium")
      save_plot(os.path.join(RESULTS_DIR, "disequilibrium_" + str(kfold) + str(SUFFIX) + ".pdf"))
  
      save_results(
          os.path.join(RESULTS_DIR, "disequilibrium_" + str(kfold) + str(SUFFIX) + ".csv"), 
          [disequilibriums],
          ["disequilibrium"])
  
      measures = init_measures()
      disequilibriums = []