To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

train_model.py 10.5 KB
Newer Older
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
"""
Stephan Wegner & Vithurjan Visuvalingam
pdz, ETH Zürich
2020

This file contains all functions to train the proposal NN
"""
print('start train proposal NN')

import numpy as np
import pandas as pd
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import optimizers, regularizers
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Dense, Dropout, Conv3D, MaxPooling3D, BatchNormalization
from tensorflow.keras.backend import set_session
from time import gmtime, strftime
import random
import argparse
import os
import sys
import math
import proposal_model as pm

i=0
while i<=3:
    os.chdir(os.path.dirname(os.getcwd()))
    i+=1
sys.path.append(os.getcwd())
from definitions import ROOT_DIR
from definitions import train_val_nums
from src.ThreeDCNN.models.data_generator.ThreeDimCNN_datagenerator import ThreeDimCNN_datagenerator

#set tensorflow configuration
config = tf.ConfigProto(
    gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.4)
    # device_count = {'GPU': 1}
)
config.gpu_options.allow_growth = True
session = tf.Session(config=config)
set_session(session)

# paths to load and store data
path_to_id_label_mapping = ROOT_DIR + "\\" + r"data\datasets\proposal_NN\train_val_d_classification_dataset.csv"
path_to_store_model = ROOT_DIR + "\\" + r"models\ThreeDCNN\proposal_NN"
path_to_store_figures = ROOT_DIR + "\\" + r"reports\figures"

# load id label mapping
df_id_label_map = pd.read_csv(path_to_id_label_mapping)

ids = list(df_id_label_map['ids']) #ids: video-num_frame-time[ms]_segment-length
labels = list(df_id_label_map['labels']) #labels: 0,1,2,3 (BG, Guiding, Directing, Observing)

# create labels dictionary
dict_labels = dict(zip(ids, labels))

triple_ids = [ID.split('_') for ID in ids] #triple_ids[i] = ['num_video', 'start_time_segment', 'segment_length']
num_triple_ids = [[float(a), float(b), float(c)] for [a, b, c] in triple_ids] #convert string to float
s_num_triple_ids = sorted(num_triple_ids)
sorted_ids = [f"{int(a)}" + "_" + f"{float(b)}" + "_" + f"{int(c)}" for [a, b, c] in s_num_triple_ids]
sorted_labels = [dict_labels[ID] for ID in sorted_ids]

sorted_ids.reverse()
sorted_labels.reverse()

ids = sorted_ids
labels = sorted_labels

#### check for k-fold cross validation ####

