-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEmotionRecognition.py
194 lines (157 loc) · 7.22 KB
/
EmotionRecognition.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
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
from __future__ import division, absolute_import
from os.path import isfile
from PIL import Image
import h5py
from Constants import *
from tensorflow import keras as k
import tensorflow as tf
from tensorflow.contrib.keras import layers, models, optimizers, metrics
class EmotionRecognition:
model = 0
def __init__(self):
pass
def build_network(self, number):
print('Building the CNN model')
#Model
self.model = k.models.Sequential()
#The selected network is trained
if number == '1':
self.olliNetwork()
elif number == '2':
self.optimizedNework()
elif number =='3':
self.fastNetwork()
elif number == '4':
self.olliNetwork()
print('Compile the model')
self.model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['categorical_accuracy'])
def full_training(self, number):
#Build the CNN network
self.build_network(number)
#Generate a test dataset form the images
train_set, validation_set = self.generate_test_data()
#Start the training
print('Training....')
#self.model.fit(train_set, epochs=nb_epoch, batch_size=BATCH_SIZE, validation_split=0.1, shuffle=True, verbose=1)
self.model.fit_generator(train_set,
steps_per_epoch=int(7307 / BATCH_SIZE),
epochs=EPOCHS,
verbose=1,
validation_steps=1025,
validation_data=validation_set)
print('Training finished')
# Show the result of the model
#loss_and_metrics = self.model.evaluate(train_set, batch_size=BATCH_SIZE, verbose=1)
#print('Training Results:')
#print('Loss: ', loss_and_metrics[0])
#print('Acc: ', loss_and_metrics[1])
def generate_test_data(self):
# TODO train and testset spit
#train_gen, test_gen = sk.train_test_split(train_gen, test_size=0.2)
#Get a list of all images and split into train an test set
#Image_List = glob.glob(os.path.join('data/train', '*.png'))
#train_samples, validation_samples = train_test_split(Image_List, test_size=0.1)
# Load the training data
# this is the augmentation configuration we will use for training
train_data_gen = k.preprocessing.image.ImageDataGenerator(
rescale=1. / 255.
)
test_data_gen = k.preprocessing.image.ImageDataGenerator(
rescale=1. / 255.
)
train_gen = train_data_gen.flow_from_directory(
"data/train",
target_size=(SIZE_FACE, SIZE_FACE),
batch_size=BATCH_SIZE,
class_mode="categorical",
color_mode="grayscale"
)
test_gen = test_data_gen.flow_from_directory(
"data/test",
target_size=(SIZE_FACE, SIZE_FACE),
batch_size=BATCH_SIZE,
class_mode="categorical",
color_mode="grayscale"
)
return (train_gen, test_gen)
def predict(self, image):
if image is None:
return None
image = image.reshape([-1, SIZE_FACE, SIZE_FACE, 1])
return self.model.predict(image)
def save_model(self, filename):
filepath = MODEL_DIRECTORY + filename + '.h5'
k.models.save_model(self.model, filepath)
print('[+] Model trained and saved at ' + MODEL_DIRECTORY + filename)
def load_model(self, filename):
print('Model loaded from ' + MODEL_DIRECTORY + filename + '.h5')
if isfile(MODEL_DIRECTORY + filename + '.h5'):
self.model = k.models.load_model(MODEL_DIRECTORY + filename + '.h5')
else:
print('Model could not be loaded')
#loss: 0.3298 - categorical_accuracy: 0.8690 - val_loss: 0.3960 - val_categorical_accuracy: 0.8442
def olliNetwork(self):
self.model = models.Sequential()
self.model.add(layers.Conv2D(64, (5, 5), activation='relu', input_shape=(48, 48, 1)))
self.model.add(layers.Conv2D(64, (5, 5), activation='relu'))
self.model.add(layers.MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
self.model.add(layers.Dropout(0.25))
self.model.add(layers.Conv2D(64, (5, 5), activation='relu'))
self.model.add(layers.Conv2D(64, (5, 5), activation='relu'))
self.model.add(layers.MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
self.model.add(layers.Dropout(0.25))
self.model.add(layers.Conv2D(128, (4, 4), activation='relu'))
self.model.add(layers.MaxPooling2D(pool_size=(2, 2)))
self.model.add(layers.Dropout(0.25))
self.model.add(layers.Flatten())
self.model.add(layers.Dense(3072, activation='relu'))
self.model.add(layers.Dropout(0.5))
self.model.add(layers.Dense(128, activation='relu'))
self.model.add(layers.Dropout(0.5))
self.model.add(layers.Dense(3, activation='softmax'))
# loss: 0.3352 - acc: 0.75
def optimizedNework(self):
self.model.add(layers.Conv2D(filters=16, kernel_size=(7, 7), padding='same', name='image_array', input_shape=(SIZE_FACE, SIZE_FACE, 1)))
self.model.add(layers.BatchNormalization())
self.model.add(layers.Convolution2D(filters=16, kernel_size=(7, 7), padding='same'))
self.model.add(layers.BatchNormalization())
self.model.add(layers.Activation('relu'))
self.model.add(layers.AveragePooling2D(pool_size=(2, 2), padding='same'))
self.model.add(layers.Dropout(.5))
self.model.add(layers.Conv2D(filters=32, kernel_size=(5, 5), padding='same'))
self.model.add(layers.BatchNormalization())
self.model.add(layers.Convolution2D(filters=32, kernel_size=(5, 5), padding='same'))
self.model.add(layers.BatchNormalization())
self.model.add(layers.Activation('relu'))
self.model.add(layers.AveragePooling2D(pool_size=(2, 2), padding='same'))
self.model.add(layers.Dropout(.5))
self.model.add(layers.Conv2D(filters=64, kernel_size=(3, 3), padding='same'))
self.model.add(layers.BatchNormalization())
self.model.add(layers.Conv2D(filters=64, kernel_size=(3, 3), padding='same'))
self.model.add(layers.BatchNormalization())
self.model.add(layers.Activation('relu'))
self.model.add(layers.AveragePooling2D(pool_size=(2, 2), padding='same'))
self.model.add(layers.Dropout(.5))
self.model.add(layers.Conv2D(filters=128, kernel_size=(3, 3), padding='same'))
self.model.add(layers.BatchNormalization())
self.model.add(layers.Convolution2D(filters=128, kernel_size=(3, 3), padding='same'))
self.model.add(layers.BatchNormalization())
self.model.add(layers.Activation('relu'))
self.model.add(layers.AveragePooling2D(pool_size=(2, 2), padding='same'))
self.model.add(layers.Dropout(.5))
self.model.add(layers.Conv2D(filters=256, kernel_size=(3, 3), padding='same'))
self.model.add(layers.BatchNormalization())
self.model.add(layers.Conv2D(filters=3, kernel_size=(3, 3), padding='same'))
self.model.add(layers.GlobalAveragePooling2D())
self.model.add(layers.Activation('softmax', name='predictions'))
#loss: 0.3352 - acc: 0.8642 - val_loss: 0.5588 - val_acc: 0.7708
def fastNetwork(self):
self.model.add(k.layers.Conv2D(32, 3, 3, input_shape=(48, 48, 1)))
self.model.add(k.layers.Activation('relu'))
self.model.add(k.layers.MaxPooling2D(pool_size=(2, 2)))
self.model.add(k.layers.Flatten())
self.model.add(k.layers.Dense(128, kernel_initializer='lecun_uniform'))
self.model.add(k.layers.Dropout(0.4))
self.model.add(k.layers.Activation('relu'))
self.model.add(k.layers.Dense(3))
self.model.add(k.layers.Activation('softmax'))