-
Notifications
You must be signed in to change notification settings - Fork 1
/
train_vpp.py
executable file
·221 lines (182 loc) · 6.5 KB
/
train_vpp.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
#!/usr/bin/env python3
import argparse
import logging
from pathlib import Path
import numpy as np
import torch
import pinta.settings as settings
from pinta.data_processing import plot as plt
from pinta.data_processing.load import load_folder, load_sets
from pinta.data_processing.training_set import TrainingSetBundle
from pinta.data_processing.transforms import (
Normalize,
OffsetInputsOutputs,
SinglePrecision,
transform_factory,
)
from pinta.model.model_factory import model_factory
def run(args):
# Basic setup: get config and logger
params = settings.load(args.settings_path)
params.training.mixed_precision = args.amp
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(params.log)
log.setLevel(level=logging.INFO)
log.info("Settings:\n{}".format(params))
if not args.model_path:
# Generate a default name which describes the settings
args.model_path = "trained/" + settings.get_name(params) + ".pt"
dnn = model_factory(params, model_path=args.model_path)
# Load the dataset
dataframes = load_folder(
Path(args.data_path),
zero_mean_helm=False,
parallel_load=args.parallel,
max_number_sequences=args.max_number_sequences,
)
data_list = load_sets(dataframes, params)
training_bundle = TrainingSetBundle(data_list)
if params.data.statistics is None:
log.info("Updating the normalization statistics with the current data pool")
params.data.statistics = training_bundle.get_norm()
log.info(
"Loaded {} samples. Batch is {}".format(
len(training_bundle), params.data.train_batch_size
)
)
log.info("Available fields: {}".format(dataframes[0].columns.values))
# Data augmentation / preparation.
transforms = transform_factory(params)
# Adjust for a possible time offset requirement
offset_transform = list(
filter(lambda t: isinstance(t, OffsetInputsOutputs), transforms)
)
if len(offset_transform) > 0:
offset = offset_transform.pop().offset
log.info(
"Offset transform requested, adjusting the raw sequence length to {}".format(
params.trunk.seq_length + offset
)
)
params.trunk.seq_length += offset
# Train a new model from scratch if need be
if not dnn.valid:
log.info("Training a new model, this can take a while")
training_set, validation_set = training_bundle.get_dataloaders(
params,
transforms=transforms,
)
dnn.fit(training_set, validation_set, settings=params)
dnn.save(args.model_path)
if args.evaluate or args.plot:
# Generate linear test data
tester, split_indices = training_bundle.get_sequential_dataloader(
params["seq_length"],
transforms=[Normalize(*params.data.stats), SinglePrecision()],
batch_size=params.data.train_batch_size,
)
# Check the training
if args.evaluate:
log.info("Evaluating the model")
losses = dnn.evaluate(tester, params)
log.info("Final test Score: %.2f RMSE" % np.sqrt(sum(losses) / len(losses)))
# Compare visually the outputs
if args.plot:
# FIXME: @lefaudeux Timings are misaligned
log.info("---\nQuality evaluation:")
mean, std = params.data.statistics
# - prediction: go through the net, split the output sequence to re-align,
prediction = (
dnn.predict(
tester,
mean=mean.outputs,
std=std.outputs,
)
.detach()
.cpu()
.numpy()
)
# - de-whiten the data
std, mean = std.to(settings.device), mean.to(settings.device)
def denormalize(data: torch.Tensor):
# Broadcast the normalization factor to the hidden dimensions
return torch.add(
torch.mul(data, std.outputs),
mean.outputs,
)
reference = (
torch.cat([denormalize(batch.outputs[:, :, -1]) for batch in tester])
.detach()
.cpu()
.numpy()
)
# - limit the display to fewer samples
SAMPLES = 500
reference = reference[:SAMPLES]
prediction = prediction[:SAMPLES]
# - split back to restore the individual datasets
if len(split_indices) > 1:
prediction = np.split(prediction, split_indices)
reference = np.split(reference, split_indices)
else:
prediction = [prediction]
reference = [reference]
plt.parallel_plot(
reference + prediction,
[f"Ground truth {i}" for i in range(len(reference))]
+ [f"Prediction {i}" for i in range(len(prediction))],
title="Network predictions vs ground truth",
auto_open=True,
)
log.info("--Done")
if __name__ == "__main__":
parser = argparse.ArgumentParser("Generate VPP")
parser.add_argument(
"--data_path",
action="store",
help="path to the training data",
default="data",
)
parser.add_argument(
"--model_path",
action="store",
help="path to a saved model",
default=None,
)
parser.add_argument(
"--settings_path",
action="store",
help="path to the json settings for the run",
default=None,
)
parser.add_argument(
"--plot",
action="store_true",
help="generate a plot to visually compare the ground truth and predictions",
)
parser.add_argument(
"--amp",
action="store_true",
help="enable Pytorch Automatic Mixed Precision",
)
parser.add_argument(
"--parallel",
action="store_true",
help="Load muliple files in parallel. Errors may not be properly visible",
default=False,
)
parser.add_argument(
"--evaluate",
action="store_true",
help="Test a model against a new dataset",
default=False,
)
parser.add_argument(
"--max_number_sequences",
action="store",
help="Optionally limit the number of sequences to load from a data pool",
default=-1,
type=int,
)
args = parser.parse_args()
run(args)