forked from alan-turing-institute/affinity-vae
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
734 lines (714 loc) · 16.5 KB
/
run.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
import logging
import os
import warnings
import click
import avae.settings as settings
from avae.config import (
load_config_params,
setup_visualisation_config,
write_config_file,
)
from avae.evaluate import evaluate
from avae.train import train
@click.command(name="Affinity Trainer")
@click.option("--config_file", type=click.Path(exists=True))
@click.option(
"--datapath",
"-d",
type=str,
default=None,
help="Path to training data.",
)
@click.option(
"--datatype",
"-dtype",
type=str,
default=None,
help="Type of the data: mrc, npy",
)
@click.option(
"--debug",
"-dbg",
type=bool,
default=None,
is_flag=True,
help="Run in debug mode.",
)
@click.option(
"--restart",
"-res",
type=bool,
default=None,
is_flag=True,
help="Is the calculation restarting from a checkpoint.",
)
@click.option(
"--state",
"-st",
type=str,
default=None,
help="The saved model state to be loaded for evaluation/resume training.",
)
@click.option(
"--meta",
"-mt",
type=str,
default=None,
help="The saved meta file to be loaded for regenerating dynamic plots.",
)
@click.option(
"--limit",
"-lm",
type=int,
default=None,
help="Limit the number of samples loaded (default None).",
)
@click.option(
"--split", "-sp", type=int, default=None, help="Train/val split in %."
)
@click.option(
"--new_out",
"-newo",
type=bool,
default=None,
is_flag=True,
help="Create new output directory where to save the results.",
)
@click.option(
"--no_val_drop",
"-nd",
type=bool,
default=None,
is_flag=True,
help="Do not drop last validate batch if "
"if it is smaller than batch_size.",
)
@click.option(
"--affinity",
"-af",
type=str,
default=None,
help="Path to affinity matrix for training.",
)
@click.option(
"--classes",
"-cl",
type=str,
default=None,
help="Path to a CSV file containing a list of classes for training.",
)
@click.option(
"--classifier",
"-clf",
type=str,
default=None,
help="Method to classify the latent space. Options are: KNN (nearest neighbour), NN (neural network), LR (Logistic Regression).",
)
@click.option(
"--epochs",
"-ep",
type=int,
default=None,
help="Number of epochs (default 100).",
)
@click.option(
"--batch", "-ba", type=int, default=None, help="Batch size (default 128)."
)
@click.option(
"--depth",
"-de",
type=int,
default=None,
help="Depth of the convolutional layers (default 3).",
)
@click.option(
"--channels",
"-ch",
type=int,
default=None,
help="First layer channels (default 64).",
)
@click.option(
"--filters",
"-fl",
type=str,
default=None,
help="Comma-separated list of filters for the network. Either provide "
"filters, or capacity and depth.",
)
@click.option(
"--latent_dims",
"-ld",
type=int,
default=None,
help="Latent space dimension (default 10).",
)
@click.option(
"--pose_dims",
"-pd",
type=int,
default=None,
help="If pose on, number of pose dimensions. If 0 and gamma=0 it becomes"
"a standard beta-VAE.",
)
@click.option(
"--bnorm_encoder",
"-bn_enc",
type=bool,
is_flag=True,
default=None,
help="Batch normalisation in encoder is on if True.",
)
@click.option(
"--bnorm_decoder",
"-bn_dec",
type=bool,
is_flag=True,
default=None,
help="Batch normalisation in encoder is on if True.",
)
@click.option(
"--klreduction",
"-kr",
type=str,
default=None,
help="Mean or sum reduction on KLD term.",
)
@click.option(
"--beta",
"-be",
type=float,
default=None,
help="Beta maximum in the case of cyclical annealing schedule",
)
@click.option(
"--beta_load",
"-bl",
type=str,
default=None,
is_flag=True,
help="The path to the saved beta array file to be loaded "
"if this file is provided, all other beta related variables would be ignored",
)
@click.option(
"--gamma",
"-g",
type=float,
default=None,
help="Scale factor for the loss component corresponding "
"to shape similarity. If 0 and pd=0 it becomes a standard"
"beta-VAE.",
)
@click.option(
"--gamma_load",
"-gl",
type=str,
default=None,
is_flag=True,
help="The path to the saved gamma array file to be loaded"
"if this file is provided, all other gamma related variables would be ignored",
)
@click.option(
"--learning",
"-lr",
type=float,
default=None,
help="Learning rate.",
)
@click.option(
"--loss_fn",
"-lf",
type=str,
default=None,
help="Loss type: 'MSE' or 'BCE' (default 'MSE').",
)
@click.option(
"--beta_min",
"-bs",
type=float,
default=None,
help="Beta minimum in the case of cyclical annealing schedule",
)
@click.option(
"--beta_cycle",
"-bc",
type=int,
default=None,
help="Number of cycles for beta during training in the case of cyclical annealing schedule",
)
@click.option(
"--beta_ratio",
"-br",
type=float,
default=None,
help="The ratio for steps in beta",
)
@click.option(
"--cyc_method_beta",
"-cycmb",
type=str,
default=None,
help="The schedule for : for constant beta : flat, other options include , cycle_linear, cycle_sigmoid, cycle_cosine, ramp",
)
@click.option(
"--gamma_min",
"-gs",
type=float,
default=None,
help="gamma minimum in the case of cyclical annealing schedule",
)
@click.option(
"--gamma_cycle",
"-gc",
type=int,
default=None,
help="Number of cycles for gamma during training in the case of cyclical annealing schedule",
)
@click.option(
"--gamma_ratio",
"-gr",
type=float,
default=None,
help="The ratio for steps in gamma",
)
@click.option(
"--cyc_method_gamma",
"-cycmg",
type=str,
default=None,
help="The schedule for gamma: for constant gamma : flat, other options include , cycle_linear, cycle_sigmoid, cycle_cosine, ramp",
)
@click.option(
"--gpu",
"-g",
type=bool,
default=None,
is_flag=True,
help="Use GPU for training.",
)
@click.option(
"--eval",
"-ev",
type=bool,
default=None,
is_flag=True,
help="Evaluate test data.",
)
@click.option(
"--dynamic",
"-dn",
type=bool,
default=None,
is_flag=True,
help="Enable collecting meta and dynamic latent space plots.",
)
@click.option(
"--model",
"-m",
type=str,
default=None,
help="Choose model to run.",
)
@click.option(
"--vis_los",
"-vl",
type=bool,
default=None,
is_flag=True,
help="Visualise loss (every epoch starting at epoch 2).",
)
@click.option(
"--vis_acc",
"-vac",
type=bool,
default=None,
is_flag=True,
help="Visualise confusion matrix and F1 scores (frequency controlled).",
)
@click.option(
"--vis_rec",
"-vr",
type=bool,
default=None,
is_flag=True,
help="Visualise reconstructions (frequency controlled).",
)
@click.option(
"--vis_emb",
"-ve",
type=bool,
default=None,
is_flag=True,
help="Visualise latent space embedding (frequency controlled).",
)
@click.option(
"--vis_int",
"-vi",
type=bool,
default=None,
is_flag=True,
help="Visualise interpolations (frequency controlled).",
)
@click.option(
"--vis_dis",
"-vt",
type=bool,
default=None,
is_flag=True,
help="Visualise latent disentanglement (frequency controlled).",
)
@click.option(
"--vis_pos",
"-vps",
type=bool,
default=None,
is_flag=True,
help="Visualise pose disentanglement (frequency controlled).",
)
@click.option(
"--vis_pose_class",
"-vpsc",
type=str,
default=None,
help="Example: A,B,C. your deliminator should be commas and no spaces. Classes to be used for pose interpolation (a seperate pose interpolation figure would be created for each class).",
)
@click.option(
"--vis_z_n_int",
"-vzni",
type=str,
default=None,
help="Number of Latent interpolation classes to to be printed, number of interpolation steps in each plot. Example: 1,10. 1 plot with 10 interpolation steps between two classes. your deliminator should be commas and no spaces.",
)
@click.option(
"--vis_cyc",
"-vc",
type=bool,
default=None,
is_flag=True,
help="Visualise cyclical parameters (once per run).",
)
@click.option(
"--vis_aff",
"-va",
type=bool,
default=None,
is_flag=True,
help="Visualise affinity matrix (once per run).",
)
@click.option(
"--vis_his",
"-his",
type=bool,
default=None,
is_flag=True,
help="Visualise train-val class distribution (once per run).",
)
@click.option(
"--vis_sim",
"-similarity",
type=bool,
default=None,
is_flag=True,
help="Visualise train-val model similarity matrix.",
)
@click.option(
"--vis_all",
"-va",
type=bool,
default=None,
is_flag=True,
help="Visualise all above.",
)
@click.option(
"--freq_eval",
"-fev",
type=int,
default=None,
help="Frequency at which to evaluate test set.",
)
@click.option(
"--freq_sta",
"-fs",
type=int,
default=None,
help="Frequency at which to save state",
)
@click.option(
"--freq_acc",
"-fac",
type=int,
default=None,
help="Frequency at which to visualise confusion matrix.",
)
@click.option(
"--freq_rec",
"-fr",
type=int,
default=None,
help="Frequency at which to visualise reconstructions ",
)
@click.option(
"--freq_emb",
"-fe",
type=int,
default=None,
help="Frequency at which to visualise the latent " "space embedding.",
)
@click.option(
"--freq_int",
"-fi",
type=int,
default=None,
help="Frequency at which to visualise latent space"
"interpolations (default every 10 epochs).",
)
@click.option(
"--freq_dis",
"-ft",
type=int,
default=None,
help="Frequency at which to visualise single transversals.",
)
@click.option(
"--freq_pos",
"-fp",
type=int,
default=None,
help="Frequency at which to visualise pose.",
)
@click.option(
"--freq_sim",
"-fsim",
type=int,
default=None,
help="Frequency at which to visualise similarity matrix.",
)
@click.option(
"--freq_all",
"-fa",
type=int,
default=None,
help="Frequency at which to visualise all plots except loss. ",
)
@click.option(
"--opt_method",
"-opt",
type=str,
default=None,
help=" The method of optimisation. It can be adam/sgd/asgd",
)
@click.option(
"--gaussian_blur",
"-gb",
type=bool,
default=None,
is_flag=True,
help="Applying gaussian bluring to the image data which should help removing noise. The minimum and maximum for this is hardcoded.",
)
@click.option(
"--normalise",
"-nrm",
type=bool,
default=None,
is_flag=True,
help="Normalise data",
)
@click.option(
"--shift_min",
"-sftm",
type=bool,
default=None,
is_flag=True,
help="Shift the minimum of the data to one zero and the maximum to one",
)
@click.option(
"--rescale",
"-res",
type=int,
default=None,
is_flag=False,
help="Rescale images to given value (tuple, one value per dim).",
)
@click.option(
"--tensorboard",
"-tb",
type=bool,
default=None,
is_flag=True,
help="Log metrics and figures to tensorboard during training",
)
def run(
config_file,
datapath,
datatype,
restart,
state,
meta,
limit,
split,
no_val_drop,
affinity,
classes,
epochs,
batch,
depth,
channels,
filters,
latent_dims,
pose_dims,
bnorm_encoder,
bnorm_decoder,
klreduction,
beta,
beta_load,
gamma_load,
gamma,
learning,
loss_fn,
beta_min,
beta_cycle,
beta_ratio,
cyc_method_beta,
gamma_min,
gamma_cycle,
gamma_ratio,
cyc_method_gamma,
freq_eval,
freq_sta,
freq_emb,
freq_rec,
freq_int,
freq_dis,
freq_pos,
freq_acc,
freq_sim,
freq_all,
vis_rec,
vis_los,
vis_emb,
vis_int,
vis_dis,
vis_pos,
vis_pose_class,
vis_z_n_int,
vis_acc,
vis_cyc,
vis_aff,
vis_his,
vis_sim,
vis_all,
gpu,
eval,
dynamic,
model,
opt_method,
gaussian_blur,
normalise,
shift_min,
rescale,
tensorboard,
classifier,
new_out,
debug,
):
warnings.simplefilter("ignore", FutureWarning)
# read config file and command line arguments and assign to local variables that are used in the rest of the code
logging.info("Reading submission configuration file" + config_file)
local_vars = locals().copy()
data = load_config_params(config_file, local_vars)
if data["debug"]:
logging.info("Debug mode enabled")
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger("matplotlib.font_manager").disabled = True
# visualisation global settings defined from config file
setup_visualisation_config(data)
if data["new_out"]:
# dir_name = f'results_{settings.date_time_run}_model_{data["model"]}_lat{data["latent_dims"]}_pose{data["pose_dims"]}_lr{data["learning"]}_beta{data["beta"]}_gamma{data["gamma"]}'
dir_name = f'results_{settings.date_time_run}_model_{data["model"]}_lat{data["latent_dims"]}_pose{data["pose_dims"]}_dep{data["depth"]}_channels{data["channels"]}_lr{data["learning"]}_beta{data["beta"]}_gamma{data["gamma"]}'
if not os.path.exists(dir_name):
os.mkdir(dir_name)
os.chdir(dir_name)
if not os.path.exists("logs"):
os.mkdir("logs")
# setup logger inside the directory where we are running the code
fileh = logging.FileHandler(
"logs/avae_run_log_" + settings.date_time_run + ".log", "a"
)
logging.getLogger().addHandler(fileh)
logging.info(
"Saving final submission config file to: "
+ "avae_final_config"
+ settings.date_time_run
+ ".yaml"
)
write_config_file(settings.date_time_run, data)
try:
run_pipeline(data)
except Exception as e:
logging.exception("An exception was thrown!", e)
def run_pipeline(data):
if not data["eval"]:
train(
datapath=data["datapath"],
datatype=data["datatype"],
restart=data["restart"],
state=data["state"],
lim=data["limit"],
splt=data["split"],
batch_s=data["batch"],
no_val_drop=data["no_val_drop"],
affinity=data["affinity"],
classes=data["classes"],
epochs=data["epochs"],
channels=data["channels"],
depth=data["depth"],
filters=data["filters"],
lat_dims=data["latent_dims"],
pose_dims=data["pose_dims"],
bnorm_encoder=data["bnorm_encoder"],
bnorm_decoder=data["bnorm_decoder"],
klred=data["klreduction"],
learning=data["learning"],
beta_load=data["beta_load"],
beta_min=data["beta_min"],
beta_max=data["beta"],
beta_cycle=data["beta_cycle"],
beta_ratio=data["beta_ratio"],
cyc_method_beta=data["cyc_method_beta"],
gamma_load=data["gamma_load"],
gamma_min=data["gamma_min"],
gamma_max=data["gamma"],
gamma_cycle=data["gamma_cycle"],
gamma_ratio=data["gamma_ratio"],
cyc_method_gamma=data["cyc_method_gamma"],
recon_fn=data["loss_fn"],
use_gpu=data["gpu"],
model=data["model"],
opt_method=data["opt_method"],
gaussian_blur=data["gaussian_blur"],
normalise=data["normalise"],
shift_min=data["shift_min"],
rescale=data["rescale"],
tensorboard=data["tensorboard"],
classifier=data["classifier"],
)
else:
evaluate(
datapath=data["datapath"],
datatype=data["datatype"],
state=data["state"],
meta=data["meta"],
lim=data["limit"],
splt=data["split"],
batch_s=data["batch"],
classes=data["classes"],
use_gpu=data["gpu"],
gaussian_blur=data["gaussian_blur"],
normalise=data["normalise"],
shift_min=data["shift_min"],
rescale=data["rescale"],
classifier=data["classifier"],
pose_dims=data["pose_dims"], # ECP - added 3.06.24. Missing so can't turn off pose in evaluation
)
if __name__ == "__main__":
run()