|
a |
|
b/train.py |
|
|
1 |
from tensorflow.keras.optimizers import Adam |
|
|
2 |
from tensorflow.keras.callbacks import (ModelCheckpoint, TensorBoard, ReduceLROnPlateau, |
|
|
3 |
CSVLogger, EarlyStopping) |
|
|
4 |
from model import get_model |
|
|
5 |
import argparse |
|
|
6 |
from datasets import ECGSequence |
|
|
7 |
|
|
|
8 |
if __name__ == "__main__": |
|
|
9 |
# Get data and train |
|
|
10 |
parser = argparse.ArgumentParser(description='Train neural network.') |
|
|
11 |
parser.add_argument('path_to_hdf5', type=str, |
|
|
12 |
help='path to hdf5 file containing tracings') |
|
|
13 |
parser.add_argument('path_to_csv', type=str, |
|
|
14 |
help='path to csv file containing annotations') |
|
|
15 |
parser.add_argument('--val_split', type=float, default=0.02, |
|
|
16 |
help='number between 0 and 1 determining how much of' |
|
|
17 |
' the data is to be used for validation. The remaining ' |
|
|
18 |
'is used for validation. Default: 0.02') |
|
|
19 |
parser.add_argument('--dataset_name', type=str, default='tracings', |
|
|
20 |
help='name of the hdf5 dataset containing tracings') |
|
|
21 |
args = parser.parse_args() |
|
|
22 |
# Optimization settings |
|
|
23 |
loss = 'binary_crossentropy' |
|
|
24 |
lr = 0.001 |
|
|
25 |
batch_size = 64 |
|
|
26 |
opt = Adam(lr) |
|
|
27 |
callbacks = [ReduceLROnPlateau(monitor='val_loss', |
|
|
28 |
factor=0.1, |
|
|
29 |
patience=7, |
|
|
30 |
min_lr=lr / 100), |
|
|
31 |
EarlyStopping(patience=9, # Patience should be larger than the one in ReduceLROnPlateau |
|
|
32 |
min_delta=0.00001)] |
|
|
33 |
|
|
|
34 |
train_seq, valid_seq = ECGSequence.get_train_and_val( |
|
|
35 |
args.path_to_hdf5, args.dataset_name, args.path_to_csv, batch_size, args.val_split) |
|
|
36 |
|
|
|
37 |
# If you are continuing an interrupted section, uncomment line bellow: |
|
|
38 |
# model = keras.models.load_model(PATH_TO_PREV_MODEL, compile=False) |
|
|
39 |
model = get_model(train_seq.n_classes) |
|
|
40 |
model.compile(loss=loss, optimizer=opt) |
|
|
41 |
# Create log |
|
|
42 |
callbacks += [TensorBoard(log_dir='./logs', write_graph=False), |
|
|
43 |
CSVLogger('training.log', append=False)] # Change append to true if continuing training |
|
|
44 |
# Save the BEST and LAST model |
|
|
45 |
callbacks += [ModelCheckpoint('./backup_model_last.hdf5'), |
|
|
46 |
ModelCheckpoint('./backup_model_best.hdf5', save_best_only=True)] |
|
|
47 |
# Train neural network |
|
|
48 |
history = model.fit(train_seq, |
|
|
49 |
epochs=70, |
|
|
50 |
initial_epoch=0, # If you are continuing a interrupted section change here |
|
|
51 |
callbacks=callbacks, |
|
|
52 |
validation_data=valid_seq, |
|
|
53 |
verbose=1) |
|
|
54 |
# Save final result |
|
|
55 |
model.save("./final_model.hdf5") |