|
a |
|
b/Code/emotion_recognition.py |
|
|
1 |
from keras.callbacks import CSVLogger, ModelCheckpoint, EarlyStopping |
|
|
2 |
from keras.callbacks import ReduceLROnPlateau |
|
|
3 |
from keras.preprocessing.image import ImageDataGenerator |
|
|
4 |
from load_and_process import load_fer2013 |
|
|
5 |
from load_and_process import preprocess_input |
|
|
6 |
from models.cnn import mini_XCEPTION |
|
|
7 |
from sklearn.model_selection import train_test_split |
|
|
8 |
|
|
|
9 |
# parameters |
|
|
10 |
batch_size = 32 |
|
|
11 |
num_epochs = 10000 |
|
|
12 |
input_shape = (48, 48, 1) |
|
|
13 |
validation_split = .2 |
|
|
14 |
verbose = 1 |
|
|
15 |
num_classes = 7 |
|
|
16 |
patience = 50 |
|
|
17 |
base_path = 'models/' |
|
|
18 |
|
|
|
19 |
# data generator |
|
|
20 |
data_generator = ImageDataGenerator( |
|
|
21 |
featurewise_center=False, |
|
|
22 |
featurewise_std_normalization=False, |
|
|
23 |
rotation_range=10, |
|
|
24 |
width_shift_range=0.1, |
|
|
25 |
height_shift_range=0.1, |
|
|
26 |
zoom_range=.1, |
|
|
27 |
horizontal_flip=True) |
|
|
28 |
|
|
|
29 |
# model parameters/compilation |
|
|
30 |
model = mini_XCEPTION(input_shape, num_classes) |
|
|
31 |
model.compile(optimizer='adam', loss='categorical_crossentropy', |
|
|
32 |
metrics=['accuracy']) |
|
|
33 |
model.summary() |
|
|
34 |
|
|
|
35 |
|
|
|
36 |
|
|
|
37 |
|
|
|
38 |
|
|
|
39 |
# callbacks |
|
|
40 |
log_file_path = base_path + '_emotion_training.log' |
|
|
41 |
csv_logger = CSVLogger(log_file_path, append=False) |
|
|
42 |
early_stop = EarlyStopping('val_loss', patience=patience) |
|
|
43 |
reduce_lr = ReduceLROnPlateau('val_loss', factor=0.1, |
|
|
44 |
patience=int(patience/4), verbose=1) |
|
|
45 |
trained_models_path = base_path + '_mini_XCEPTION' |
|
|
46 |
model_names = trained_models_path + '.{epoch:02d}-{val_acc:.2f}.hdf5' |
|
|
47 |
model_checkpoint = ModelCheckpoint(model_names, 'val_loss', verbose=1, |
|
|
48 |
save_best_only=True) |
|
|
49 |
callbacks = [model_checkpoint, csv_logger, early_stop, reduce_lr] |
|
|
50 |
|
|
|
51 |
# loading dataset |
|
|
52 |
faces, emotions = load_fer2013() |
|
|
53 |
faces = preprocess_input(faces) |
|
|
54 |
num_samples, num_classes = emotions.shape |
|
|
55 |
xtrain, xtest,ytrain,ytest = train_test_split(faces, emotions,test_size=0.2,shuffle=True) |
|
|
56 |
model.fit_generator(data_generator.flow(xtrain, ytrain, |
|
|
57 |
batch_size), |
|
|
58 |
steps_per_epoch=len(xtrain) / batch_size, |
|
|
59 |
epochs=num_epochs, verbose=1, callbacks=callbacks, |
|
|
60 |
validation_data=(xtest,ytest)) |