# sort the  background and activity segments
index_label_0 = [i for i in range(len(labels)) if labels[i] == 0] #store position of every segment in list of labels with label 0, e.g. [0,1,2,3,21,...]
index_label_1 = [i for i in range(len(labels)) if labels[i] > 0] #store position of every segment in list of labels with label > 0

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='train classification NN')
    parser.add_argument('--filter')
    parser.add_argument('--kernel')
    parser.add_argument('--optimizer')
    parser.add_argument('--activation')
    parser.add_argument('--weight')
    parser.add_argument('--start')
    parser.add_argument('--end')
    argument= parser.parse_args()

    # create the training and validation set
    config = tf.ConfigProto(
        gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.4)
    )
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config)
    set_session(session)

    start = float(argument.start) #if k =5, start=[0.01, 0.21, 0.41, 0.61, 0.81]
    end = float(argument.end)

    val_0 = index_label_0[int(len(index_label_0)*start):int(len(index_label_0)*end)]
    train_0_1 = index_label_0[:int(len(index_label_0)*start)]
    train_0_2 = index_label_0[int(len(index_label_0)*end):]

    val_1 = index_label_1[int(len(index_label_1)*start):int(len(index_label_1)*end)]
    train_1_1 = index_label_1[:int(len(index_label_1) * start)]
    train_1_2 = index_label_1[int(len(index_label_1) * end):]

    val_indexes = val_0 + val_1
    train_indexes = train_0_1 + train_0_2 + train_1_1 + train_1_2

    train_ids = [ids[i] for i in train_indexes]
    val_ids = [ids[i] for i in val_indexes]

    random.shuffle(train_ids)
    random.shuffle(val_ids)

    len_val0 = len(val_0)
    len_val1 = len(val_1)
    cw = [len_val0, len_val1]
    cw_0 = float(max(cw) / len_val0)
    cw_1 = float(max(cw) / len_val1)

    print("cw's:", cw_0, cw_1)
    print('len training set', len(train_0_1) + len(train_0_2), len(train_1_1) + len(train_1_2))
    print('len val set', len_val0, len_val1)

    # create partition dictionary
    dict_partition = {}
    dict_partition['train'] = train_ids
    dict_partition['validation'] = val_ids

    # create the parameters for the train, validation and test generators
    params = {'dim_feature_sequence': (16, 128, 128, 3),
              'batch_size': 10,
              'n_classes': 2,
              'shuffle': False}

    # create the train, validation and test generator
    training_generator = ThreeDimCNN_datagenerator(dict_partition['train'], dict_labels, **params)
    validation_generator = ThreeDimCNN_datagenerator(dict_partition['validation'], dict_labels, **params)

    # different optimizers
    sgd1 = optimizers.SGD(lr=0.01, decay=0.05, momentum=0.9, nesterov=True)  # momentum = 0.9 is standard value, keep
    sgd = optimizers.SGD(lr=0.001, decay=0.005, momentum=0.9, nesterov=True)
    rmsprop = optimizers.RMSprop(learning_rate=0.001, rho=0.9)
    adam = optimizers.Adam(learning_rate=0.00001, beta_1=0.9, beta_2=0.999, amsgrad=False, clipnorm=5)
    adagrad = optimizers.Adagrad(learning_rate=0.001, initial_accumulator_value=0.1, epsilon=1e-7, clipnorm=10)  # well suited for sparse data

    optimizer = [sgd1, sgd, rmsprop, adam, adagrad]

    filter_base = int(argument.filter)
    kernel_base = int(argument.kernel)
    optimizer = optimizer[int(argument.optimizer)]


    activation='relu'
    initializer = tf.keras.initializers.he_normal()  # activation = 'relu'

    regularizer = regularizers.l1_l2(l1=1e-4, l2=1e-4)

    # Create the model
    model = pm.directing_model(filter_base=filter_base, kernel_base=kernel_base, activation=activation,
                                   initializer=initializer, regularizer=regularizer, optimizer=optimizer)

    class_weight = {0: cw_0*cw_0*cw_0,
                    1: cw_1*cw_1*cw_1
                    }
    print('class weight', class_weight)
    def scheduler(epoch, learning_rate):
        if epoch < 50:
            return learning_rate
        else:
            learning_rate = learning_rate * math.exp(-0.1)
            return learning_rate

    callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, min_delta=0, restore_best_weights=True)
    lr_scheduler = tf.keras.callbacks.LearningRateScheduler(scheduler)

    # train the model and save the history data
    history = model.fit_generator(generator=training_generator,
                                  validation_data=validation_generator,
                                  use_multiprocessing=True,
                                  epochs=50,
                                  workers=0,
                                  class_weight=class_weight,
                                  callbacks= [callback, lr_scheduler]
                                  )

    time = strftime("%Y%b%d_%H%M", gmtime())

    identifier = str(start) + '-' + str(filter_base) + '-' + str(kernel_base) + '-' + str(
        argument.optimizer) + '-' + str(argument.activation) + '-' + str(argument.weight)
    print(identifier)

    # plot the training performance
    plt.plot(history.history['categorical_accuracy'])
    plt.plot(history.history['val_categorical_accuracy'])
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'val'], loc='upper left')
    plt.savefig(path_to_store_figures + f"\\acc\\" +'prop_'+ time + '_' + identifier + "_acc_small.png")
    plt.clf()

    # summarize history for loss
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'val'], loc='upper left')
    # plt.show()
    plt.savefig(path_to_store_figures + f"\\loss\\" +'prop_'+ time + '_' + identifier + f"_loss_small.png")
    plt.clf()

    # get the loss and accuracy of the model
    loss, acc = model.evaluate_generator(generator=validation_generator, use_multiprocessing=True, workers=0)

    # print the confusion matrix and classification report of the model performance
    Y_pred = model.predict_generator(validation_generator)
    y_pred = np.argmax(Y_pred, axis=1)
    target_names = ['Background', 'Action']

    Ypred_0 = []
    for i in range(len(Y_pred)):
        Ypred_0.append(Y_pred[i][0])
    Ypred_1 = []
    for i in range(len(Y_pred)):
        Ypred_1.append(Y_pred[i][1])


    y_true = []
    for i in range(int(len(y_pred) / params['batch_size'])):
        temp = []
        for j in range(params['batch_size']):
            temp = np.append(temp, int(np.argmax(validation_generator[i][1][j])))
        y_true = np.append(y_true, temp)

    t_dict = {'labels pred': y_pred, 'labels true': y_true, 'val id': val_ids[:len(y_pred)], 'value pred 0': Ypred_0,
              'value pred 1': Ypred_1}
    df = pd.DataFrame(t_dict)
    df.to_csv(
        path_to_store_figures + f"\\ComparisonPredTrue\\" +'prop_'+ time + '_' + identifier + r'classification_predictions-true.csv',
        sep=',', index=False)

    plt.figure(figsize=[10.0, 6.3])
    plt.cool()
    plt.plot(y_true, 'b*')
    plt.plot(y_pred, 'r+')
    plt.title('comparison pred vs true')
    plt.ylabel('label')
    plt.xlabel('sequence')
    plt.legend(['y_true', 'y_pred'])  # , loc='upper left')
    # plt.show()
    plt.savefig(path_to_store_figures + f"\\ComparisonPredTrue\\" +'prop_'+ time + '_' + identifier + f"_loss_small.png")
    plt.clf()

    print('acc', i, acc)
    print('loss', i, loss)

    print('Confusion Matrix')
    conv_mat = confusion_matrix(y_true, y_pred, labels=[0, 1])
    print(conv_mat)  # target_names ))
    df_conv = pd.DataFrame.from_dict(conv_mat)
    df_conv.to_csv(path_to_store_figures + f"\\ConfusionMat\\" + 'prop_' + time + '_' + identifier + f".csv")

    print('Classification Report')
    class_rep = classification_report(y_true, y_pred, target_names=target_names)
    print(class_rep)
    path = path_to_store_figures + f"\\ClassificationRep\\" +'prop_'+ time + '_' + identifier + f".txt"
    text_file = open(path, 'w')
    n = text_file.write(class_rep)
    text_file.close()

    # save the model
    model.save(path_to_store_model + "\\" + str(i) + 'i_' + r'TCNN_prop_acc_' + str(acc) + '.h5',
               include_optimizer=True)
    del model
    del history