-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJAFEE.py
309 lines (206 loc) · 8.31 KB
/
JAFEE.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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import keras.backend as K
from keras.models import Model, Sequential
from keras.layers import Conv2D, MaxPool2D, Flatten, Dense, Input, Subtract, Lambda
from keras.optimizers import Adam, SGD
from keras.regularizers import l2
import keras.backend as K
from sklearn.model_selection import train_test_split
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import cv2
import itertools
import time
# In[2]:
labels = {
"surprise": 0,
"angry": 1,
"happy": 2,
"fear": 3,
"disgust": 4,
"sad": 5,
"neutral": 6
}
# In[3]:
def abc(str1):
for i in range (len(str1)-5,0,-1):
try:
z = int(str1[i])
except:
return str1[:i+1]
# In[17]:
def getImage(im,k):
im = plt.imread('../Datasets/Facial-Expression-Recognization-using-JAFFE-master/jaffe/AllFiles/'+im.numpy()[k].decode('utf8'))
im = im.astype('float32')
im = im/255
im=cv2.resize(im,(64,64))
img = im.reshape((-1,64 * 64))
return img
# In[5]:
data_path = '../Datasets/Facial-Expression-Recognization-using-JAFFE-master/id'
data_dir_list = os.listdir(data_path)
n_class = 7
img_data_list=[]
x = []
y = []
for dataset in data_dir_list:
img_list=os.listdir(data_path+'/'+ dataset)
print ('Loaded the images of dataset-'+'{}\n'.format(dataset))
combinations = list(itertools.combinations(range(len(img_list)), 2))
for i in range (len(combinations)):
imgName1 = img_list[combinations[i][0]]
imgName2 = img_list[combinations[i][1]]
# label1 = labels[abc(imgName1)]
# label2 = labels[abc(imgName2)]
label1 = tf.one_hot(labels[abc(imgName1)], n_class)
label2 = tf.one_hot(labels[abc(imgName2)], n_class)
# img1 = plt.imread(data_path + '/'+ dataset + '/'+ imgName1)
# img2 = plt.imread(data_path + '/'+ dataset + '/'+ imgName2)
# img1 = cv2.resize(img1,(128,128))
# img2 = cv2.resize(img2,(128,128))
# img1 = img1.astype('float32')
# img1 = img1/255
# img2 = img2.astype('float32')
# img2 = img2/255
# img1 = img1.reshape((-1, 128 * 128))
# img2 = img2.reshape((-1, 128 * 128))
x.append((imgName1,imgName2))
y.append((label1,label2))
# img_data = img_data.reshape((-1, 128 * 128))
# In[6]:
len(x)
# In[7]:
#x = x[:-14]
# In[8]:
#y = y[:-14]
# In[9]:
# Building model
n_class = 7
input_dim = 4096
z_dim = 256
# Encoder
def make_encoder_model():
inputs = tf.keras.Input(shape=(input_dim,), name='Original_input')
x = tf.keras.layers.Dense(2048, activation='relu')(inputs)
x = tf.keras.layers.Dense(1024, activation='relu')(x)
x = tf.keras.layers.Dense(512, activation='relu')(x)
latent = tf.keras.layers.Dense(z_dim, activation='linear', name='Latent_variables')(x)
observed = tf.keras.layers.Dense(n_class, activation='softmax', name='Observed_variables')(x)
model = tf.keras.Model(inputs=inputs, outputs=[latent, observed], name='Encoder')
return model
encoder = make_encoder_model()
# # In[ ]:
encoder.summary()
# In[10]:
# # Decoder
def make_decoder_model():
inputted_latent = tf.keras.Input(shape=(z_dim,), name='Latent_variables')
inputted_observed = tf.keras.Input(shape=(n_class,), name='Observed_variables')
x = tf.keras.layers.concatenate([inputted_latent, inputted_observed], axis=-1)
x = tf.keras.layers.Dense(512, activation='relu')(x)
x = tf.keras.layers.Dense(1024, activation='relu')(x)
x = tf.keras.layers.Dense(2048, activation='relu')(x)
reconstruction = tf.keras.layers.Dense(input_dim, activation='linear', name='Reconstruction')(x)
model = tf.keras.Model(inputs=[inputted_latent, inputted_observed], outputs=reconstruction, name='Decoder')
return model
decoder = make_decoder_model()
# In[11]:
# Multipliers
alpha = 1000.0
beta = 100.0
gamma = 1000.0
zeta = 100
# Loss functions
# Reconstruction cost
mse_loss_fn = tf.keras.losses.MeanSquaredError()
# Supervised cost
cat_loss_fn = tf.keras.losses.CategoricalCrossentropy(from_logits=False)
# In[35]:
# Unsupervised cross-covariance cost
def xcov_loss_fn(latent, observed,batch_size):
latent_centered = latent - tf.reduce_mean(latent, axis=0, keepdims=True)
observed_centered = observed - tf.reduce_mean(observed, axis=0, keepdims=True)
xcov_loss = 0.5 * tf.reduce_sum(
tf.square(tf.matmul(latent_centered, observed_centered, transpose_a=True)))
return xcov_loss
# In[12]:
optimizer = tf.keras.optimizers.Adam(lr=0.0001)
# In[14]:
batch_size = 8
n_epochs = 100
#x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.15, random_state=2)
train_dataset = tf.data.Dataset.from_tensor_slices((x, y))
train_dataset = train_dataset.batch(batch_size)
train_dataset = train_dataset.shuffle(buffer_size=1024)
#np.save('x_test.npy',x_test)
#np.save('y_test.npy',y_test)
# In[24]:
# Training step
# @tf.function
def train_on_batch(batch_x, batch_y):
with tf.GradientTape() as tape:
# Inference
batch_x_1 = np.zeros((batch_size,64*64))
batch_x_2 = np.zeros((batch_size,64*64))
batch_y_1 = np.zeros((batch_size,7))
batch_y_2 = np.zeros((batch_size,7))
for i in range (batch_size):
batch_x_1[i] = getImage(batch_x[i],0)
batch_x_2[i] = getImage(batch_x[i],1)
batch_y_1[i] = batch_y[i].numpy()[0]
batch_y_2[i] = batch_y[i].numpy()[1]
batch_latent_1, batch_observed_1 = encoder(batch_x_1)
batch_latent_2, batch_observed_2 = encoder(batch_x_2)
batch_reconstruction_1 = decoder([batch_latent_1, batch_observed_1])
batch_reconstruction_2 = decoder([batch_latent_2, batch_observed_2])
# plt.figure()
# print(batch_x_1)
# print(batch_observed_1)
# Loss functions
recon_loss_1 = alpha * mse_loss_fn(batch_x_1, batch_reconstruction_1)
recon_loss_2 = alpha * mse_loss_fn(batch_x_2, batch_reconstruction_2)
# print(batch_reconstruction_1.shape)
# plt.imshow(batch_latent_1)
# plt.imshow(batch_latent_1)
cat_loss_1 = beta * cat_loss_fn(batch_y_1, batch_observed_1)
cat_loss_2 = beta * cat_loss_fn(batch_y_2, batch_observed_2)
xcov_loss_1 = gamma * xcov_loss_fn(batch_latent_1, batch_observed_1, tf.cast(tf.shape(batch_x_1)[0], tf.float32))
xcov_loss_2 = gamma * xcov_loss_fn(batch_latent_2, batch_observed_2, tf.cast(tf.shape(batch_x_2)[0], tf.float32))
similarity_loss = zeta*mse_loss_fn(batch_latent_1,batch_latent_2)
# Final loss function
ae_loss = recon_loss_1 + recon_loss_2 + cat_loss_1 +cat_loss_2 + xcov_loss_1 + xcov_loss_2 + similarity_loss
gradients = tape.gradient(ae_loss, encoder.trainable_variables + decoder.trainable_variables)
optimizer.apply_gradients(zip(gradients, encoder.trainable_variables + decoder.trainable_variables))
recon_loss = (recon_loss_1 + recon_loss_2)/2
cat_loss = (cat_loss_1 + cat_loss_2)/2
xcov_loss = (xcov_loss_1 + xcov_loss_2)/2
return recon_loss, cat_loss, xcov_loss, similarity_loss
# In[25]:
for epoch in range(n_epochs):
start = time.time()
# Functions to calculate epoch's mean performance
epoch_recon_loss_avg = tf.metrics.Mean()
epoch_cat_loss_avg = tf.metrics.Mean()
epoch_xcov_loss_avg = tf.metrics.Mean()
epoch_sim_loss_avg = tf.metrics.Mean()
for batch, (batch_x, batch_y) in enumerate(train_dataset):
if(len(batch_x)<8):break
recon_loss, cat_loss, xcov_loss, similarity_loss = train_on_batch(batch_x, batch_y)
epoch_recon_loss_avg(recon_loss)
epoch_cat_loss_avg(cat_loss)
epoch_xcov_loss_avg(xcov_loss)
epoch_sim_loss_avg(similarity_loss)
epoch_time = time.time() - start
print('{:3d}: {:.2f}s ETA: {:.2f}s Reconstruction cost: {:.4f} Supervised cost: {:.4f} XCov cost: {:.4f} Similarity cost: {:.4f}'
.format(epoch + 1, epoch_time,
epoch_time * (n_epochs - epoch),
epoch_recon_loss_avg.result(),
epoch_cat_loss_avg.result(),
epoch_xcov_loss_avg.result(),epoch_sim_loss_avg.result()))
encoder.save('Ronaks encoder.h5')
decoder.save('Ronaks decoder.h5')