-
Notifications
You must be signed in to change notification settings - Fork 0
/
age_gender_model.py
262 lines (199 loc) · 12.8 KB
/
age_gender_model.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
import tensorflow as tf
import numpy as np
import math
#import matplotlib.pyplot as plt
#%matplotlib inline
import time
import os
import tensornets as nets
import cv2
import sys
from load_wiki_cropface import get_wiki_crop_data
from tensornets.utils import var_scope
from tensornets.layers import dropout
from tensornets.layers import fc
from tensornets.ops import softmax
from tensornets.ops import reduce_mean
@var_scope('mobilenet100')
def age_gender_model(inputs, is_training, outputs_age = None, outputs_gender = None, num_class = 80, batch_size = 100, learning_rate = 1e-5):
cnn_net = nets.MobileNet100(inputs, is_training = is_training, classes = num_class, stem=True)
cnn_net = reduce_mean(cnn_net, [1, 2], name='avgpool')
cnn_net = dropout(cnn_net, keep_prob=0.999, is_training=is_training, scope='dropout')
cnn_net_age = fc(cnn_net, num_class, scope='logits_age')
cnn_net_gender = fc(cnn_net, 2, scope='logits_gender')
cnn_net_age = softmax(cnn_net_age, name='probs_age')
cnn_net_gender = softmax(cnn_net_gender, name='probs_gender')
cnn_predictions_age = tf.reduce_sum(tf.multiply(tf.range(0, 80, dtype = np.float32), cnn_net_age), axis = 1, name = "cnn_predictions_age")
cnn_predictions_gender = tf.argmax(cnn_net_gender, axis = 1, name = "cnn_predictions_gender")
#return cnn_predictions_age, cnn_predictions_gender
age_loss = tf.divide(tf.sqrt(tf.reduce_sum((cnn_predictions_age - tf.cast(outputs_age, tf.float32)) ** 2), name = "sqrt_age_loss"), \
float(batch_size), name = "age_loss")
cnn_MAE_age = tf.reduce_mean(tf.abs(cnn_predictions_age - tf.cast(outputs_age, tf.float32)))
cnn_predictions_gender_correct = tf.equal(tf.cast(cnn_predictions_gender, dtype=tf.int32), outputs_gender)
cnn_accuracy_gender = tf.reduce_mean(tf.cast(cnn_predictions_gender_correct, tf.float32))
gender_loss = tf.losses.softmax_cross_entropy(tf.one_hot(outputs_gender,2, dtype=tf.float32), cnn_net_gender)
total_loss = tf.add_n([gender_loss, age_loss])
#cnn_predictions = tf.argmax(cnn_net)
#cnn_loss = tf.losses.softmax_cross_entropy(tf.one_hot(outputs,num_class, dtype=tf.int32), cnn_net)
#cnn_loss = tf.reduce_mean(cnn_loss)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
cnn_train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(total_loss)
return cnn_train, cnn_net_age, cnn_net_gender, total_loss, age_loss, gender_loss, \
cnn_MAE_age, cnn_accuracy_gender, cnn_predictions_age, cnn_predictions_gender
def run_test(session, input_data, model_path = "train_models/age_gender_tensornets_wiki_cropface_model_20180519_123211"):
cnn_predictions_age = 0
cnn_predictions_gender = 0
#inputs = tf.placeholder(tf.float32, [None, 224, 224, 3])
loader = tf.train.import_meta_graph(model_path + ".meta")
#saver.restore(sess, tf.train.latest_checkpoint("train_models/"))
#cnn_predictions_age, cnn_predictions_gender = age_gender_model(inputs)
#graph = tf.get_default_graph()
#saver_def = saver.as_saver_def()
#print (saver_def.filename_tensor_name)
#print (saver_def.restore_op_name)
session.run(tf.global_variables_initializer())
loader.restore(session, tf.train.latest_checkpoint("train_models/"))
inference_graph = tf.get_default_graph()
cnn_predictions_age = session.graph.get_tensor_by_name("mobilenet100/cnn_predictions_age:0")
cnn_predictions_gender = session.graph.get_tensor_by_name('mobilenet100/cnn_predictions_gender:0')
inputs_tensor = session.graph.get_tensor_by_name('inputs_tensor:0')
is_training = session.graph.get_tensor_by_name('is_training:0')
input_data = nets.preprocess('mobilenet100', input_data)
feed = {inputs_tensor : input_data, is_training : False}
cnn_predictions_age_test, cnn_predictions_gender_test = session.run([cnn_predictions_age, cnn_predictions_gender], feed_dict=feed)
print("@#!", cnn_predictions_age_test)
for i in range(len(cnn_predictions_age_test)):
cnn_predictions_age_test[i] = int(cnn_predictions_age_test[i]) + 10
return cnn_predictions_age_test, cnn_predictions_gender_test
def run_test_temp(sess, input_data, load_model_path = "train_models/age_gender_tensornets_wiki_cropface_model_20180519_123211"):
inputs = tf.placeholder(tf.float32, [None, 224, 224, 3], name = "inputs_tensor")
is_training = tf.placeholder(tf.bool, name = "is_training")
outputs_age = tf.placeholder(tf.int32, [None])
outputs_gender = tf.placeholder(tf.int32, [None])
cnn_train, cnn_net_age, cnn_net_gender, total_loss, age_loss, gender_loss, cnn_MAE_age, cnn_accuracy_gender, cnn_predictions_age, \
cnn_predictions_gender = age_gender_model(inputs,is_training, outputs_age, outputs_gender, 80, 1, 0.0001)
#cnn_net_age, cnn_net_gender = age_gender_model(inputs,is_training)
sess.run(tf.global_variables_initializer())
#nets.pretrained(cnn_net_age)
loader = tf.train.import_meta_graph(load_model_path + ".meta")
sess.run(tf.global_variables_initializer())
loader.restore(sess, tf.train.latest_checkpoint("train_models/"))
temp_age_output = np.array([56])
temp_gender_output = np.array([0])
input_data = nets.preprocess('mobilenet100', input_data)
feed = {inputs : input_data, outputs_age : temp_age_output, outputs_gender : temp_gender_output, is_training : False}
#feed = {inputs : batch_Xd, outputs_age : batch_yd_age, outputs_gender : batch_yd_gender, is_training : True}
cnn_predictions_age_test, cnn_predictions_gender_test = sess.run([cnn_accuracy_gender, cnn_predictions_gender], feed_dict=feed)
#for i in range(len(cnn_predictions_age_test)):
cnn_predictions_age_test = int(cnn_predictions_age_test) + 10
return cnn_predictions_age_test, cnn_predictions_gender_test
def run_train(sess, input_dict, num_class, epochs=3, batch_size=100,print_every=10,
learning_rate = 1e-5, dropout = 0.5, is_save_summary = True, load_model_path = None):
Xd = input_dict["X_train"]
yd_age = input_dict["y_age_train"]
yd_gender = input_dict["y_gender_train"]
Xv = input_dict["X_val"]
yv_age = input_dict["y_age_val"]
yv_gender = input_dict["y_gender_val"]
print("Batch dataset initialized.\n# of training data: {}\n# of val data: {}\n# of class: {}"
.format(Xd.shape[0], Xv.shape[0], num_class))
print("learning_rate: ", learning_rate)
# shuffle indicies
train_indicies = np.arange(Xd.shape[0])
np.random.shuffle(train_indicies)
inputs = tf.placeholder(tf.float32, [None, 224, 224, 3], name = "inputs_tensor")
is_training = tf.placeholder(tf.bool, name = "is_training")
outputs_age = tf.placeholder(tf.int32, [None])
outputs_gender = tf.placeholder(tf.int32, [None])
cnn_train, cnn_net_age, cnn_net_gender, total_loss, age_loss, gender_loss, cnn_MAE_age, cnn_accuracy_gender, cnn_predictions_age = \
age_gender_model(inputs,is_training, outputs_age, outputs_gender, num_class, batch_size, learning_rate)
train_summary = tf.summary.merge([tf.summary.scalar("total_loss", total_loss),
tf.summary.scalar("age_loss", age_loss),
tf.summary.scalar("gender_loss", gender_loss),
tf.summary.scalar("cnn_MAE_age", cnn_MAE_age),
tf.summary.scalar("cnn_accuracy_gender", cnn_accuracy_gender),
tf.summary.scalar("cnn_predictions50", cnn_predictions_age[50]),
tf.summary.scalar("outputs_age", outputs_age[50]),
tf.summary.scalar("cnn_predictions_min", tf.reduce_min(cnn_predictions_age)),
tf.summary.image("inputs", tf.expand_dims(inputs[0], 0))])
test_summary = tf.summary.merge([tf.summary.scalar("val_total_loss", total_loss),
tf.summary.scalar("val_age_loss", age_loss),
tf.summary.scalar("val_gender_loss", gender_loss),
tf.summary.scalar("val_cnn_MAE_age", cnn_MAE_age),
tf.summary.scalar("val_cnn_accuracy_gender", cnn_accuracy_gender)])
merged = tf.summary.merge_all()
sess.run(tf.global_variables_initializer())
nets.pretrained(cnn_net_age)
# tensorboard setting
time_now = time.strftime("%Y%m%d_%H%M%S", time.localtime())
if is_save_summary:
fileName = os.path.normcase("./result/" + time_now)
summary_writer = tf.summary.FileWriter(fileName, sess.graph)
print("loaded model successful")
global_step = 0
#var_list = tf.trainable_variables()
g_list = tf.global_variables()
#bn_moving_vars = [g for g in g_list if 'moving_mean' in g.name]
#bn_moving_vars += [g for g in g_list if 'moving_variance' in g.name]
#var_list += bn_moving_vars
saver = tf.train.Saver(var_list = g_list, max_to_keep=2, keep_checkpoint_every_n_hours=2)
if (load_model_path != None):
loader = tf.train.import_meta_graph(load_model_path + ".meta")
sess.run(tf.global_variables_initializer())
loader.restore(sess, tf.train.latest_checkpoint("train_models/"))
for current_epoch in range(epochs):
# training step
###for x_batch, y_batch in batch_set.batches():
print("#############################Epoch Start##############################")
for i in range(int(math.ceil(Xd.shape[0]/batch_size))):
start = time.time()
start_idx = (i*batch_size)%Xd.shape[0]
idx = np.int32(train_indicies[start_idx:start_idx+batch_size])
#batch_Xd = load_img_from_tensor(Xd[idx,:, :, :], target_size=256, crop_size=224)
batch_Xd = Xd[idx,:, :, :]
"""
H = 224
low = int(0.4/1.8 * H)
high = int(1.4 / 1.8 * H)
tempImgData = batch_Xd[:, low:high, low : high, :]
for j in range(batch_Xd.shape[0]):
batch_Xd[j] = cv2.resize(tempImgData[j], (224, 224))
"""
batch_Xd = nets.preprocess('mobilenet100', batch_Xd)
batch_yd_age = yd_age[idx]
batch_yd_gender = yd_gender[idx]
feed = {inputs : batch_Xd, outputs_age : batch_yd_age, outputs_gender : batch_yd_gender, is_training : True}
global_step = global_step + 1
_, total_loss_running, age_loss_running, gender_loss_running, cnn_MAE_age_running, \
cnn_accuracy_gender_running, summary_running = sess.run([cnn_train, total_loss, \
age_loss, gender_loss, cnn_MAE_age, cnn_accuracy_gender, train_summary], feed_dict=feed)
#tem_data_fileName = os.path.normcase("./tmp_data/" + time_now + "/")
#if i < 100 and current_epoch == 0:
# np.save("./tmp_data/batch_yd_batch_" + str(i) + ".npy",batch_yd)
# np.save("./tmp_data/cnn_predictions_batch_" + str(i) + ".npy",cnn_predictions_now)
# np.save("./tmp_data/cnn_softmax_batch_" + str(i) + ".npy",scores)
if is_save_summary:
summary_writer.add_summary(summary_running, global_step)
if global_step % print_every == 0:
print("{}/{} ({} epochs) step, total_loss:{:.4f}, aloss:{:.3f}, gloss:{:.3f}, gaccuracy:{:.3f}, ageMAE:{:.3f}, time/batch : {:.3f}sec"
.format(global_step, int(round(Xd.shape[0]/batch_size)) * epochs, current_epoch, \
total_loss_running, age_loss_running, gender_loss_running, \
cnn_accuracy_gender_running, cnn_MAE_age_running, time.time() - start))
saver.save(sess, 'train_models/age_gender_tensornets_wiki_cropface_model_' + time_now)
# test step
start, avg_loss, avg_accuracy = time.time(), 0, 0
#Xv = load_img_from_tensor(Xv, target_size=256, crop_size=224)
#Xv = cnn_net.preprocess(Xv)
Xv = nets.preprocess('mobilenet100', Xv)
feed = {inputs : Xv, outputs_age : yv_age, outputs_gender : yv_gender, is_training : True}
total_loss_running, age_loss_running, gender_loss_running, cnn_MAE_age_running, \
cnn_accuracy_gender_running, summary_running = sess.run([total_loss, \
age_loss, gender_loss, cnn_MAE_age, cnn_accuracy_gender, test_summary], feed_dict=feed)
if is_save_summary:
summary_writer.add_summary(summary_running, current_epoch)
print("{} epochs test result, total_loss:{:.4f}, aloss:{:.3f}, gloss:{:.3f}, gaccuracy:{:.3f}, ageMAE:{:.3f}, time/batch : {:.3f}sec"
.format(current_epoch, total_loss_running, age_loss_running, gender_loss_running, cnn_accuracy_gender_running, \
cnn_MAE_age_running, time.time() - start))
print("\n")
return