[66326d]: / src / utils / training.py

Download this file

434 lines (376 with data), 13.2 kB

  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
"""
Contains functions for running hyperparameter sweep and
Continual Learning model-training and evaluation.
"""
import json
import warnings
from pathlib import Path
from functools import partial
# import random
# import numpy as np
import torch
from ray import tune
from torch import nn, optim
from avalanche.logging import InteractiveLogger, TensorboardLogger
from avalanche.training.plugins import EvaluationPlugin
from avalanche.training.plugins.early_stopping import EarlyStoppingPlugin
from avalanche.evaluation.metrics import (
accuracy_metrics,
loss_metrics,
StreamConfusionMatrix,
)
# Local imports
from utils import models, plotting, data_processing, cl_strategies
from utils.metrics import (
balancedaccuracy_metrics,
sensitivity_metrics,
specificity_metrics,
precision_metrics,
rocauc_metrics,
auprc_metrics,
)
# Suppressing erroneous MaxPool1d named tensors warning
warnings.filterwarnings("once", category=UserWarning)
# GLOBALS
RESULTS_DIR = Path(__file__).parents[1] / "results"
CONFIG_DIR = Path(__file__).parents[1] / "config"
CUDA = torch.cuda.is_available()
DEVICE = "cuda" if CUDA else "cpu"
# Reproducibility
SEED = 12345
# random.seed(SEED)
# np.random.seed(SEED)
torch.manual_seed(SEED)
def save_params(data, domain, outcome, model, strategy, best_params):
"""Save hyper-param config to json."""
file_loc = CONFIG_DIR / data / outcome / domain
file_loc.mkdir(parents=True, exist_ok=True)
with open(
file_loc / f"config_{model}_{strategy}.json", "w", encoding="utf-8"
) as json_file:
json.dump(best_params, json_file)
def load_params(data, domain, outcome, model, strategy):
"""Load hyper-param config from json."""
file_loc = CONFIG_DIR / data / outcome / domain
with open(
file_loc / f"config_{model}_{strategy}.json", encoding="utf-8"
) as json_file:
best_params = json.load(json_file)
return best_params
def save_results(data, outcome, domain, res):
"""Saves results to .json (excluding tensor confusion matrix)."""
with open(
RESULTS_DIR / f"results_{data}_{outcome}_{domain}.json", "w", encoding="utf-8"
) as handle:
res_no_tensors = {
m: {
s: [
{
metric: value
for metric, value in run.items()
if "Confusion" not in metric
}
for run in runs
]
for s, runs in strats.items()
}
for m, strats in res.items()
}
json.dump(res_no_tensors, handle)
def load_strategy(
model,
model_name,
strategy_name,
data="",
domain="",
n_tasks=0,
weight=None,
validate=False,
config=None,
benchmark=None,
early_stopping=False,
):
"""
- `stream` Avg accuracy over all experiences (may rely on tasks being roughly same size?)
- `experience` Accuracy for each experience
"""
strategy = cl_strategies.STRATEGIES[strategy_name]
criterion = nn.CrossEntropyLoss(weight=weight)
if config["generic"]["optimizer"] == "SGD":
optimizer = optim.SGD(
model.parameters(), lr=config["generic"]["lr"], momentum=0.9
)
elif config["generic"]["optimizer"] == "Adam":
optimizer = optim.Adam(model.parameters(), lr=config["generic"]["lr"])
if validate:
loggers = []
else:
timestamp = plotting.get_timestamp()
log_dir = (
RESULTS_DIR
/ "log"
/ "tensorboard"
/ f"{data}_{domain}_{timestamp}"
/ model_name
/ strategy_name
)
interactive_logger = InteractiveLogger()
tb_logger = TensorboardLogger(tb_log_dir=log_dir)
loggers = [interactive_logger, tb_logger]
eval_plugin = EvaluationPlugin(
StreamConfusionMatrix(save_image=False),
loss_metrics(stream=True, experience=not validate),
accuracy_metrics(trained_experience=True, stream=True, experience=not validate),
balancedaccuracy_metrics(
trained_experience=True, stream=True, experience=not validate
),
specificity_metrics(
trained_experience=True, stream=True, experience=not validate
),
sensitivity_metrics(
trained_experience=True, stream=True, experience=not validate
),
precision_metrics(
trained_experience=True, stream=True, experience=not validate
),
# rocauc_metrics(trained_experience=True, stream=True, experience=not validate),
# auprc_metrics(trained_experience=True, stream=True, experience=not validate),
loggers=loggers,
benchmark=benchmark,
)
if early_stopping:
early_stopping = EarlyStoppingPlugin(
patience=5,
val_stream_name="train_stream/Task000",
metric_name="BalancedAccuracy_On_Trained_Experiences",
)
plugins = [early_stopping]
else:
plugins = None
if strategy_name == "Joint":
eval_every = None
cl_strategy = strategy(
model,
optimizer=optimizer,
device=DEVICE,
criterion=criterion,
eval_mb_size=1024,
eval_every=0, # if validate or n_tasks > 5 else 1,
evaluator=eval_plugin,
train_epochs=15,
train_mb_size=config["generic"]["train_mb_size"],
plugins=plugins,
**config["strategy"],
)
return cl_strategy
def train_cl_method(cl_strategy, scenario, strategy_name, validate=False):
"""
Avalanche Cl training loop. For each 'experience' in scenario's train_stream:
- Trains method on experience
- evaluates model on train_stream and test_stream
"""
if not validate:
print("Starting experiment...")
if strategy_name == "Joint":
if not validate:
print(f"Joint training:")
cl_strategy.train(
scenario.train_stream,
eval_streams=[scenario.train_stream, scenario.test_stream],
)
if not validate:
print("Training completed", "\n\n")
else:
for experience in scenario.train_stream:
if not validate:
print(
f"{strategy_name} - Start of experience: {experience.current_experience}"
)
cl_strategy.train(
experience, eval_streams=[scenario.train_stream, scenario.test_stream]
)
if not validate:
print("Training completed", "\n\n")
if validate:
return cl_strategy.evaluator.get_last_metrics()
else:
return cl_strategy.evaluator.get_all_metrics()
def training_loop(
config,
data,
domain,
outcome,
model_name,
strategy_name,
validate=False,
checkpoint_dir=None,
):
"""
Training wrapper:
- loads data
- instantiates model
- equips model with CL strategy
- trains and evaluates method
- returns either results or hyperparam optimisation if `validate`
"""
# Loading data into 'stream' of 'experiences' (tasks)
if not validate:
print("Loading data...")
scenario, n_tasks, n_timesteps, n_channels, weight = data_processing.load_data(
data, domain, outcome, validate
)
if weight is not None:
weight = weight.to(DEVICE)
if not validate:
print("Data loaded.\n")
if not validate:
print(f"N timesteps: {n_timesteps}\nN features: {n_channels}")
model = models.MODELS[model_name](n_channels, n_timesteps, **config["model"])
cl_strategy = load_strategy(
model,
model_name,
strategy_name,
data,
domain,
n_tasks=n_tasks,
weight=weight,
validate=validate,
config=config,
benchmark=scenario,
)
results = train_cl_method(cl_strategy, scenario, strategy_name, validate=validate)
if validate:
loss = results["Loss_Stream/eval_phase/test_stream/Task000"]
accuracy = results[
"Accuracy_On_Trained_Experiences/eval_phase/test_stream/Task000"
]
balancedaccuracy = results[
"BalancedAccuracy_On_Trained_Experiences/eval_phase/test_stream/Task000"
]
# sensitivity = results['Sens_Stream/eval_phase/test_stream/Task000']
# specificity = results['Spec_Stream/eval_phase/test_stream/Task000']
# precision = results['Prec_Stream/eval_phase/test_stream/Task000']
# rocauc = results['ROCAUC_Stream/eval_phase/test_stream/Task000']
# auprc = results['AUPRC_Stream/eval_phase/test_stream/Task000']
# WARNING: `return` overwrites raytune report
tune.report(
loss=loss,
accuracy=accuracy,
balancedaccuracy=balancedaccuracy,
# auprc=auprc,
# rocauc=rocauc
)
else:
return results
def hyperparam_opt(
config, data, domain, outcome, model_name, strategy_name, num_samples
):
"""
Hyperparameter optimisation for the given model/strategy.
Runs over the validation data for the first 2 tasks.
"""
reporter = tune.CLIReporter(
metric_columns=[
"loss",
"accuracy",
"balancedaccuracy",
#'auprc',
#'rocauc'
]
)
resources = {"cpu": 4, "gpu": 0.5} if CUDA else {"cpu": 1}
result = tune.run(
partial(
training_loop,
data=data,
domain=domain,
outcome=outcome,
model_name=model_name,
strategy_name=strategy_name,
validate=True,
),
config=config,
num_samples=num_samples,
progress_reporter=reporter,
raise_on_failed_trial=False,
resources_per_trial=resources,
name=f"{model_name}_{strategy_name}",
local_dir=RESULTS_DIR / "log" / "raytune" / f"{data}_{outcome}_{domain}",
trial_name_creator=lambda t: f"{model_name}_{strategy_name}_{t.trial_id}",
)
best_trial = result.get_best_trial("balancedaccuracy", "max", "last")
print(f"Best trial config: {best_trial.config}")
print(
f"Best trial final validation loss: {best_trial.last_result['loss']}"
)
print(
f"Best trial final validation accuracy: {best_trial.last_result['accuracy']}"
)
print(
f"Best trial final validation balanced accuracy: {best_trial.last_result['balancedaccuracy']}"
)
return best_trial.config
def main(
data,
domain,
outcome,
models,
strategies,
dropout=False,
config_generic={},
config_model={},
config_cl={},
validate=False,
num_samples=50,
freeze_model_hp=False,
):
"""
Main training loop. Defines dataset given outcome/domain
and evaluates model/strategies over given hyperparams over this problem.
"""
# Container for metrics results
res = {m: {s: [] for s in strategies} for m in models}
for model in models:
for strategy in strategies:
# Garbage collection
torch.cuda.empty_cache()
if validate: # Hyperparam opt over first 2 tasks
# Load generic tuned hyper-params
if strategy == "Naive" or not freeze_model_hp:
config = {
"generic": config_generic,
"model": config_model[model],
"strategy": config_cl.get(strategy, {}),
}
else:
naive_params = load_params(data, domain, outcome, model, "Naive")
config = {
"generic": naive_params["generic"],
"model": naive_params["model"],
"strategy": config_cl.get(strategy, {}),
}
# JA: Investigate adding dropout to CNN (final FC layers only?)
if not dropout and model != "CNN":
config["model"]["dropout"] = 0
best_params = hyperparam_opt(
config,
data,
domain,
outcome,
model,
strategy,
num_samples=1 if strategy == "Naive" else num_samples,
)
save_params(data, domain, outcome, model, strategy, best_params)
else: # Training loop over all tasks
config = load_params(data, domain, outcome, model, strategy)
# Multiple runs for Confidence Intervals
n_repeats = 1
for _ in range(n_repeats):
curr_results = training_loop(
config, data, domain, outcome, model, strategy
)
res[model][strategy].append(curr_results)
if not validate:
save_results(data, outcome, domain, res)
plotting.plot_all_figs(data, domain, outcome)