-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
76 lines (70 loc) · 3.29 KB
/
train.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
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import (ModelCheckpoint, TensorBoard, ReduceLROnPlateau,
CSVLogger, EarlyStopping)
from model import get_model
import argparse
from datasets import ECGSequence
if __name__ == "__main__":
# Get data and train
parser = argparse.ArgumentParser(description='Train neural network.')
parser.add_argument('path_to_hdf5', type=str,
help='path to hdf5 file containing tracings')
parser.add_argument('path_to_csv', type=str,
help='path to csv file containing annotations')
parser.add_argument('--val_split', type=float, default=0.04,
help='number between 0 and 1 determining how much of'
' the data is to be used for validation. The remaining '
'is used for validation. Default: 0.02')
parser.add_argument('--dataset_name', type=str, default='tracings',
help='name of the hdf5 dataset containing tracings')
args = parser.parse_args()
# Optimization settings
loss = 'binary_crossentropy'
lr = 0.001
batch_size = 32
opt = Adam(lr)
callbacks = [ReduceLROnPlateau(monitor='val_loss',
factor=0.1,
patience=7,
min_lr=lr / 1000),
EarlyStopping(patience=9, # Patience should be larger than the one in ReduceLROnPlateau
min_delta=0.00001)
]
train_seq, valid_seq = ECGSequence.get_train_and_val(
args.path_to_hdf5, args.dataset_name, args.path_to_csv, batch_size, args.val_split)
# If you are continuing an interrupted section, uncomment line bellow:
# model = keras.models.load_model(PATH_TO_PREV_MODEL, compile=False)
model = get_model(train_seq.n_classes)
model.compile(loss=loss, optimizer=opt, metrics=['binary_accuracy'])
# Create log
callbacks += [TensorBoard(log_dir='./logs', write_graph=False),
CSVLogger('training.log', append=False)] # Change append to true if continuing training
# Save the BEST and LAST model
# callbacks += [ModelCheckpoint('./backup_model_last.hdf5'),
# ModelCheckpoint('./backup_model_best.hdf5', save_best_only=True)]
# Train neural network
history = model.fit(train_seq,
epochs=15,
initial_epoch=0, # If you are continuing a interrupted section change here
callbacks=callbacks,
validation_data=valid_seq,
verbose=1)
#绘制损失函数
import matplotlib.pyplot as plt
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# 绘制精度
plt.plot(history.history['binary_accuracy'])
plt.plot(history.history['val_binary_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# Save final result
model.save("./final_model.hdf5")