-
Notifications
You must be signed in to change notification settings - Fork 7
/
models.py
382 lines (334 loc) · 14.4 KB
/
models.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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import tensorflow as tf
from layers import AffineTransformLayer, TransformParamsLayer, LandmarkImageLayer, LandmarkTransformLayer
from utils import cyclic_learning_rate
def NormRmse(GroudTruth, Prediction, n_landmark=68):
Gt = tf.reshape(GroudTruth, [-1, n_landmark, 2])
Pt = tf.reshape(Prediction, [-1, n_landmark, 2])
loss = tf.reduce_mean(
tf.sqrt(tf.reduce_sum(tf.squared_difference(Gt, Pt), 2)), 1)
if n_landmark == 68:
eyes_distance = tf.reduce_mean(Gt[:, 36:42, :], 1) - tf.reduce_mean(Gt[:, 42:48, :], 1)
elif n_landmark == 51:
eyes_distance = tf.reduce_mean(Gt[:, 19:25, :], 1) - tf.reduce_mean(Gt[:, 25:31, :], 1)
elif n_landmark == 32:
eyes_distance = tf.reduce_mean(Gt[:, 0:6, :], 1) - tf.reduce_mean(Gt[:, 6:12, :], 1)
elif n_landmark == 42:
eyes_distance = tf.reduce_mean(Gt[:, 10:16, :], 1) - tf.reduce_mean(Gt[:, 16:22, :], 1)
norm = tf.norm(eyes_distance, axis=1)
return loss / norm
# Numpy version
# def NormRmse(GroudTruth, Prediction, n_landmark=68):
# Gt = np.reshape(GroudTruth, [-1, n_landmark, 2])
# Pt = np.reshape(Prediction, [-1, n_landmark, 2])
# loss = np.mean(
# np.sqrt(np.sum(np.square(Gt- Pt), 2)), 1)
# if n_landmark == 68:
# eyes_distance = np.mean(Gt[:, 36:42, :], 1) - np.mean(Gt[:, 42:48, :], 1)
# elif n_landmark == 51:
# eyes_distance = np.mean(Gt[:, 19:25, :], 1) - np.mean(Gt[:, 25:31, :], 1)
# elif n_landmark == 32:
# eyes_distance = np.mean(Gt[:, 0:6, :], 1) - np.mean(Gt[:, 6:12, :], 1)
# elif n_landmark == 42:
# eyes_distance = np.mean(Gt[:, 10:16, :], 1) - np.mean(Gt[:, 16:22, :], 1)
# norm = np.linalg.norm(eyes_distance, axis=1)
# return loss / norm
def augment(images, labels, labels_em):
brght_imgs = tf.image.random_brightness(images, max_delta=0.3)
cntrst_imgs = tf.image.random_contrast(
brght_imgs, lower=0.2, upper=1.8)
# hue_imgs = tf.image.random_hue(cntrst_imgs, max_delta=0.2)
return cntrst_imgs, labels, labels_em
def emoDAN(MeanShapeNumpy, batch_size, nb_emotions=7,
lr_stage1=0.001, lr_stage2=0.001, n_landmark=68, IMGSIZE=224):
InputImage = tf.placeholder(tf.float32, [None, IMGSIZE, IMGSIZE, 1])
GroundTruth = tf.placeholder(tf.float32, [None, n_landmark * 2])
Emotion_Labels = tf.placeholder(tf.int32, [None, ])
# dataset = tf.data.Dataset.from_tensor_slices((x, y, z)).batch(batch_size)
# iter_ = dataset.make_initializable_iterator()
# InputImage, GroundTruth, Emotion_Labels = iter_.get_next()
MeanShape = tf.constant(MeanShapeNumpy, dtype=tf.float32)
S1_isTrain = tf.placeholder(tf.bool)
S2_isTrain = tf.placeholder(tf.bool)
global_step = tf.Variable(0, trainable=False)
Ret_dict = {}
Ret_dict['InputImage'] = InputImage
Ret_dict['GroundTruth'] = GroundTruth
Ret_dict['Emotion_labels'] = Emotion_Labels
# Ret_dict['x'] = x
# Ret_dict['y'] = y
# Ret_dict['z'] = z
InputImage, GroundTruth, Emotion_Labels = tf.cond(S1_isTrain,
lambda: augment(InputImage, GroundTruth, Emotion_Labels),
lambda: (InputImage, GroundTruth, Emotion_Labels))
InputImage, GroundTruth, Emotion_Labels = tf.cond(S2_isTrain,
lambda: augment(InputImage, GroundTruth, Emotion_Labels),
lambda: (InputImage, GroundTruth, Emotion_Labels))
Ret_dict['S1_isTrain'] = S1_isTrain
Ret_dict['S2_isTrain'] = S2_isTrain
with tf.variable_scope('Stage1'):
S1_Conv1a = tf.layers.batch_normalization(
tf.layers.conv2d(
InputImage,
64,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S1_isTrain)
S1_Conv1b = tf.layers.batch_normalization(
tf.layers.conv2d(
S1_Conv1a,
64,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S1_isTrain)
S1_Pool1 = tf.layers.max_pooling2d(S1_Conv1b, 2, 2, padding='same')
S1_Conv2a = tf.layers.batch_normalization(
tf.layers.conv2d(
S1_Pool1,
128,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S1_isTrain)
S1_Conv2b = tf.layers.batch_normalization(
tf.layers.conv2d(
S1_Conv2a,
128,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S1_isTrain)
S1_Pool2 = tf.layers.max_pooling2d(S1_Conv2b, 2, 2, padding='same')
S1_Conv3a = tf.layers.batch_normalization(
tf.layers.conv2d(
S1_Pool2,
256,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S1_isTrain)
S1_Conv3b = tf.layers.batch_normalization(
tf.layers.conv2d(
S1_Conv3a,
256,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S1_isTrain)
S1_Pool3 = tf.layers.max_pooling2d(S1_Conv3b, 2, 2, padding='same')
S1_Conv4a = tf.layers.batch_normalization(
tf.layers.conv2d(
S1_Pool3,
512,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S1_isTrain)
S1_Conv4b = tf.layers.batch_normalization(
tf.layers.conv2d(
S1_Conv4a,
512,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S1_isTrain)
S1_Pool4 = tf.layers.max_pooling2d(S1_Conv4b, 2, 2, padding='same')
S1_Pool4_Flat = tf.contrib.layers.flatten(S1_Pool4)
S1_DropOut = tf.layers.dropout(
S1_Pool4_Flat, 0.5, training=S1_isTrain)
S1_Fc1 = tf.layers.batch_normalization(
tf.layers.dense(
S1_DropOut,
256,
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S1_isTrain,
name='S1_Fc1')
S1_Fc2 = tf.layers.dense(S1_Fc1, n_landmark * 2)
S1_Ret = S1_Fc2 + MeanShape
S1_Cost = tf.reduce_mean(NormRmse(GroundTruth, S1_Ret, n_landmark=n_landmark))
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS, 'Stage1')):
S1_Optimizer = tf.train.AdamOptimizer(lr_stage1).minimize(
S1_Cost, var_list=tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES, "Stage1"))
Ret_dict['S1_Ret'] = S1_Ret
Ret_dict['S1_Cost'] = S1_Cost
Ret_dict['S1_Optimizer'] = S1_Optimizer
with tf.variable_scope('Stage2'):
S2_AffineParam = TransformParamsLayer(S1_Ret, MeanShape)
S2_InputImage = AffineTransformLayer(InputImage, S2_AffineParam)
S2_InputLandmark = LandmarkTransformLayer(S1_Ret, S2_AffineParam, nb_landmarks=n_landmark)
S2_InputHeatmap = LandmarkImageLayer(S2_InputLandmark)
S2_Feature = tf.reshape(tf.layers.dense(S1_Fc1,
int((IMGSIZE / 2) * (IMGSIZE / 2)),
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
(-1,
int(IMGSIZE / 2),
int(IMGSIZE / 2),
1))
S2_FeatureUpScale = tf.image.resize_images(
S2_Feature, (IMGSIZE, IMGSIZE), 1)
S2_ConcatInput = tf.layers.batch_normalization(
tf.concat([S2_InputImage, S2_InputHeatmap, S2_FeatureUpScale], 3), training=S2_isTrain)
S2_Conv1a = tf.layers.batch_normalization(
tf.layers.conv2d(
S2_ConcatInput,
64,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S2_isTrain)
S2_Conv1b = tf.layers.batch_normalization(
tf.layers.conv2d(
S2_Conv1a,
64,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S2_isTrain)
S2_Pool1 = tf.layers.max_pooling2d(S2_Conv1b, 2, 2, padding='same')
S2_Conv2a = tf.layers.batch_normalization(
tf.layers.conv2d(
S2_Pool1,
128,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S2_isTrain)
S2_Conv2b = tf.layers.batch_normalization(
tf.layers.conv2d(
S2_Conv2a,
128,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S2_isTrain)
S2_Pool2 = tf.layers.max_pooling2d(S2_Conv2b, 2, 2, padding='same')
S2_Conv3a = tf.layers.batch_normalization(
tf.layers.conv2d(
S2_Pool2,
256,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S2_isTrain)
S2_Conv3b = tf.layers.batch_normalization(
tf.layers.conv2d(
S2_Conv3a,
256,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S2_isTrain)
S2_Pool3 = tf.layers.max_pooling2d(S2_Conv3b, 2, 2, padding='same')
S2_Conv4a = tf.layers.batch_normalization(
tf.layers.conv2d(
S2_Pool3,
512,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S2_isTrain)
S2_Conv4b = tf.layers.batch_normalization(
tf.layers.conv2d(
S2_Conv4a,
512,
3,
1,
padding='same',
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S2_isTrain)
S2_Pool4 = tf.layers.max_pooling2d(S2_Conv4b, 2, 2, padding='same')
S2_Pool4_Flat = tf.contrib.layers.flatten(S2_Pool4)
S2_DropOut = tf.layers.dropout(
S2_Pool4_Flat, 0.5, training=S2_isTrain)
S2_Fc1 = tf.layers.batch_normalization(
tf.layers.dense(
S2_DropOut,
256,
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer()),
training=S2_isTrain)
S2_Fc2 = tf.layers.dense(S2_Fc1, n_landmark * 2)
S2_Emotion = tf.layers.dense(S2_Fc1, nb_emotions)
Pred_Emotion = tf.nn.softmax(S2_Emotion)
S2_Pred_Emotion = tf.argmax(input=Pred_Emotion, axis=1)
correct_prediction = tf.equal(
Emotion_Labels, tf.cast(S2_Pred_Emotion, tf.int32))
emotion_accuracy = tf.reduce_mean(
tf.cast(correct_prediction, tf.float32))
S2_Ret = LandmarkTransformLayer(
S2_Fc2 + S2_InputLandmark, S2_AffineParam, Inverse=True, nb_landmarks=n_landmark)
S2_Cost_landm = tf.reduce_mean(
NormRmse(GroundTruth, S2_Ret, n_landmark=n_landmark)) # cost for landmarks
one_hot_labels = tf.one_hot(indices=tf.cast(
Emotion_Labels, tf.int32), depth=nb_emotions)
print_output = tf.Print(S2_Pred_Emotion, [
Pred_Emotion, Emotion_Labels, S2_Pred_Emotion], summarize=100000)
S2_Cost_emotion = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
labels=one_hot_labels, logits=S2_Emotion)) # loss for emotion prediction
Joint_Cost = 0.5 * S2_Cost_landm + 0.5 * S2_Cost_emotion
learning_rate = cyclic_learning_rate(global_step,
learning_rate=0.0001,
max_lr=0.05,
step_size=10000)
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS, 'Stage2')):
S2_Optimizer = tf.train.GradientDescentOptimizer(
learning_rate=learning_rate).minimize(
Joint_Cost,
var_list=tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES,
"Stage2"),
global_step=global_step)
Ret_dict['S2_Fc2'] = S2_Fc2
Ret_dict['S2_Ret'] = S2_Ret
Ret_dict['S2_Cost'] = S2_Cost_landm
Ret_dict['S2_Optimizer'] = S2_Optimizer
Ret_dict['Joint_Cost'] = Joint_Cost
Ret_dict['Emotion_Accuracy'] = emotion_accuracy
Ret_dict['Pred_emotion'] = S2_Pred_Emotion
Ret_dict['S2_InputImage'] = S2_InputImage
Ret_dict['S2_InputLandmark'] = S2_InputLandmark
Ret_dict['S2_InputHeatmap'] = S2_InputHeatmap
Ret_dict['S2_FeatureUpScale'] = S2_FeatureUpScale
Ret_dict['S2_Conv4b'] = S2_Conv4b
Ret_dict['S2_Conv4a'] = S2_Conv4a
Ret_dict['S2_Conv3a'] = S2_Conv3a
Ret_dict['S2_Conv3b'] = S2_Conv3b
Ret_dict['S2_Emotion'] = S2_Emotion
Ret_dict['softmax'] = Pred_Emotion
Ret_dict['lr'] = learning_rate
return Ret_dict