-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
244 lines (196 loc) · 8.69 KB
/
main.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
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
import MachineLearningUtils
from NetworkModels import VGGModel
import argparse
import numpy as np
import pandas as pd
import tensorflow as tf
from keras import backend as K
from keras.applications.vgg16 import VGG16
from keras.layers import Dense, Dropout, Input
from keras.models import Model
from keras.models import Sequential
from keras.optimizers import Adamax
from keras.utils import np_utils
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import utils
from tensorflow.python.saved_model import tag_constants, signature_constants
from tensorflow.python.saved_model.signature_def_utils_impl import build_signature_def, predict_signature_def
from tensorflow.contrib.session_bundle import exporter
NUM_CLASSES = 7
IMG_SIZE = 48
# TODO: Use the 'Usage' field to separate based on training/testing
TRAIN_END = 28708
TEST_START = TRAIN_END + 1
def split_for_test(list):
train = list[0:TRAIN_END]
test = list[TEST_START:]
return train, test
def pandas_vector_to_list(pandas_df):
py_list = [item[0] for item in pandas_df.values.tolist()]
return py_list
def process_emotion(emotion):
"""
Takes in a vector of emotions and outputs a list of emotions as one-hot vectors.
:param emotion: vector of ints (0-7)
:return: list of one-hot vectors (array of 7)
"""
emotion_as_list = pandas_vector_to_list(emotion)
y_data = []
for index in range(len(emotion_as_list)):
y_data.append(emotion_as_list[index])
# Y data
y_data_categorical = np_utils.to_categorical(y_data, NUM_CLASSES)
return y_data_categorical
def process_pixels(pixels, img_size=IMG_SIZE):
"""
Takes in a string (pixels) that has space separated ints. Will transform the ints
to a 48x48 matrix of floats(/255).
:param pixels: string with space separated ints
:param img_size: image size
:return: array of 48x48 matrices
"""
pixels_as_list = pandas_vector_to_list(pixels)
np_image_array = []
for index, item in enumerate(pixels_as_list):
# 48x48
data = np.zeros((img_size, img_size), dtype=np.uint8)
# split space separated ints
pixel_data = item.split()
# 0 -> 47, loop through the rows
for i in range(0, img_size):
# (0 = 0), (1 = 47), (2 = 94), ...
pixel_index = i * img_size
# (0 = [0:47]), (1 = [47: 94]), (2 = [94, 141]), ...
data[i] = pixel_data[pixel_index:pixel_index + img_size]
np_image_array.append(np.array(data))
np_image_array = np.array(np_image_array)
# convert to float and divide by 255
np_image_array = np_image_array.astype('float32') / 255.0
return np_image_array
def get_vgg16_output(vgg16, array_input, n_feature_maps):
vg_input = duplicate_input_layer(array_input, n_feature_maps)
picture_train_features = vgg16.predict(vg_input)
del (vg_input)
feature_map = np.empty([n_feature_maps, 512])
for idx_pic, picture in enumerate(picture_train_features):
feature_map[idx_pic] = picture
return feature_map
def duplicate_input_layer(array_input, size):
vg_input = np.empty([size, 48, 48, 3])
for index, item in enumerate(vg_input):
item[:, :, 0] = array_input[index]
item[:, :, 1] = array_input[index]
item[:, :, 2] = array_input[index]
return vg_input
def main():
# used to get the session/graph data from keras
K.set_learning_phase(0)
# get the data in a Pandas dataframe
raw_data = pd.read_csv('./Data/fer2013.csv')
print('Loaded Data')
# convert to one hot vectors
emotion_array = process_emotion(raw_data[['emotion']])
# convert to a 48x48 float matrix
pixel_array = process_pixels(raw_data[['pixels']])
# split for test/train
y_train, y_test = split_for_test(emotion_array)
x_train_matrix, x_test_matrix = split_for_test(pixel_array)
n_train = int(len(x_train_matrix))
n_test = int(len(x_test_matrix))
x_train_input = duplicate_input_layer(x_train_matrix, n_train)
x_test_input = duplicate_input_layer(x_test_matrix, n_test)
# vgg 16. include_top=False so the output is the 512 and use the learned weights
vgg16 = VGG16(include_top=False, input_shape=(48, 48, 3), pooling='avg', weights='imagenet')
# get vgg16 outputs
x_train_feature_map = get_vgg16_output(vgg16, x_train_matrix, n_train)
x_test_feature_map = get_vgg16_output(vgg16, x_test_matrix, n_test)
# build and train model
top_layer_model = Sequential()
top_layer_model.add(Dense(256, input_shape=(512,), activation='relu'))
top_layer_model.add(Dense(256, input_shape=(256,), activation='relu'))
top_layer_model.add(Dropout(0.5))
top_layer_model.add(Dense(128, input_shape=(256,)))
top_layer_model.add(Dense(NUM_CLASSES, activation='softmax'))
adamax = Adamax()
top_layer_model.compile(loss='categorical_crossentropy',
optimizer=adamax, metrics=['accuracy'])
# train
top_layer_model.fit(x_train_feature_map, y_train,
validation_data=(x_train_feature_map, y_train),
nb_epoch=1, batch_size=25)
# Evaluate
score = top_layer_model.evaluate(x_test_feature_map,
y_test, batch_size=25)
print("After top_layer_model training (test set): {}".format(score))
# Merge two models and create the final_model_final_final
inputs = Input(shape=(48, 48, 3))
vg_output = vgg16(inputs)
print("vg_output: {}".format(vg_output.shape))
# TODO: the 'pooling' argument of the VGG16 model is important for this to work otherwise you will have to squash
# output from (?, 1, 1, 512) to (?, 512)
model_predictions = top_layer_model(vg_output)
final_model = Model(input=inputs, output=model_predictions)
final_model.compile(loss='categorical_crossentropy',
optimizer=adamax, metrics=['accuracy'])
final_model_score = final_model.evaluate(x_train_input,
y_train, batch_size=25)
print("Sanity check - final_model (train score): {}".format(final_model_score))
final_model_score = final_model.evaluate(x_test_input,
y_test, batch_size=25)
print("Sanity check - final_model (test score): {}".format(final_model_score))
# config = final_model.get_config()
# weights = final_model.get_weights()
# probably don't need to create a new model
# model_to_save = Model.from_config(config)
# model_to_save.set_weights(weights)
model_to_save = final_model
print("Model input name: {}".format(model_to_save.input))
print("Model output name: {}".format(model_to_save.output))
# # Save Model
# builder = saved_model_builder.SavedModelBuilder(FLAGS.export_path)
# signature = predict_signature_def(inputs={'images': model_to_save.input},
# outputs={'scores': model_to_save.output})
# with K.get_session() as sess:
# builder.add_meta_graph_and_variables(sess=sess,
# tags=[tag_constants.SERVING],
# signature_def_map={'predict': signature})
# builder.save()
if __name__ == '__main__':
main()
# image_loader = MachineLearningUtils.ImageLoader()
# data_transformer = MachineLearningUtils.DataTransformer()
#
# ## Load Data
# loaded_csv_data = image_loader.load_csv_data('./Data/fer2013.csv')
#
# ## Convert to one hot vectors
# emotion_array = data_transformer.process_emotion(loaded_csv_data[['emotion']])
#
# ## Convert to a 48x48 float matrix
# pixel_array = data_transformer.process_pixels(loaded_csv_data[['pixels']])
#
# ## Split the training and test data
# y_train, y_test = data_transformer.split_data(emotion_array)
# x_train_matrix, x_test_matrix = data_transformer.split_data(pixel_array)
#
# ## Duplicate the input layer
# n_train = int(len(x_train_matrix))
# n_test = int(len(x_test_matrix))
#
# x_train_input = data_transformer.duplicate_input_layer(x_train_matrix, n_train)
# x_test_input = data_transformer.duplicate_input_layer(x_test_matrix, n_test)
#
# ## Initialise VGG16 Model
# vgg16 = VGGModel()
#
# ## Get model outputs
# x_train_feature_map = vgg16.get_vgg16_output(x_train_matrix, n_train)
# x_test_feature_map = vgg16.get_vgg16_output(x_test_matrix, n_test)
#
# ## Build and train model
# model_trained_dict = vgg16.train_base_model(x_train_feature_map, x_test_feature_map, y_train, y_test)
#
# ## Model Merge
# final_model = vgg16.merge_models(model_trained_dict)
## Save Model
# vgg16.save_model(final_model)