-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest_pmnist.py
154 lines (137 loc) · 6.94 KB
/
test_pmnist.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
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import pickle
import numpy as np
import argparse
import os
from models.arnn import AttnRNN
np.random.seed(10)
shuffle_indices = np.random.permutation(np.arange(784))
def reshape_perm(xs):
xs_shf = []
for x in xs:
x = np.reshape(x, [784])
x = np.array(list(x))
x_shf = x[shuffle_indices]
xs_shf.append(x_shf)
xs_shf = np.array(xs_shf)
return xs_shf
def save(fname, obj):
with open(fname, 'wb') as f:
pickle.dump(obj, f)
def load(fname):
with open(fname, 'rb') as f:
return pickle.load(f)
class LSTMCM(object):
def __init__(self, config, cell, reuse=None):
self.batch_size = config.batch_size
self.step_size = config.step_size
self.input_size = config.input_size
self.class_num = config.class_num
self.unit_size = config.unit_size
self.learning_rate = config.learning_rate
self.device = config.device
self.K = cell.K
self.cell_name = cell.name
self.clip_value = config.clip_value
self.test_iter = config.test_iter
with tf.device(self.device), tf.name_scope(self.cell_name), \
tf.variable_scope("LSTMCM", reuse=reuse):
with tf.variable_scope("inputs"):
self.inputs = tf.placeholder(tf.float32, [self.batch_size, self.step_size])
inputs = tf.reshape(self.inputs,
[self.batch_size, self.step_size, self.input_size])
with tf.variable_scope("rnn_unit") as scope:
lstm_outputs, self.final_state = cell.dynamic_rnn(inputs, scope=scope)
final_hidden = lstm_outputs[-1]
lstm_outputs = tf.reshape(final_hidden, [self.batch_size, self.unit_size])
with tf.variable_scope("full_conn"):
w_shape = [self.unit_size, self.class_num]
truc_init = tf.truncated_normal_initializer()
softmax_W = tf.get_variable('softmax_W', w_shape, initializer=truc_init)
softmax_b = tf.get_variable('softmax_b', [self.class_num])
outputs = tf.nn.softmax(tf.matmul(lstm_outputs, softmax_W) + softmax_b)
self.targets = tf.placeholder(tf.float32, [self.batch_size, self.class_num])
with tf.variable_scope("train"):
self.cross_entropy = tf.reduce_mean(-tf.reduce_sum(self.targets * tf.log(outputs),
reduction_indices=[1]))
correct_prediction = tf.equal(tf.argmax(outputs, 1), tf.argmax(self.targets, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.variable_scope("optimize"):
optimizer = tf.train.AdamOptimizer(self.learning_rate)
gvs = optimizer.compute_gradients(self.cross_entropy)
capped_gvs = [(None if grad is None else tf.clip_by_value(grad, -self.clip_value, self.clip_value), var)
for grad, var in gvs]
self.train_op = optimizer.apply_gradients(capped_gvs)
def run(self, sess, data, accuracys):
(valid_accs, test_accs) = accuracys
batch_size = self.batch_size
num_examples = data.train.num_examples
num_batch = int(num_examples / batch_size)
for batch_id in range(num_batch):
batch_xs, batch_ys = data.train.next_batch(batch_size)
batch_xs = reshape_perm(batch_xs)
feed = {self.inputs: batch_xs, self.targets: batch_ys}
loss, state, _ = sess.run([self.cross_entropy, self.final_state, self.train_op], feed)
if (batch_id % self.test_iter) == 0:
accuracy = 0.0
num_valid_examp = data.validation.num_examples
num_valid_batch = int(num_valid_examp / batch_size)
for i in range(num_valid_batch):
batch_xs, batch_ys = data.validation.next_batch(batch_size)
batch_xs = reshape_perm(batch_xs)
feed = {self.inputs: batch_xs, self.targets: batch_ys}
accuracy += sess.run(self.accuracy, feed)
valid_accs.append(accuracy / num_valid_batch)
print('[%s vald] acc: %f' % (self.cell_name, accuracy / num_valid_batch))
if (batch_id % self.test_iter) == 0:
accuracy = 0.0
num_test_examp = data.test.num_examples
num_test_batch = int(num_test_examp / batch_size)
for i in range(num_test_batch):
batch_xs, batch_ys = data.test.next_batch(batch_size)
batch_xs = reshape_perm(batch_xs)
feed = {self.inputs: batch_xs, self.targets: batch_ys}
accuracy += sess.run(self.accuracy, feed)
test_accs.append(accuracy / num_test_batch)
print('[%s test] acc: %f' % (self.cell_name, accuracy / num_test_batch))
return (valid_accs, test_accs)
def parse_input():
parser = argparse.ArgumentParser(description="Parse network configuretion")
parser.add_argument("--batch_size",type=int, default=100)
parser.add_argument("--step_size",type=int, default=784)
parser.add_argument("--input_size",type=int, default=1)
parser.add_argument("--class_num",type=int, default=10)
parser.add_argument("--unit_size",type=int, default=100)
parser.add_argument("--epoch_num",type=int, default=800)
parser.add_argument("--test_iter",type=int, default=100)
parser.add_argument("--learning_rate",type=float, default=1.0e-3)
parser.add_argument("--clip_value",type=float, default=1.0)
parser.add_argument("--device",type=str, default='/gpu:0')
parser.add_argument("--cell_name",type=str, default="arnn")
parser.add_argument("--K",type=int, default=8)
return parser.parse_args()
if __name__ == "__main__":
config = parse_input()
mnist = input_data.read_data_sets("./data/mnist", one_hot=True)
graph = tf.Graph()
with graph.as_default():
name = config.cell_name
cell = AttnRNN(config.unit_size, config.K, config.cell_name)
model = LSTMCM(config, cell)
sess_cfg = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)
sess_cfg.gpu_options.allow_growth = True
with tf.Session(graph=graph, config=sess_cfg) as sess:
valid_accs = []
test_accs = []
accuracys = (valid_accs, test_accs)
sess.run(tf.global_variables_initializer())
if config.cell_name == 'arnn':
fname = "pmnist_arnn_k%d.pkl" % (config.K)
else:
fname = "pmnist_%s.pkl" % (config.cell_name)
file_name = os.path.join("result", "pmnist", fname)
for epoch in range(config.epoch_num):
accuracys = model.run(sess, mnist, accuracys)
save(file_name,accuracys)
print("[ep: %d] save secuess..%s\n\n" % (epoch+1, file_name))