-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathevaluate.py
executable file
·289 lines (226 loc) · 9.75 KB
/
evaluate.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
""" Evaluates train model and produces plots
--load checkpoint directory if you want to continue training a model
--task task to train on {'mnist', 'translated' or 'cluttered'}
--num_glimpses # glimpses (fixed)
--n_patches # resolutions extracted for each glimpse
"""
import matplotlib as mpl
mpl.use('Agg')
import tensorflow as tf
import numpy as np
import os
import argparse
from datetime import datetime
import pickle
from RAM import RAM
from DRAM import DRAM
from DRAM_loc import DRAMl
from config import Config
from src.utils import evaluate_repeatedly
from tensorflow.examples.tutorials.mnist import input_data
# ----- parse command line -----
parser = argparse.ArgumentParser()
parser.add_argument('--task','-t', type=str, default='cluttered_var',
help='Task - ["org","translated","cluttered", "cluttered_var"].')
parser.add_argument('--model','-m', type=str, default='dram_loc',
help='Model - "RAM" or "DRAM".')
parser.add_argument('--load','-l', type=str, default=None,
help='Load model from directory.')
parser.add_argument('--num_glimpses','-n', type=int, default=8,
help='Number of glimpses to take')
parser.add_argument('--n_patches','-np', type=int, default=2,
help='Number of patches for each glimpse')
parser.add_argument('--use_context', default=False, action='store_true',
help='Use context network (True) or not (False)')
parser.add_argument('--convnet', default=False, action='store_true',
help='True: glimpse sensor is convnet, False: fully-connected')
parser.add_argument('--N','-N', type=int, default=10,
help='Number of plots')
parser.add_argument('--plot_dir','-od', type=str, default='plots',
help='Plot directory.')
parser.add_argument('--visualize','-v', default=False, action='store_true',
help='Create plots or not')
FLAGS, _ = parser.parse_known_args()
def evaluate(model='ram', width=60, n_distractors=4, N=10):
"""Tests performance of trained model on larger/noisier mnist images."""
# data
mnist = input_data.read_data_sets('MNIST_data', one_hot=False)
# set parameters
#config.loc_std = 1e-10
config.num_glimpses = FLAGS.num_glimpses
config.n_patches = FLAGS.n_patches
config.use_context = FLAGS.use_context
config.convnet = FLAGS.convnet
config.sensor_size = config.glimpse_size**2 * config.n_patches * config.num_channels
config.N = mnist.train.num_examples # number of training examples
config.new_size = width
config.n_distractors = n_distractors
# init model
print '\n-- Model: {} --'.format(model)
print 'Setting samplding SD to {:.4e}'.format(config.loc_std)
if model == 'ram':
net = RAM(config)
elif model == 'dram':
net = DRAM(config)
elif model == 'dram_loc':
net = DRAMl(config)
else:
print 'Unknown model {}'.format(model)
exit()
net.load(FLAGS.load) # restore
net.count_params()
#params = net.return_params(['context_network/conv0/w:0'])
#net.plot_filters(params[0], fname=FLAGS.plot_dir + '.pdf')
#exit()
if FLAGS.visualize:
# create plot for current parameters
plot_dir = os.path.join(FLAGS.load, FLAGS.plot_dir)
if not os.path.exists(plot_dir):
os.mkdir(plot_dir)
task = {'variant': FLAGS.task, 'width': width, 'n_distractors': n_distractors}
net.visualize(data=mnist,
task=task,
config=config,
N=N,
plot_dir=plot_dir)
# evaluate
#test, val = net.evaluate(data=mnist, task=FLAGS.task)
return test, val
def evaluate_generalization(model='dram_loc', visualize=False, N=10):
"""Tests performance of trained model on larger/noisier mnist images."""
# data
mnist = input_data.read_data_sets('MNIST_data', one_hot=False)
# set parameters
n_reps = N
widths = [200]
noise_levels = [4]
RESULTS = {}
for width in widths:
for noise in noise_levels:
# set parameters
#config.loc_std = 1e-10
config.num_glimpses = FLAGS.num_glimpses
config.n_patches = FLAGS.n_patches
config.use_context = FLAGS.use_context
config.convnet = FLAGS.convnet
config.sensor_size = config.glimpse_size**2 * config.n_patches * config.num_channels
config.N = mnist.train.num_examples # number of training examples
config.new_size = width
config.n_distractors = noise
# init model
print '\n-- Model: {} --'.format(model)
print 'Setting samplding SD to {:.4e}'.format(config.loc_std)
tf.reset_default_graph()
if model == 'ram':
net = RAM(config)
elif model == 'dram':
net = DRAM(config)
elif model == 'dram_loc':
net = DRAMl(config)
else:
print 'Unknown model {}'.format(model)
exit()
net.load(FLAGS.load) # restore
if FLAGS.visualize:
n_reps =1
# create plot for current parameters
subfolder = os.path.join(FLAGS.load, FLAGS.plot_dir)
if not os.path.exists(subfolder):
os.mkdir(subfolder)
plot_dir = os.path.join(subfolder, 'w={}_n_distractors={}'.format(width,noise))
if not os.path.exists(plot_dir):
os.mkdir(plot_dir)
task = {'variant': FLAGS.task, 'width': width, 'n_distractors': noise}
net.visualize(data=mnist,
task=task,
config=config,
plot_dir=plot_dir,
N=N)
# evaluate (n_reps) times
acc, _ = evaluate_repeatedly(ram=net, data=mnist, task=FLAGS.task, n_reps=n_reps)
print acc
# store results
RESULTS[(width,noise)] = acc
# save dictionary
with open(os.path.join(FLAGS.load, 'glimpses{}_results.pickle'.format(FLAGS.num_glimpses )), 'wb') as handle:
pickle.dump(RESULTS, handle, protocol=pickle.HIGHEST_PROTOCOL)
def evaluate_numglimpses(model='dram_loc', visualize=False, N=10):
"""Tests performance of trained model on larger/noisier mnist images."""
# data
mnist = input_data.read_data_sets('MNIST_data', one_hot=False)
# set parameters
n_glimpses = [1,2,3,4,5,6,7,8]
n_reps = N
width, noise = 100, 4
RESULTS = {}
for n in n_glimpses:
# set parameters
config.num_glimpses = n
config.n_patches = FLAGS.n_patches
config.use_context = FLAGS.use_context
config.convnet = FLAGS.convnet
config.sensor_size = config.glimpse_size**2 * config.n_patches * config.num_channels
config.N = mnist.train.num_examples # number of training examples
config.new_size = width
config.n_distractors = noise
# init model
print '\n-- Model: {} --'.format(model)
print 'Setting samplding SD to {:.4e}'.format(config.loc_std)
tf.reset_default_graph()
if model == 'ram':
net = RAM(config)
elif model == 'dram':
net = DRAM(config)
elif model == 'dram_loc':
net = DRAMl(config)
else:
print 'Unknown model {}'.format(model)
exit()
net.load(FLAGS.load) # restore
if FLAGS.visualize:
n_reps =1
# create plot for current parameters
subfolder = os.path.join(FLAGS.load, FLAGS.plot_dir)
if not os.path.exists(subfolder):
os.mkdir(subfolder)
plot_dir = os.path.join(subfolder, 'w={}_n_distractors={}'.format(width,noise))
if not os.path.exists(plot_dir):
os.mkdir(plot_dir)
task = {'variant': FLAGS.task, 'width': width, 'n_distractors': noise}
net.visualize(data=mnist,
task=task,
config=config,
plot_dir=plot_dir,
N=N)
# evaluate (n_reps) times
acc, _ = evaluate_repeatedly(ram=net, data=mnist, task=FLAGS.task, n_reps=n_reps)
print acc
# store results
RESULTS[n] = acc
# save dictionary
with open(os.path.join(FLAGS.load, 'glimpses{}_results.pickle'.format(FLAGS.num_glimpses )), 'wb') as handle:
pickle.dump(RESULTS, handle, protocol=pickle.HIGHEST_PROTOCOL)
if __name__ == '__main__':
if FLAGS.model == 'ram':
from config import Config
elif FLAGS.model == 'dram':
from config_dram import Config
elif FLAGS.model == 'dram_loc':
from config_dram import Config
else:
print 'Unknown model {}'.format(FLAGS.model)
exit()
# parameters
config = Config()
n_steps = config.step
# number of glimpses
config.num_glimpses = FLAGS.num_glimpses
config.n_patches = FLAGS.n_patches
config.N = 55000 # number of training examples
print '\n\nFlags: {}\n\n'.format(FLAGS)
# ------------------------------
#evaluate_generalization(model=FLAGS.model, N=2)
# number of glimpses
#evaluate_numglimpses(model=FLAGS.model, N=5)
evaluate(model=FLAGS.model, width=config.new_size, n_distractors=config.n_distractors,
N=FLAGS.N)