train.py 3.53 KB
Newer Older
1
"""
2
Train our RNN on extracted features or images.
3
4
5
6
7
"""
from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping, CSVLogger
from models import ResearchModels
from data import DataSet
import time
Matt Harvey's avatar
Matt Harvey committed
8
import os.path
9
10

def train(data_type, seq_length, model, saved_model=None,
11
          class_limit=None, image_shape=None,
Matt Harvey's avatar
Matt Harvey committed
12
          load_to_memory=False, batch_size=32, nb_epoch=100):
13
14
    # Helper: Save the model.
    checkpointer = ModelCheckpoint(
Matt Harvey's avatar
Matt Harvey committed
15
        filepath=os.path.join('data', 'checkpoints', model + '-' + data_type + \
Matt Harvey's avatar
Matt Harvey committed
16
            '.{epoch:03d}-{val_loss:.3f}.hdf5'),
17
18
19
20
        verbose=1,
        save_best_only=True)

    # Helper: TensorBoard
21
    tb = TensorBoard(log_dir=os.path.join('data', 'logs', model))
22
23

    # Helper: Stop when we stop learning.
Matt Harvey's avatar
Matt Harvey committed
24
    early_stopper = EarlyStopping(patience=5)
25
26
27

    # Helper: Save results.
    timestamp = time.time()
Matt Harvey's avatar
Matt Harvey committed
28
    csv_logger = CSVLogger(os.path.join('data', 'logs', model + '-' + 'training-' + \
Matt Harvey's avatar
Matt Harvey committed
29
        str(timestamp) + '.log'))
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

    # Get the data and process it.
    if image_shape is None:
        data = DataSet(
            seq_length=seq_length,
            class_limit=class_limit
        )
    else:
        data = DataSet(
            seq_length=seq_length,
            class_limit=class_limit,
            image_shape=image_shape
        )

    # Get samples per epoch.
    # Multiply by 0.7 to attempt to guess how much of data.data is the train set.
Matt Harvey's avatar
Matt Harvey committed
46
    steps_per_epoch = (len(data.data) * 0.7) // batch_size
47

48
49
    if load_to_memory:
        # Get data.
50
51
        X, y = data.get_all_sequences_in_memory('train', data_type)
        X_test, y_test = data.get_all_sequences_in_memory('test', data_type)
52
53
    else:
        # Get generators.
54
55
        generator = data.frame_generator(batch_size, 'train', data_type)
        val_generator = data.frame_generator(batch_size, 'test', data_type)
56
57
58
59
60

    # Get the model.
    rm = ResearchModels(len(data.classes), model, seq_length, saved_model)

    # Fit!
61
62
63
64
65
66
67
68
    if load_to_memory:
        # Use standard fit.
        rm.model.fit(
            X,
            y,
            batch_size=batch_size,
            validation_data=(X_test, y_test),
            verbose=1,
69
            callbacks=[tb, early_stopper, csv_logger],
Matt Harvey's avatar
Matt Harvey committed
70
            epochs=nb_epoch)
71
72
73
74
    else:
        # Use fit generator.
        rm.model.fit_generator(
            generator=generator,
Matt Harvey's avatar
Matt Harvey committed
75
76
            steps_per_epoch=steps_per_epoch,
            epochs=nb_epoch,
77
            verbose=1,
Matt Harvey's avatar
Matt Harvey committed
78
            callbacks=[tb, early_stopper, csv_logger, checkpointer],
79
            validation_data=val_generator,
80
81
            validation_steps=40,
            workers=4)
82
83
84
85

def main():
    """These are the main training settings. Set each before running
    this file."""
86
    # model can be one of lstm, lrcn, mlp, conv_3d, c3d
87
    model = 'lstm'
88
    saved_model = None  # None or weights file
89
    class_limit = 10  # int, can be 1-101 or None
Matt Harvey's avatar
Matt Harvey committed
90
    seq_length = 40
Matt Harvey's avatar
Matt Harvey committed
91
92
93
    load_to_memory = False  # pre-load the sequences into memory
    batch_size = 32
    nb_epoch = 1000
Matt Harvey's avatar
Matt Harvey committed
94
95

    # Chose images or features and image shape based on network.
96
    if model in ['conv_3d', 'c3d', 'lrcn']:
Matt Harvey's avatar
Matt Harvey committed
97
        data_type = 'images'
Matt Harvey's avatar
Matt Harvey committed
98
        image_shape = (80, 80, 3)
99
    elif model in ['lstm', 'mlp']:
Matt Harvey's avatar
Matt Harvey committed
100
101
102
        data_type = 'features'
        image_shape = None
    else:
103
        raise ValueError("Invalid model. See train.py for options.")
104
105

    train(data_type, seq_length, model, saved_model=saved_model,
106
          class_limit=class_limit, image_shape=image_shape,
Matt Harvey's avatar
Matt Harvey committed
107
          load_to_memory=load_to_memory, batch_size=batch_size, nb_epoch=nb_epoch)
108
109
110

if __name__ == '__main__':
    main()