-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrecognition.py
344 lines (287 loc) · 13.4 KB
/
recognition.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
from __future__ import division
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import time
class Emotion:
def __init__(self, batch_size=100, min_after_dequeue=200, num_threads=2, train_times=10000,
model_path="./ckpt_data/my_param.ckpt"):
# the absolute path and name of each tfrecord file
self.tfrecords_filename_train = './data/Face_train.tfrecords'
self.tfrecords_filename_test = './data/Face_test.tfrecords'
# these properties will be used when we attempt to get the batch data
self.batch_size = batch_size
self.min_after_dequeue = min_after_dequeue
self.num_threads = num_threads
self.capacity = self.min_after_dequeue + 3 * self.batch_size
# the number of iteration when train the CNN
self.train_times = train_times # use the training images for two times
# the path which save the ckpt file
self.model_path = model_path
def read_tfrecord_to_data(self, filename, num_epochs=None):
'''
:param filename: an absolute path which contains the tfrecord file
:return: an image and a corresponding label
'''
filename_queue = tf.train.string_input_producer(
[filename],
num_epochs=num_epochs
)
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
features={
'image_raw': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.string),
'img_floder': tf.FixedLenFeature([], tf.string)
}
)
image = tf.decode_raw(features['image_raw'], tf.uint8)
image = self.image_pre_process(image)
label = tf.decode_raw(features['label'], tf.float64)
label = tf.reshape(tensor=label,shape=[8])
# img_floder = features['img_floder']
return image, label
def image_pre_process(self, image):
'''
:param image: the image need to be preprocessed
:return: a preprocessed image
'''
img = tf.reshape(tensor=image, shape=[100, 100, 1])
img = tf.image.convert_image_dtype(image=img, dtype=tf.float32)
img = tf.image.random_flip_left_right(image=img)
img = tf.image.per_image_standardization(img)
image = tf.image.resize_images(images=img, size=[96, 96], method=1)
return image
def distort_color(self, image, color_ordering=0):
'''
:param image: the image need to be adjusted
:param color_ordering: the method of how to adjust the image
:return: an image(a 3-D tensor)
'''
if color_ordering == 0:
image = tf.image.random_brightness(image=image, max_delta=32. / 255.)
image = tf.image.random_saturation(image=image, lower=0.5, upper=1.5)
image = tf.image.random_hue(image=image, max_delta=0.2)
image = tf.image.random_contrast(image=image, lower=0.5, upper=1.5)
elif color_ordering == 1:
image = tf.image.random_saturation(image=image, lower=0.5, upper=1.5)
image = tf.image.random_brightness(image=image, max_delta=32. / 255.)
image = tf.image.random_contrast(image=image, lower=0.5, upper=1.5)
image = tf.image.random_hue(image=image, max_delta=0.2)
return tf.clip_by_value(t=image, clip_value_min=0.0, clip_value_max=1.0)
def add_conv2D(self, input, out_size, kw, kh, sw=1, sh=1, padding='SAME', is_training=True):
in_size = input.get_shape()[-1].value
kernal_shape = [kw, kh, in_size, out_size]
kernal = tf.Variable(tf.truncated_normal(shape=kernal_shape, mean=0.0, stddev=1.0, dtype=tf.float32))
bias = tf.Variable(tf.constant(0.1, shape=[out_size]))
conv = tf.nn.bias_add(tf.nn.conv2d(input, kernal, strides=[1, sw, sh, 1], padding=padding), bias)
conv_bn = self.batch_norm(conv, is_training=is_training, is_conv_out=True)
activation = tf.nn.relu(conv_bn)
return activation
def add_pooling(self, input, kw=2, kh=2, sw=2, sh=2, padding="SAME"):
ksize = [1, kw, kh, 1]
strides = [1, sw, sh, 1]
return tf.nn.max_pool(input, ksize=ksize, strides=strides, padding=padding)
def add_fc(self, input, out_size, is_training=True):
length = len(input.get_shape())
if length == 4:
w1 = input.get_shape()[1].value
w2 = input.get_shape()[2].value
w3 = input.get_shape()[3].value
w = w1 * w2 * w3
elif length == 2:
w = input.get_shape()[-1].value
weights = tf.Variable(tf.truncated_normal(shape=[w, out_size], mean=0.0, stddev=1.0, dtype=tf.float32))
bias = tf.Variable(tf.constant(0.1, shape=[out_size]))
input2D = tf.reshape(input, shape=[-1, w])
fc = tf.nn.bias_add(tf.matmul(input2D, weights), bias=bias)
fc_bn = self.batch_norm(fc, is_training=is_training, is_conv_out=False)
# activation = tf.nn.relu(fc_bn)
return fc_bn
def batch_norm(self, inputs, is_training, is_conv_out=True, decay=0.997):
'''
:param inputs: the input tensor
:param is_training: if the network is being trained
:param is_conv_out: if the current layer is convolution layer
:param decay: the decay factor
:return: the normalized tensor
'''
scale = tf.Variable(tf.ones([inputs.get_shape()[-1]]))
beta = tf.Variable(tf.zeros([inputs.get_shape()[-1]]))
pop_mean = tf.Variable(tf.zeros([inputs.get_shape()[-1]]), trainable=False)
pop_var = tf.Variable(tf.ones([inputs.get_shape()[-1]]), trainable=False)
if is_training == True:
if is_conv_out == True:
batch_mean, batch_var = tf.nn.moments(inputs, [0, 1, 2])
else:
batch_mean, batch_var = tf.nn.moments(inputs, [0])
train_mean = tf.assign(pop_mean, pop_mean * decay + batch_mean * (1 - decay))
train_var = tf.assign(pop_var, pop_var * decay + batch_var * (1 - decay))
with tf.control_dependencies([train_mean, train_var]):
return tf.nn.batch_normalization(inputs, batch_mean, batch_var, beta, scale, 0.001)
else:
return tf.nn.batch_normalization(inputs, pop_mean, pop_var, beta, scale, 0.001)
def build_network(self):
'''
:return: the train_step interface and accuracy interface
'''
# ----------------------- build the configuration of the CNN ----------------------- #
self.x = tf.placeholder(shape=[None, 96, 96, 1], dtype=tf.float32)
self.y_ = tf.placeholder(shape=[None, 8], dtype=tf.float32)
self.is_training = tf.placeholder(shape=(), dtype=tf.bool)
x_bn = self.batch_norm(self.x, self.is_training, is_conv_out=True)
# the first convolution layer
h_conv1_1 = self.add_conv2D(input=x_bn, out_size=32, kw=1, kh=1, is_training=self.is_training)
h_conv1_2 = self.add_conv2D(input=h_conv1_1, out_size=32, kw=1, kh=3, is_training=self.is_training)
h_conv1_3 = self.add_conv2D(input=h_conv1_2, out_size=32, kw=3, kh=1, is_training=self.is_training)
h_pool1 = self.add_pooling(input=h_conv1_3, kw=2, kh=2, sw=2, sh=2)
# the second convolution layer
h_conv2 = self.add_conv2D(input=h_pool1, out_size=64, kw=3, kh=3, is_training=self.is_training)
h_pool2 = self.add_pooling(h_conv2, kw=2, kh=2, sw=2, sh=2)
# the third convolution layer
h_conv3 = self.add_conv2D(input=h_pool2, out_size=128, kw=3, kh=3, is_training=self.is_training)
h_pool3 = self.add_pooling(h_conv3, kw=2, kh=2, sw=2, sh=2)
# the first full connected layer
h_fc1 = tf.nn.relu(self.add_fc(input=h_pool3, out_size=300, is_training=self.is_training))
# the second full connected layer
h_fc2 = self.add_fc(input=h_fc1, out_size=8, is_training=self.is_training)
# the loss function
diff = tf.nn.softmax_cross_entropy_with_logits(logits=h_fc2, labels=self.y_)
cross_entropy_loss = tf.reduce_mean(diff)
# the objective function
train_step = tf.train.AdagradOptimizer(1e-1).minimize(cross_entropy_loss)
correct_prediction = tf.equal(tf.argmax(h_fc2, 1), tf.argmax(self.y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
return train_step, accuracy, h_fc1
def run_train_step():
'''
:return: the path which save the ckpt file
'''
emotion = Emotion()
train_step, accuracy, _ = emotion.build_network()
# --------------------------- get the batch data ---------------------------- #
image, label = emotion.read_tfrecord_to_data(emotion.tfrecords_filename_test)
img_batch, lab_batch = tf.train.shuffle_batch(
[image, label],
batch_size=emotion.batch_size,
capacity=emotion.capacity,
min_after_dequeue=emotion.min_after_dequeue,
num_threads=emotion.num_threads
)
image_2, label_2 = emotion.read_tfrecord_to_data(emotion.tfrecords_filename_test)
img_batch_2, lab_batch_2 = tf.train.shuffle_batch(
[image_2, label_2],
batch_size=emotion.batch_size,
capacity=emotion.capacity,
min_after_dequeue=emotion.min_after_dequeue,
num_threads=emotion.num_threads
)
# ----------------------------- the initializer ----------------------------- #
init_op = tf.group(
tf.local_variables_initializer(),
tf.global_variables_initializer()
)
# ------------------ the saver used to save the parameters ------------------ #
saver = tf.train.Saver()
# -------------------------- train the CNN -------------------------- #
with tf.Session() as sess:
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(
sess=sess,
coord=coord
)
# print("load the ckpt data......")
# saver.restore(sess, emotion.model_path)
print("start to train......")
curr_time = time.time()
for i in range(emotion.train_times):
image_batch, label_batch = sess.run([img_batch, lab_batch])
if i % 100 == 0:
image_batch_2, label_batch_2 = sess.run([img_batch_2, lab_batch_2])
train_accuacy = accuracy.eval(
feed_dict={
emotion.x: image_batch_2,
emotion.y_: label_batch_2,
emotion.is_training: False
}
)
print("step %d,training accuracy %g" % (i, train_accuacy), "耗时:", time.time()-curr_time)
train_step.run(
feed_dict={
emotion.x: image_batch,
emotion.y_: label_batch,
emotion.is_training: True
}
)
save_path = saver.save(sess=sess, save_path=emotion.model_path)
coord.request_stop()
coord.join(threads)
print("the train step is completed!")
print(save_path)
return save_path
def run_test_step():
'''
:return: void
'''
accuracy_sum = 0.0
total_num = 0
emotion = Emotion()
_, accuracy, _ = emotion.build_network()
# --------------------------- get the batch data ---------------------------- #
image, label = emotion.read_tfrecord_to_data(
emotion.tfrecords_filename_test,
num_epochs=1
)
img_batch, lab_batch = tf.train.batch(
[image, label],
batch_size=emotion.batch_size,
capacity=emotion.capacity,
num_threads=emotion.num_threads
)
# ----------------------------- the initializer ----------------------------- #
init_op = tf.group(
tf.local_variables_initializer(),
tf.global_variables_initializer()
)
# ------------------ the saver used to save the parameters ------------------ #
saver = tf.train.Saver()
# ------------------------------ train the CNN ------------------------------ #
with tf.Session() as sess:
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(
sess=sess,
coord=coord
)
print("load the ckpt data......")
saver.restore(sess, emotion.model_path)
print("strat to test......")
for i in range(emotion.train_times):
# - if the batch data were all used when test the CNN, an exception will take place - #
try:
image_batch, label_batch = sess.run([img_batch, lab_batch])
except:
print('\n')
print('\n')
print("the average accuracy is %.3g" % (accuracy_sum / total_num))
print("the test step is completed!")
break
test_accuracy = accuracy.eval(
feed_dict={
emotion.x: image_batch,
emotion.y_: label_batch,
emotion.is_training: False
}
)
accuracy_sum = accuracy_sum + test_accuracy
total_num = total_num + 1
print("step %d,testing accuracy %.3g" % (i, test_accuracy))
if i % 100 == 0 and i > 0:
print("for the step in %d, the average testing accuracy is %.3g" % (i, accuracy_sum / total_num))
coord.request_stop()
coord.join(threads)
run_train_step()
# run_test_step()