forked from thesherrinford/memoji_fer2013
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
133 lines (106 loc) · 4.36 KB
/
train.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
#import matplotlib.image as mig
from models import EmoNet
FLAGS = None
def loadData(file_name, batch_size):
x = np.load(file_name+"_x.npy")
y = np.load(file_name+"_y.npy")
print(x.shape)
#f = open(file_name+"_ydata", "w")
#for yy in y:
# f.write(str(yy))
# f.write("\n")
#f.close()
#img_g = np.ones([48, 48, 3])
#print(y)
count = len(x) // batch_size
if len(x) % batch_size != 0:
count += 1
x_batch = np.empty([count, batch_size, x.shape[1], x.shape[2], x.shape[3]])
y_batch = np.empty([count, batch_size], dtype=np.int32)
for i in range(count-1):
x_batch[i] = x[i*batch_size:(i+1)*batch_size] / 255
y_batch[i] = y[i*batch_size:(i+1)*batch_size]
#mig.imsave(file_name+str(i)+"_x.png", img_g*x[i*batch_size]/255, vmax=1.0, vmin=0.0)
x_batch[-1] = x[-batch_size:] / 255
y_batch[-1] = y[-batch_size:]
return (x_batch, y_batch, count)
def main(FLAGS):
sess = tf.InteractiveSession()
m = EmoNet()
x_input = tf.placeholder(shape=[FLAGS.batch_size, 48, 48, 1], dtype=tf.float32)
y_input = tf.placeholder(shape=[FLAGS.batch_size], dtype=tf.int64)
logits, dropout_placeholder = m.build_network(x_input, is_training=True)
predictions = tf.argmax(logits, axis=-1)
cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y_input, logits=logits))
accuracy = tf.reduce_mean(tf.cast(tf.equal(y_input, predictions), tf.float32))
optimizer = tf.train.AdamOptimizer(FLAGS.learn_rate)
gradsvars = optimizer.compute_gradients(cost, var_list=tf.trainable_variables())
grads, _ = tf.clip_by_global_norm([g for g, v in gradsvars], 50)
optimizer_fn = optimizer.apply_gradients(zip(grads, tf.trainable_variables()))
cel = tf.summary.scalar('cross-entropy-loss', cost)
acc = tf.summary.scalar('accuracy', accuracy)
summary = tf.summary.merge([cel, acc])
train_writer = tf.summary.FileWriter(os.path.join(FLAGS.model_dir, "train"))
test_writer = tf.summary.FileWriter(os.path.join(FLAGS.model_dir, "test"))
global_step = tf.Variable(tf.constant(0, dtype=tf.int32), trainable=False)
increment_global_step = tf.assign(global_step, global_step + 1)
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver(max_to_keep=50)
if FLAGS.start_checkpoint: #ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
print("Imported")
tf.logging.info("Imported model")
saver.restore(sess, FLAGS.start_checkpoint)
tf.train.write_graph(sess.graph_def, FLAGS.model_dir, 'graph.pbtxt')
x_train, y_train, train_epochs = loadData(os.path.join(FLAGS.data_dir, "train"), FLAGS.batch_size)
x_test, y_test, test_epochs = loadData(os.path.join(FLAGS.data_dir, "test"), FLAGS.batch_size)
for i in range(FLAGS.epochs):
for j in range(train_epochs):
loss, _, s = sess.run([cost, optimizer_fn, summary], feed_dict={x_input: x_train[j], y_input: y_train[j], dropout_placeholder: 0.5}) #m.runBatch(sess, train_writer, train_batches_x[j], train_batches_y[j], sess.run(global_step))
train_writer.add_summary(s, sess.run(global_step))
sess.run(increment_global_step)
print(loss) #for slow computer
saver.save(sess, os.path.join(FLAGS.model_dir, "EmoNet"), global_step=global_step)
test_acc = 0
print("Test:")
for k in range(test_epochs):
a, _, s = sess.run([accuracy, optimizer_fn, summary], feed_dict={x_input: x_test[k], y_input: y_test[k], dropout_placeholder: 1.0}) #m.runBatch(sess, train_writer, train_batches_x[j], train_batches_y[j], sess.run(global_step))
test_writer.add_summary(s, sess.run(global_step))
test_acc += a
print(test_acc/test_epochs)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir",
type=str,
default="data/",
help="Data dir")
parser.add_argument("--model_dir",
type=str,
default="data/",
help="Model save dir")
parser.add_argument("--epochs",
type=int,
default=5,
help="Model save dir")
parser.add_argument("--start_checkpoint",
type=str,
default=None,
help="Model save dir")
parser.add_argument("--learn_rate",
type=float,
default=0.01,
help="Learn rate")
parser.add_argument("--batch_size",
type=int,
default=256,
help="Size of batch")
FLAGS, unparsed = parser.parse_known_args()
main(FLAGS)