-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathanalysis_utils.py
executable file
·2563 lines (2115 loc) · 84.2 KB
/
analysis_utils.py
1
2
3
4
5
6
7
8
9
10
11
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import json
import numbers
import os
import pickle
import re
import shutil
import yaml
import pprint
import traceback
import torch
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import tqdm
import utils as u
import plotly.express as px
import plotly.graph_objs as go
from tabulate import tabulate
from typing import Any, Dict, List, Optional, Tuple
from ray.tune.experiment.trial import Trial
from ray.tune.result import DEFAULT_METRIC, EXPR_PARAM_FILE, EXPR_PROGRESS_FILE, \
CONFIG_PREFIX, TRAINING_ITERATION
from ray.tune.search.variant_generator import generate_variants
logger = u.getLogger(__name__)
pp = pprint.PrettyPrinter(indent=4)
"""
resolve_nested_dict has been made private in later release of ray, so keep a copy here
"""
# from ray.tune.suggest.variant_generator import resolve_nested_dict
def resolve_nested_dict(nested_dict: Dict) -> Dict[Tuple, Any]:
"""Flattens a nested dict by joining keys into tuple of paths.
Can then be passed into `format_vars`.
"""
res = {}
for k, v in nested_dict.items():
if isinstance(v, dict):
for k_, v_ in resolve_nested_dict(v).items():
res[(k,) + k_] = v_
else:
res[(k,)] = v
return res
"""
Analysis has been depreciated by ray in favor of ExperimentAnalysis, which only loads recent experiment using the large json file.
This Analysis is what needed by this lib so keep a copy of it from ray==1.4.0
"""
class Analysis:
"""Analyze all results from a directory of experiments.
To use this class, the experiment must be executed with the JsonLogger.
Args:
experiment_dir (str): Directory of the experiment to load.
default_metric (str): Default metric for comparing results. Can be
overwritten with the ``metric`` parameter in the respective
functions. If None but a mode was passed, the anonymous metric
`ray.tune.result.DEFAULT_METRIC` will be used per default.
default_mode (str): Default mode for comparing results. Has to be one
of [min, max]. Can be overwritten with the ``mode`` parameter
in the respective functions.
"""
def __init__(self,
experiment_dir: str,
default_metric: Optional[str] = None,
default_mode: Optional[str] = None):
experiment_dir = os.path.expanduser(experiment_dir)
if not os.path.isdir(experiment_dir):
raise ValueError(
"{} is not a valid directory.".format(experiment_dir))
self._experiment_dir = experiment_dir
self._configs = {}
self._trial_dataframes = {}
self.default_metric = default_metric
if default_mode and default_mode not in ["min", "max"]:
raise ValueError(
"`default_mode` has to be None or one of [min, max]")
self.default_mode = default_mode
if self.default_metric is None and self.default_mode:
# If only a mode was passed, use anonymous metric
self.default_metric = DEFAULT_METRIC
if not pd:
logger.warning(
"pandas not installed. Run `pip install pandas` for "
"Analysis utilities.")
else:
self.fetch_trial_dataframes()
def _validate_metric(self, metric: str) -> str:
if not metric and not self.default_metric:
raise ValueError(
"No `metric` has been passed and `default_metric` has "
"not been set. Please specify the `metric` parameter.")
return metric or self.default_metric
def _validate_mode(self, mode: str) -> str:
if not mode and not self.default_mode:
raise ValueError(
"No `mode` has been passed and `default_mode` has "
"not been set. Please specify the `mode` parameter.")
if mode and mode not in ["min", "max"]:
raise ValueError("If set, `mode` has to be one of [min, max]")
return mode or self.default_mode
def dataframe(self,
metric: Optional[str] = None,
mode: Optional[str] = None) -> pd.DataFrame:
"""Returns a pd.DataFrame object constructed from the trials.
Args:
metric (str): Key for trial info to order on.
If None, uses last result.
mode (str): One of [min, max].
Returns:
pd.DataFrame: Constructed from a result dict of each trial.
"""
# Allow None values here.
if metric or self.default_metric:
metric = self._validate_metric(metric)
if mode or self.default_mode:
mode = self._validate_mode(mode)
rows = self._retrieve_rows(metric=metric, mode=mode)
all_configs = self.get_all_configs(prefix=True)
for path, config in all_configs.items():
if path in rows:
rows[path].update(config)
rows[path].update(logdir=path)
return pd.DataFrame(list(rows.values()))
def get_best_config(self,
metric: Optional[str] = None,
mode: Optional[str] = None) -> Optional[Dict]:
"""Retrieve the best config corresponding to the trial.
Args:
metric (str): Key for trial info to order on. Defaults to
``self.default_metric``.
mode (str): One of [min, max]. Defaults to
``self.default_mode``.
"""
metric = self._validate_metric(metric)
mode = self._validate_mode(mode)
rows = self._retrieve_rows(metric=metric, mode=mode)
if not rows:
# only nans encountered when retrieving rows
logger.warning("Not able to retrieve the best config for {} "
"according to the specified metric "
"(only nans encountered).".format(
self._experiment_dir))
return None
all_configs = self.get_all_configs()
compare_op = max if mode == "max" else min
best_path = compare_op(rows, key=lambda k: rows[k][metric])
return all_configs[best_path]
def get_best_logdir(self,
metric: Optional[str] = None,
mode: Optional[str] = None) -> Optional[str]:
"""Retrieve the logdir corresponding to the best trial.
Args:
metric (str): Key for trial info to order on. Defaults to
``self.default_metric``.
mode (str): One of [min, max]. Defaults to ``self.default_mode``.
"""
metric = self._validate_metric(metric)
mode = self._validate_mode(mode)
assert mode in ["max", "min"]
df = self.dataframe(metric=metric, mode=mode)
mode_idx = pd.Series.idxmax if mode == "max" else pd.Series.idxmin
try:
return df.iloc[mode_idx(df[metric])].logdir
except KeyError:
# all dirs contains only nan values
# for the specified metric
# -> df is an empty dataframe
logger.warning("Not able to retrieve the best logdir for {} "
"according to the specified metric "
"(only nans encountered).".format(
self._experiment_dir))
return None
def fetch_trial_dataframes(self) -> Dict[str, pd.DataFrame]:
fail_count = 0
for path in self._get_trial_paths():
try:
self.trial_dataframes[path] = pd.read_csv(
os.path.join(path, EXPR_PROGRESS_FILE))
except Exception:
fail_count += 1
if fail_count:
logger.debug(
"Couldn't read results from {} paths".format(fail_count))
return self.trial_dataframes
def get_all_configs(self, prefix: bool = False) -> Dict[str, Dict]:
"""Returns a list of all configurations.
Args:
prefix (bool): If True, flattens the config dict
and prepends `config/`.
Returns:
Dict[str, Dict]: Dict of all configurations of trials, indexed by
their trial dir.
"""
fail_count = 0
for path in self._get_trial_paths():
try:
with open(os.path.join(path, EXPR_PARAM_FILE)) as f:
config = json.load(f)
if prefix:
for k in list(config):
config[CONFIG_PREFIX + k] = config.pop(k)
self._configs[path] = config
except Exception:
fail_count += 1
if fail_count:
logger.warning(
"Couldn't read config from {} paths".format(fail_count))
return self._configs
def get_trial_checkpoints_paths(self,
trial: Trial,
metric: Optional[str] = None
) -> List[Tuple[str, numbers.Number]]:
"""Gets paths and metrics of all persistent checkpoints of a trial.
Args:
trial (Trial): The log directory of a trial, or a trial instance.
metric (str): key for trial info to return, e.g. "mean_accuracy".
"training_iteration" is used by default if no value was
passed to ``self.default_metric``.
Returns:
List of [path, metric] for all persistent checkpoints of the trial.
"""
metric = metric or self.default_metric or TRAINING_ITERATION
if isinstance(trial, str):
trial_dir = os.path.expanduser(trial)
# Get checkpoints from logdir.
chkpt_df = TrainableUtil.get_checkpoints_paths(trial_dir)
# Join with trial dataframe to get metrics.
trial_df = self.trial_dataframes[trial_dir]
path_metric_df = chkpt_df.merge(
trial_df, on="training_iteration", how="inner")
return path_metric_df[["chkpt_path", metric]].values.tolist()
elif isinstance(trial, Trial):
checkpoints = trial.checkpoint_manager.best_checkpoints()
# Support metrics given as paths, e.g.
# "info/learner/default_policy/policy_loss".
return [(c.value, unflattened_lookup(metric, c.result))
for c in checkpoints]
else:
raise ValueError("trial should be a string or a Trial instance.")
def get_best_checkpoint(self,
trial: Trial,
metric: Optional[str] = None,
mode: Optional[str] = None) -> Optional[str]:
"""Gets best persistent checkpoint path of provided trial.
Args:
trial (Trial): The log directory of a trial, or a trial instance.
metric (str): key of trial info to return, e.g. "mean_accuracy".
"training_iteration" is used by default if no value was
passed to ``self.default_metric``.
mode (str): One of [min, max]. Defaults to ``self.default_mode``.
Returns:
Path for best checkpoint of trial determined by metric
"""
metric = metric or self.default_metric or TRAINING_ITERATION
mode = self._validate_mode(mode)
checkpoint_paths = self.get_trial_checkpoints_paths(trial, metric)
if not checkpoint_paths:
logger.error(f"No checkpoints have been found for trial {trial}.")
return None
if mode == "max":
return max(checkpoint_paths, key=lambda x: x[1])[0]
else:
return min(checkpoint_paths, key=lambda x: x[1])[0]
def get_last_checkpoint(self,
trial=None,
metric="training_iteration",
mode="max"):
"""Helper function that wraps Analysis.get_best_checkpoint().
Gets the last persistent checkpoint path of the provided trial,
i.e., with the highest "training_iteration".
If no trial is specified, it loads the best trial according to the
provided metric and mode (defaults to max. training iteration).
Args:
trial (Trial): The log directory or an instance of a trial.
If None, load the latest trial automatically.
metric (str): If no trial is specified, use this metric to identify
the best trial and load the last checkpoint from this trial.
mode (str): If no trial is specified, use the metric and this mode
to identify the best trial and load the last checkpoint from it.
Returns:
Path for last checkpoint of trial
"""
if trial is None:
trial = self.get_best_logdir(metric, mode)
return self.get_best_checkpoint(trial, "training_iteration", "max")
def _retrieve_rows(self,
metric: Optional[str] = None,
mode: Optional[str] = None) -> Dict[str, Any]:
assert mode is None or mode in ["max", "min"]
rows = {}
for path, df in self.trial_dataframes.items():
if mode == "max":
idx = df[metric].idxmax()
elif mode == "min":
idx = df[metric].idxmin()
else:
idx = -1
try:
rows[path] = df.iloc[idx].to_dict()
except TypeError:
# idx is nan
logger.warning(
"Warning: Non-numerical value(s) encountered for {}".
format(path))
return rows
def _get_trial_paths(self) -> List[str]:
_trial_paths = []
for trial_path, _, files in os.walk(self._experiment_dir):
if EXPR_PROGRESS_FILE in files:
_trial_paths += [trial_path]
if not _trial_paths:
raise TuneError("No trials found in {}.".format(
self._experiment_dir))
return _trial_paths
@property
def trial_dataframes(self) -> Dict[str, pd.DataFrame]:
"""List of all dataframes of the trials."""
return self._trial_dataframes
"""
Produce Nature-level plots.
"""
def nature_pre(df, our_name='PC', base_name='BP'):
# rename
if 'PC' in df.columns:
df.insert(
1, 'Rule',
df.apply(
lambda row: {
True: our_name,
False: base_name,
'TP': 'TP',
}[row['PC']], axis=1
)
)
elif 'Rule' in df.columns:
df.insert(
1, 'Rule-t',
df.apply(
lambda row: {
'Predictive-Coding': our_name,
'Back-Propagation': base_name
}[row['Rule']], axis=1
)
)
del df['Rule']
df = df.rename(columns={'Rule-t': 'Rule'})
else:
raise NotImplementedError
if 'ns' in df.columns:
df.insert(
1, 'Hidden size',
df.apply(
lambda row: eval(row['ns'])[1], axis=1
)
)
# sort
df = df.sort_values(['Rule'], ascending=False)
df1 = df.set_index('Rule')
sort_order = ['PC', 'BP']
if 'TP' in df['Rule'].unique().tolist():
sort_order.append('TP')
df = df1.loc[sort_order].reset_index()
return df
def nature_relplot(kind='line', sharey=True, sharex=True, legend_out=False, **kwargs):
"""
"""
additional_kwargs = dict()
if kind=='line':
# standard error
# historically, I was using errorbar=('ci', 68),
# this is because 68%CI = Score ±SEM, see https://www.statisticshowto.com/standard-error-of-measurement/
# but latter Rafal noticed that the error bars could be asymmetric,
# the reason is that
# Seaborn's errorbar function produces asymmetric error bars by default because it uses the bootstrapped confidence intervals for the error bars.
# This means that it samples the data with replacement to calculate the confidence intervals.
# Bootstrapping is a way to estimate the sampling distribution of a statistic (such as the mean or standard deviation) using the data itself,
# without making assumptions about the underlying distribution.
# This is a robust method that can work well even when the underlying distribution is not normal.
# However, it can result in asymmetric error bars.
# seaborn's documentation: https://seaborn.pydata.org/tutorial/error_bars.html#confidence-interval-error-bars
# so I switched to 'se'
# errorbar=("se"),
additional_kwargs['errorbar']=('ci', 68)
# bars for error
additional_kwargs['err_style']='bars'
additional_kwargs['err_kws']={
# settings for error bars
'capsize': 6,
'capthick': 2,
}
return sns.relplot(
kind=kind,
# with markers
markers=True,
facet_kws={
# legend inside
'legend_out': legend_out,
# titles of row and col on margins
'margin_titles': True,
# share axis
'sharey': sharey,
'sharex': sharex,
},
**kwargs,
**additional_kwargs,
)
def nature_relplot_curve(sharey=True, sharex=True, legend_out=False, **kwargs):
"""
"""
return sns.relplot(
# standard error
errorbar=('ci', 68),
# line
kind='line',
# without markers
markers=False,
facet_kws={
# legend inside
'legend_out': legend_out,
# share axis
'sharey': sharey,
'sharex': sharex,
'margin_titles': True,
},
# band for error
err_style='band',
**kwargs,
)
def nature_catplot(**kwargs):
"""
"""
return sns.catplot(
# standard error
errorbar=('ci', 68),
# legend inside
legend_out=False,
# titles of row and col on margins
margin_titles=True,
**kwargs,
)
def nature_catplot_sharey(*args, **kwargs):
"""
"""
return sns.catplot(
*args, **kwargs,
# standard error
errorbar=('ci', 68),
# bar
kind='bar',
# legend inside
legend_out=False,
# titles of row and col on margins
margin_titles=True,
# sharing y
sharey=True,
# # bars for error
# err_style='bars',
# err_kws={
# # settings for error bars
# 'capsize': 6,
# 'capthick': 2,
# },
)
def nature_post(g, xticks=None, yticks=None, is_grid=True):
# set xticks
if xticks is not None:
if isinstance(xticks, list):
[ax.set_xticks(xticks) for ax in g.axes.flat]
[ax.set_xticklabels(xticks) for ax in g.axes.flat]
else:
raise NotImplementedError
if yticks is not None:
if isinstance(yticks, list):
[ax.set_yticks(yticks) for ax in g.axes.flat]
[ax.set_yticklabels(yticks) for ax in g.axes.flat]
else:
raise NotImplementedError
# create grid
if is_grid:
[ax.grid(True, which='both') for ax in g.axes.flat]
"""
End of Produce Nature-level plots.
"""
def format_friendly_string(string, is_abbr=False):
"""See https://github.com/YuhangSong/general-energy-nets/tree/master/experiments#you-may-want-to-format-a-string-to-be-friendly-for-being-a-dictionary
Format a string to be friendly. Specifically,
1, replace all special characters, punctuation and spaces from string with '_'
2, remove consecutive duplicates of '_'
3, remove '_' at the start and end
Args:
is_abbr (bool): if use abbreviations.
"""
# replace all special characters, punctuation and spaces from string with '_'
friendly_string = []
for e in string:
if e.isalnum():
friendly_string.append(e)
else:
friendly_string.append('_')
# remove consecutive duplicates of '_'
friendly_string = re.sub(r'(_)\1+', r'\1', ''.join(friendly_string))
# remove '_' at the start and end
if len(friendly_string) > 0:
if friendly_string[0] == '_':
friendly_string = friendly_string[1:]
if len(friendly_string) > 0:
if friendly_string[-1] == '_':
friendly_string = friendly_string[:-1]
if is_abbr:
logger.warning(
"Replacing some long names with abbreviations, which should not cause any confusion, but be careful with this. "
"If you saw some images got overwritten (flashes while running <analysis_v1.py>), it is because of this. "
"You then need to turn this off or check if the following replacing is causing some confusion: different configs got the same abbreviation. "
)
friendly_string = friendly_string.replace('__', '_')
friendly_string = friendly_string.replace('True', 'T')
friendly_string = friendly_string.replace('False', 'F')
friendly_string = friendly_string.replace(
'test_classification_error', 'te_ce'
)
friendly_string = friendly_string.replace(
'train_classification_error', 'tr_ce'
)
friendly_string = friendly_string.replace('M', 'M')
friendly_string = friendly_string.replace('FashionMNIST', 'FM')
friendly_string = friendly_string.replace('CIFAR10', 'C10')
friendly_string = friendly_string.replace('CIFAR100', 'C100')
friendly_string = friendly_string.replace('optim_', '')
friendly_string = friendly_string.replace('torch_nn_init_', '')
friendly_string = friendly_string.replace('lambda_', '')
friendly_string = friendly_string.replace('F_', '')
friendly_string = friendly_string.replace('init_', '')
friendly_string = friendly_string.replace('xavier', 'xa')
friendly_string = friendly_string.replace('kaiming', 'ka')
friendly_string = friendly_string.replace('normal', 'n')
friendly_string = friendly_string.replace('uniform', 'u')
friendly_string = friendly_string.replace('reciprocal', 'r')
friendly_string = friendly_string.replace('friendly_', '')
return friendly_string
def save_fig(logdir, title, formats=['png'], savefig_kwargs={}):
"""Save current figure for plt.
Args:
logdir (str): Log directory of the figure.
title (str): Title of the figure.
formats (list): A list of formats.
Example: formats=['pdf', 'png']
savefig_kwargs (dict): Keyword arguments passed to <plt.savefig()>.
Example: savefig_kwargs={'pad_inches': 0.1,
'dpi': 500, 'bbox_inches': 'tight'}
Returns:
paths (dict): e.g.,
{
'png': 'path_to_png_figure.png',
'pdf': 'path_to_pdf_figure.pdf',
}
"""
assert isinstance(logdir, str)
assert isinstance(title, str)
assert isinstance(formats, list)
for format in formats:
assert isinstance(format, str)
assert isinstance(savefig_kwargs, dict)
logger.info(f"Save fig {title} to {logdir} in formats {formats}.")
u.prepare_dir(logdir)
paths = {}
for format in formats:
paths[format] = '{}/{}.{}'.format(logdir, title, format)
plt.savefig(
paths[format],
**savefig_kwargs,
)
return paths
class _SafeFallbackEncoder(json.JSONEncoder):
def __init__(self, nan_str="null", **kwargs):
super(_SafeFallbackEncoder, self).__init__(**kwargs)
self.nan_str = nan_str
def default(self, value):
try:
if np.isnan(value):
return self.nan_str
if (type(value).__module__ == np.__name__
and isinstance(value, np.ndarray)):
return value.tolist()
if issubclass(type(value), numbers.Integral):
return int(value)
if issubclass(type(value), numbers.Number):
return float(value)
return super(_SafeFallbackEncoder, self).default(value)
except Exception:
return str(value) # give up, just stringify it (ok for logs)
def save_dict(d, logdir, title, formats=['pickle']):
"""Save a dictionary
Args:
d (dict): The dictionary to save.
logdir (str): Directory to save.
title (str): Title to save.
formats (list): A list of formats to save, as the following: json, pickle, yaml.
"""
assert isinstance(d, dict)
assert isinstance(logdir, str)
assert isinstance(title, str)
assert isinstance(formats, list)
for format in formats:
assert isinstance(format, str)
logger.info(f"Saving dict {title} to {logdir} in formats {formats}.")
u.prepare_dir(logdir)
for format in formats:
path = os.path.join(logdir, '{}.{}'.format(title, format))
if format == 'json':
with open(path, "w") as f:
json.dump(
d, f,
indent=2,
sort_keys=True,
cls=_SafeFallbackEncoder)
elif format == 'pickle':
with open(path, 'wb') as handle:
pickle.dump(d, handle, protocol=pickle.HIGHEST_PROTOCOL)
elif format == 'yaml':
with open(path, 'w') as f:
yaml.dump(d, f)
else:
raise NotADirectoryError
def load_dict(logdir=None, title=None, format='pickle', path=None):
"""Load a dictionary
Args:
logdir (None | str): The log directory.
title (None | str): The title.
format (None | str): The format in the following: json, pickle, yaml.
path (None | str): The path, which will override logdir, title and format.
"""
if (path is not None):
assert isinstance(path, str)
assert (logdir is None) and (title is None)
logger.info(f"Loading dict from path {path}")
elif (logdir is not None) and (title is not None) and (format is not None):
assert isinstance(logdir, str)
assert isinstance(title, str)
assert isinstance(format, str)
logger.info(f"Loading dict {title} from {logdir} in format {format}")
path = os.path.join(logdir, '{}.{}'.format(title, format))
else:
raise NotImplementedError
format = path.split('.')[-1]
if format == 'json':
with open(path, "r") as f:
d = json.load(f)
elif format == 'pickle':
with open(path, 'rb') as handle:
d = pickle.load(handle)
elif format == 'yaml':
with open(path, "r") as f:
d = yaml.safe_load(f)
else:
raise NotImplementedError
return d
def load_config_from_params(logdir, silent_broken_trials=True):
"""Load config from params.json in a logdir.
Args:
logdir (str): The logdir, in which we load the config from params.json.
silent_broken_trials (bool): Whether to be silent when seeing broken trials.
Returns:
(Dict) The config.
"""
path = os.path.join(logdir, "params.json")
try:
with open(path, "rt") as f:
config = json.load(f)
return config
except Exception as e:
if not silent_broken_trials:
logger.warning(
f"Cannot load config from paramas.json in {logdir}: \n{e}")
is_remove = u.inquire_confirm(
"would you like to remove the folder?")
if is_remove:
shutil.rmtree(logdir)
return None
def summarize_select(df, config_columns, group_summarize, summarize_fn, group_select, select_fn):
"""See https://github.com/YuhangSong/general-energy-nets/tree/master/experiments#summarize-and-select
Args:
df (pd.DataFrame): The dataframe.
config_columns (list): A list of column names specifying config values. It is obtained from analysis_v1.py.
group_summarize (list): A list of column names specifying groups to summarize over. E.g.: ['seed'].
summarize_fn (callable): The function for summarize over the specified groups.
E.g.:
lambda df: df['test error'].mean()
group_select (list): A list of column names specifying groups to select over. E.g.: ['learning rate'].
select_fn (callable): The function for select over the specified groups.
E.g.:
lambda df: lambda df: df['summarize'] == df['summarize'].min()
Returns:
(pd.DataFrame): The dataframe.
"""
groups = copy.deepcopy(config_columns)
[groups.remove(key) for key in group_summarize]
df = add_metric_per_group(
df, groups,
lambda df: (
'summarize',
summarize_fn(df)
)
)
[groups.remove(key) for key in group_select]
df = select_rows_per_group(
df, groups,
lambda df: select_fn(df)
)
df = drop_cols(df, ['summarize'])
return df
def select_best_lr(df, config_columns, metric, group_summarize=['seed'], group_select=['learning_rate'], is_min=True):
"""See https://github.com/YuhangSong/general-energy-nets/tree/master/experiments#summarize-and-select
Args:
df: See summarize_select.
config_columns: See summarize_select.
metric (str): The name of the metric column.
group_summarize: See summarize_select.
group_select: See summarize_select.
is_min (bool): Select the minimum (True) or maximum (False).
Returns:
(pd.DataFrame): The dataframe.
"""
if is_min:
def select_fn(df): return df['summarize'] == df['summarize'].min()
else:
def select_fn(df): return df['summarize'] == df['summarize'].max()
return summarize_select(
df, config_columns,
group_summarize, lambda df: df[metric].mean(),
group_select, select_fn
)
def one_row_per_config(df, metric_columns, config_columns, keep_small=True):
"""Drop rows of the same config (specified by config_columns), only leave one row per config in df.
Note that those metrics (specified by metric_columns) with NaN values will be dropped with priority.
"""
for metric_column in metric_columns:
if "-along-" not in metric_column:
df = df.sort_values(
by=[metric_column], ascending=keep_small, na_position='last'
)
return df.drop_duplicates(
subset=config_columns
)
class AnalysisDataFrame():
"""Dataframe with specfications of config_columns and metric_columns.
"""
def __init__(self, dataframe, config_columns, metric_columns):
self.dataframe = dataframe
self.config_columns = config_columns
self.metric_columns = metric_columns
def one_row_per_config(self):
"""Drop duplicates according to config_columns.
"""
self.dataframe = one_row_per_config(
df=self.dataframe,
metric_columns=self.metric_columns,
config_columns=self.config_columns,
)
return self
def rename(self, mapper, is_include_dataframe=True):
"""Rename columns.
"""
if is_include_dataframe:
self.dataframe = self.dataframe.rename(
columns=mapper,
)
self.config_columns = u.map_list_by_dict(
self.config_columns, mapper
)
self.metric_columns = u.map_list_by_dict(
self.metric_columns, mapper
)
return self
def get_dataframe_with_config_metric_columns_only(self):
"""Return a dataframe with only config_columns and metric_columns.
"""
return self.dataframe[self.config_columns + self.metric_columns]
def get_dataframe_with_config_columns_only(self):
"""Return a dataframe with only config_columns.
"""
return self.dataframe[self.config_columns]
def get_dataframe_with_metric_columns_only(self):
"""Return a dataframe with only metric_columns.
"""
return self.dataframe[self.metric_columns]
def get_analysis_df(analysis, metrics, is_log_progress=True, silent_broken_trials=True):
"""Get a dataframe for an analysis.
Note that this function will not drop any trials.
Args:
analysis (ray.tune.Analysis): Analysis object to get dataframes from.
metrics (list of str): Each of which is a evalable str that will produce a metric.
is_log_progress (bool): Whether to show progress.
silent_broken_trials (bool): Whether to be silent when seeing broken trials.
Returns:
(pd.DataFrame) with each config or metric as a column, each trial as a row.
"""
# sanitize args
assert isinstance(analysis, Analysis)
assert isinstance(metrics, list)
for m in metrics:
assert isinstance(m, str)
assert isinstance(is_log_progress, bool)
assert isinstance(silent_broken_trials, bool)
# load config
# flatten config to flatten_configs
flatten_configs = {}
for logdir in analysis.trial_dataframes.keys():
# load config
config = load_config_from_params(
logdir, silent_broken_trials
)
if config is not None:
# flatten config to flatten_configs
flatten_configs[logdir] = resolve_nested_dict(config)
else:
continue
# init config_columns and metric_columns
config_columns = []
metric_columns = []
# init rows
rows = []
# iterate over each trial
iterator = flatten_configs.items()
if is_log_progress:
iterator = tqdm.tqdm(iterator, leave=False)
for logdir, config in iterator:
if is_log_progress:
iterator.set_description('get_analysis_df')
# get df of the trial
df = analysis.trial_dataframes[logdir]
if 'done' in df.columns:
# Why some done values has Nan (even at iloc[-1])? Anyway, replace these NaN values with False should be safe
df['done'].fillna(False, inplace=True)
if not df['done'].iloc[-1].item():
# the training is not completed, skip incompleted trails
# it is not a warning message as these incompleted may have been re-runned
logger.warning(f"Incompleted trail found.")
continue
else:
logger.warning((
f"The 'done' signal is not in the logged columns, might be an issue with ray version. Please install the correct version required. "
))
# init row