-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathmnist.py
580 lines (480 loc) · 23.4 KB
/
mnist.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
"""
Example for classification on MNIST [1].
.. code-block:: python
[1] Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner.
Gradient-based learning applied to document recognition.
Proceedings of the IEEE, 86(11), 1998.
**Note: the LMDBs can also be found in the data repository, see README.**
Use ``caffe/data/mnist/get_mnist.sh`` and ``caffe/examples/mnist/create_mnist.sh``
to convert MNIST to LMDBs. Copy the LMDBs to ``examples/mnist`` to get the
following directory structure:
.. code-block:: python
examples/mnist/
|- train_lmdb
|- test_lmdb
"""
import os
import cv2
import glob
import numpy
import argparse
from matplotlib import pyplot
# To silence Caffe! Must be added before importing Caffe or modules which
# are importing Caffe.
os.environ['GLOG_minloglevel'] = '3'
import caffe
import tools.solvers
import tools.lmdb_io
import tools.prototxt
import tools.pre_processing
caffe.set_mode_gpu()
def get_parser():
"""
Get the parser.
:return: parser
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(description = 'Caffe example on MNIST.')
parser.add_argument('mode', default = 'train')
parser.add_argument('--train_lmdb', dest = 'train_lmdb', type = str,
help = 'path to train LMDB',
default = 'examples/mnist/train_lmdb')
parser.add_argument('--test_lmdb', dest = 'test_lmdb', type = str,
help = 'path to test LMDB',
default = 'examples/mnist/test_lmdb')
parser.add_argument('--working_directory', dest = 'working_directory', type = str,
help = 'path to a directory (created if not existent) where to store the created .prototxt and snapshot files',
default = 'examples/mnist')
parser.add_argument('--iterations', dest = 'iterations', type = int,
help = 'number of iterations to train or resume',
default = 10000)
parser.add_argument('--image', dest = 'image', type = str,
help = 'path to image for testing',
default = 'examples/mnist/test_1.png')
return parser
def main_train():
"""
Train a network for MNIST from scratch.
"""
def network(lmdb_path, batch_size):
"""
The network definition given the LMDB path and the used batch size.
:param lmdb_path: path to LMDB to use (train or test LMDB)
:type lmdb_path: string
:param batch_size: batch size to use
:type batch_size: int
:return: the network definition as string to write to the prototxt file
:rtype: string
"""
net = caffe.NetSpec()
net.data, net.labels = caffe.layers.Data(batch_size = batch_size,
backend = caffe.params.Data.LMDB,
source = lmdb_path,
transform_param = dict(scale = 1./255),
ntop = 2)
net.conv1 = caffe.layers.Convolution(net.data, kernel_size = 5, num_output = 20,
weight_filler = dict(type = 'xavier'))
net.pool1 = caffe.layers.Pooling(net.conv1, kernel_size = 2, stride = 2,
pool = caffe.params.Pooling.MAX)
net.conv2 = caffe.layers.Convolution(net.pool1, kernel_size = 5, num_output = 50,
weight_filler = dict(type = 'xavier'))
net.pool2 = caffe.layers.Pooling(net.conv2, kernel_size = 2, stride = 2,
pool = caffe.params.Pooling.MAX)
net.fc1 = caffe.layers.InnerProduct(net.pool2, num_output = 500,
weight_filler = dict(type = 'xavier'))
net.relu1 = caffe.layers.ReLU(net.fc1, in_place = True)
net.score = caffe.layers.InnerProduct(net.relu1, num_output = 10,
weight_filler = dict(type = 'xavier'))
net.loss = caffe.layers.SoftmaxWithLoss(net.score, net.labels)
return net.to_proto()
def count_errors(scores, labels):
"""
Utility method to count the errors given the ouput of the
"score" layer and the labels.
:param score: output of score layer
:type score: numpy.ndarray
:param labels: labels
:type labels: numpy.ndarray
:return: count of errors
:rtype: int
"""
return numpy.sum(numpy.argmax(scores, axis = 1) != labels)
assert os.path.exists(args.train_lmdb), "LMDB %s not found" % args.train_lmdb
assert os.path.exists(args.test_lmdb), "LMDB %s not found" % args.test_lmdb
if not os.path.exists(args.working_directory):
os.makedirs(args.working_directory)
train_prototxt_path = args.working_directory + '/train.prototxt'
test_prototxt_path = args.working_directory + '/test.prototxt'
deploy_prototxt_path = args.working_directory + '/deploy.prototxt'
with open(train_prototxt_path, 'w') as f:
f.write(str(network(args.train_lmdb, 128)))
with open(test_prototxt_path, 'w') as f:
f.write(str(network(args.test_lmdb, 1000)))
tools.prototxt.train2deploy(train_prototxt_path, (1, 1, 28, 28), deploy_prototxt_path)
solver_prototxt_path = args.working_directory + '/solver.prototxt'
solver_prototxt = tools.solvers.SolverProtoTXT({
'train_net': train_prototxt_path,
'test_net': test_prototxt_path,
'test_initialization': 'false', # no testing
'test_iter': 0, # no testing
'test_interval': 1000,
'base_lr': 0.01,
'lr_policy': 'inv',
'gamma': 0.0001,
'power': 0.75,
'stepsize': 1000,
'display': 100,
'max_iter': 1000,
'momentum': 0.95,
'weight_decay': 0.0005,
'snapshot': 0, # only at the end
'snapshot_prefix': args.working_directory + '/snapshot',
'solver_mode': 'CPU'
})
solver_prototxt.write(solver_prototxt_path)
solver = caffe.SGDSolver(solver_prototxt_path)
callbacks = []
# Callback to report loss in console. Also automatically plots the loss
# and writes it to the given file. In order to silence the console,
# use plot_loss instead of report_loss.
report_loss = tools.solvers.PlotLossCallback(100, args.working_directory + '/loss.png')
callbacks.append({
'callback': tools.solvers.PlotLossCallback.report_loss,
'object': report_loss,
'interval': 1,
})
# Callback to report error in console.
report_error = tools.solvers.PlotErrorCallback(count_errors, 60000, 10000,
solver_prototxt.get_parameters()['snapshot_prefix'],
args.working_directory + '/error.png')
callbacks.append({
'callback': tools.solvers.PlotErrorCallback.report_error,
'object': report_error,
'interval': 500,
})
# Callback to save an "early stopping" model.
callbacks.append({
'callback': tools.solvers.PlotErrorCallback.stop_early,
'object': report_error,
'interval': 500,
})
# Callback for reporting the gradients for all layers in the console.
report_gradient = tools.solvers.PlotGradientCallback(100, args.working_directory + '/gradient.png')
callbacks.append({
'callback': tools.solvers.PlotGradientCallback.report_gradient,
'object': report_gradient,
'interval': 1,
})
# Callback for saving regular snapshots using the snapshot_prefix in the
# solver prototxt file.
# Is added after the "early stopping" callback to avoid problems.
callbacks.append({
'callback': tools.solvers.SnapshotCallback.write_snapshot,
'object': tools.solvers.SnapshotCallback(),
'interval': 500,
})
monitoring_solver = tools.solvers.MonitoringSolver(solver)
monitoring_solver.register_callback(callbacks)
monitoring_solver.solve(args.iterations)
def main_train_augmented():
"""
Train a network from scratch on augmented MNIST. Augmentation is done on the
fly and only involves multiplicative Gaussian noise.
Uses the same working directory as :func:`examples.mnist.main_train`, i.e.
the corresponding snapshots will be overwritten if not changed via
``--working_directory``.
"""
def network(lmdb_path, batch_size):
"""
The network definition given the LMDB path and the used batch size.
:param lmdb_path: path to LMDB to use (train or test LMDB)
:type lmdb_path: string
:param batch_size: batch size to use
:type batch_size: int
:return: the network definition as string to write to the prototxt file
:rtype: string
"""
net = caffe.NetSpec()
net.data, net.labels = caffe.layers.Data(batch_size = batch_size,
backend = caffe.params.Data.LMDB,
source = lmdb_path,
transform_param = dict(scale = 1./255),
ntop = 2)
net.augmented_data = caffe.layers.Python(net.data, python_param = dict(module = 'tools.layers', layer = 'DataAugmentationMultiplicativeGaussianNoiseLayer'))
net.augmented_labels = caffe.layers.Python(net.labels, python_param = dict(module = 'tools.layers', layer = 'DataAugmentationDoubleLabelsLayer'))
net.conv1 = caffe.layers.Convolution(net.augmented_data, kernel_size = 5, num_output = 20,
weight_filler = dict(type = 'xavier'))
net.pool1 = caffe.layers.Pooling(net.conv1, kernel_size = 2, stride = 2,
pool = caffe.params.Pooling.MAX)
net.conv2 = caffe.layers.Convolution(net.pool1, kernel_size = 5, num_output = 50,
weight_filler = dict(type = 'xavier'))
net.pool2 = caffe.layers.Pooling(net.conv2, kernel_size = 2, stride = 2,
pool = caffe.params.Pooling.MAX)
net.fc1 = caffe.layers.InnerProduct(net.pool2, num_output = 500,
weight_filler = dict(type = 'xavier'))
net.relu1 = caffe.layers.ReLU(net.fc1, in_place = True)
net.score = caffe.layers.InnerProduct(net.relu1, num_output = 10,
weight_filler = dict(type = 'xavier'))
net.loss = caffe.layers.SoftmaxWithLoss(net.score, net.augmented_labels)
return net.to_proto()
def count_errors(scores, labels):
"""
Utility method to count the errors given the ouput of the
"score" layer and the labels.
:param score: output of score layer
:type score: numpy.ndarray
:param labels: labels
:type labels: numpy.ndarray
:return: count of errors
:rtype: int
"""
return numpy.sum(numpy.argmax(scores, axis = 1) != labels)
assert os.path.exists(args.train_lmdb), "LMDB %s not found" % args.train_lmdb
assert os.path.exists(args.test_lmdb), "LMDB %s not found" % args.test_lmdb
if not os.path.exists(args.working_directory):
os.makedirs(args.working_directory)
train_prototxt_path = args.working_directory + '/train.prototxt'
test_prototxt_path = args.working_directory + '/test.prototxt'
deploy_prototxt_path = args.working_directory + '/deploy.prototxt'
with open(train_prototxt_path, 'w') as f:
f.write(str(network(args.train_lmdb, 128)))
with open(test_prototxt_path, 'w') as f:
f.write(str(network(args.test_lmdb, 1000)))
tools.prototxt.train2deploy(train_prototxt_path, (1, 1, 28, 28), deploy_prototxt_path)
solver_prototxt_path = args.working_directory + '/solver.prototxt'
solver_prototxt = tools.solvers.SolverProtoTXT({
'train_net': train_prototxt_path,
'test_net': test_prototxt_path,
'test_initialization': 'false', # no testing
'test_iter': 0, # no testing
'test_interval': 1000,
'base_lr': 0.01,
'lr_policy': 'inv',
'gamma': 0.0001,
'power': 0.75,
'stepsize': 1000,
'display': 100,
'max_iter': 1000,
'momentum': 0.95,
'weight_decay': 0.0005,
'snapshot': 0, # only at the end
'snapshot_prefix': args.working_directory + '/snapshot',
'solver_mode': 'CPU'
})
solver_prototxt.write(solver_prototxt_path)
solver = caffe.SGDSolver(solver_prototxt_path)
callbacks = []
# Callback to report loss in console. Also automatically plots the loss
# and writes it to the given file. In order to silence the console,
# use plot_loss instead of report_loss.
report_loss = tools.solvers.PlotLossCallback(100, args.working_directory + '/loss.png')
callbacks.append({
'callback': tools.solvers.PlotLossCallback.report_loss,
'object': report_loss,
'interval': 1,
})
# Callback to report error in console.
report_error = tools.solvers.PlotErrorCallback(count_errors, 60000, 10000,
solver_prototxt.get_parameters()['snapshot_prefix'],
args.working_directory + '/error.png')
callbacks.append({
'callback': tools.solvers.PlotErrorCallback.report_error,
'object': report_error,
'interval': 500,
})
# Callback to save an "early stopping" model.
callbacks.append({
'callback': tools.solvers.PlotErrorCallback.stop_early,
'object': report_error,
'interval': 500,
})
# Callback for reporting the gradients for all layers in the console.
report_gradient = tools.solvers.PlotGradientCallback(100, args.working_directory + '/gradient.png')
callbacks.append({
'callback': tools.solvers.PlotGradientCallback.report_gradient,
'object': report_gradient,
'interval': 1,
})
# Callback for saving regular snapshots using the snapshot_prefix in the
# solver prototxt file.
# Is added after the "early stopping" callback to avoid problems.
callbacks.append({
'callback': tools.solvers.SnapshotCallback.write_snapshot,
'object': tools.solvers.SnapshotCallback(),
'interval': 500,
})
monitoring_solver = tools.solvers.MonitoringSolver(solver)
monitoring_solver.register_callback(callbacks)
monitoring_solver.solve(args.iterations)
def main_resume():
"""
Resume training a network as started via :func:`examples.mnist.main_train`,
:func:`examples.mnist.main_train_augmented` or :func:`examples.mnist.main_train_autoencoder`.
"""
def network(lmdb_path, batch_size):
"""
The network definition given the LMDB path and the used batch size.
:param lmdb_path: path to LMDB to use (train or test LMDB)
:type lmdb_path: string
:param batch_size: batch size to use
:type batch_size: int
:return: the network definition as string to write to the prototxt file
:rtype: string
"""
net = caffe.NetSpec()
net.data, net.labels = caffe.layers.Data(batch_size = batch_size,
backend = caffe.params.Data.LMDB,
source = lmdb_path,
transform_param = dict(scale = 1./255),
ntop = 2)
net.augmented_data = caffe.layers.Python(net.data, python_param = dict(module = 'tools.layers', layer = 'DataAugmentationMultiplicativeGaussianNoiseLayer'))
net.augmented_labels = caffe.layers.Python(net.labels, python_param = dict(module = 'tools.layers', layer = 'DataAugmentationDoubleLabelsLayer'))
net.conv1 = caffe.layers.Convolution(net.augmented_data, kernel_size = 5, num_output = 20,
weight_filler = dict(type = 'xavier'))
net.pool1 = caffe.layers.Pooling(net.conv1, kernel_size = 2, stride = 2,
pool = caffe.params.Pooling.MAX)
net.conv2 = caffe.layers.Convolution(net.pool1, kernel_size = 5, num_output = 50,
weight_filler = dict(type = 'xavier'))
net.pool2 = caffe.layers.Pooling(net.conv2, kernel_size = 2, stride = 2,
pool = caffe.params.Pooling.MAX)
net.fc1 = caffe.layers.InnerProduct(net.pool2, num_output = 500,
weight_filler = dict(type = 'xavier'))
net.relu1 = caffe.layers.ReLU(net.fc1, in_place = True)
net.score = caffe.layers.InnerProduct(net.relu1, num_output = 10,
weight_filler = dict(type = 'xavier'))
net.loss = caffe.layers.SoftmaxWithLoss(net.score, net.augmented_labels)
return net.to_proto()
def count_errors(scores, labels):
"""
Utility method to count the errors given the ouput of the
"score" layer and the labels.
:param score: output of score layer
:type score: numpy.ndarray
:param labels: labels
:type labels: numpy.ndarray
:return: count of errors
:rtype: int
"""
return numpy.sum(numpy.argmax(scores, axis = 1) != labels)
max_iteration = 0
files = glob.glob(args.working_directory + '/*.solverstate')
for filename in files:
filenames = filename.split('_')
iteration = filenames[-1][:-12]
try:
iteration = int(iteration)
if iteration > max_iteration:
max_iteration = iteration
except:
pass
caffemodel = args.working_directory + '/snapshot_iter_' + str(max_iteration) + '.caffemodel'
solverstate = args.working_directory + '/snapshot_iter_' + str(max_iteration) + '.solverstate'
train_prototxt_path = args.working_directory + '/train.prototxt'
test_prototxt_path = args.working_directory + '/test.prototxt'
deploy_prototxt_path = args.working_directory + '/deploy.prototxt'
solver_prototxt_path = args.working_directory + '/solver.prototxt'
assert max_iteration > 0, "could not find a solverstate or snaphot file to resume"
assert os.path.exists(caffemodel), "caffemodel %s not found" % caffemodel
assert os.path.exists(solverstate), "solverstate %s not found" % solverstate
assert os.path.exists(train_prototxt_path), "prototxt %s not found" % train_prototxt_path
assert os.path.exists(test_prototxt_path), "prototxt %s not found" % test_prototxt_path
assert os.path.exists(deploy_prototxt_path), "prototxt %s not found" % deploy_prototxt_path
assert os.path.exists(solver_prototxt_path), "prototxt %s not found" % solver_prototxt_path
solver = caffe.SGDSolver(solver_prototxt_path)
solver.restore(solverstate)
solver.net.copy_from(caffemodel)
solver_prototxt = tools.solvers.SolverProtoTXT()
solver_prototxt.read(solver_prototxt_path)
callbacks = []
# Callback to report loss in console.
report_loss = tools.solvers.PlotLossCallback(100, args.working_directory + '/loss.png')
callbacks.append({
'callback': tools.solvers.PlotLossCallback.report_loss,
'object': report_loss,
'interval': 1,
})
# Callback to report error in console.
report_error = tools.solvers.PlotErrorCallback(count_errors, 60000, 10000,
solver_prototxt.get_parameters()['snapshot_prefix'],
args.working_directory + '/error.png')
callbacks.append({
'callback': tools.solvers.PlotErrorCallback.report_error,
'object': report_error,
'interval': 500,
})
# Callback to save an "early stopping" model.
callbacks.append({
'callback': tools.solvers.PlotErrorCallback.stop_early,
'object': report_error,
'interval': 500,
})
# Callback for reporting the gradients for all layers in the console.
report_gradient = tools.solvers.PlotGradientCallback(100, args.working_directory + '/gradient.png')
callbacks.append({
'callback': tools.solvers.PlotGradientCallback.report_gradient,
'object': report_gradient,
'interval': 1,
})
# Callback for saving regular snapshots using the snapshot_prefix in the
# solver prototxt file.
# Is added after the "early stopping" callback to avoid problems.
callbacks.append({
'callback': tools.solvers.SnapshotCallback.write_snapshot,
'object': tools.solvers.SnapshotCallback(),
'interval': 500,
})
monitoring_solver = tools.solvers.MonitoringSolver(solver, max_iteration)
monitoring_solver.register_callback(callbacks)
monitoring_solver.solve(args.iterations)
def main_test():
"""
Test the latest model obtained by :func:`examples.cifar10.main_train`
or :func:`examples.cifar10.main_resume` on the given input image.
"""
max_iteration = 0
files = glob.glob(args.working_directory + '/*.solverstate')
for filename in files:
filenames = filename.split('_')
iteration = filenames[-1][:-12]
try:
iteration = int(iteration)
if iteration > max_iteration:
max_iteration = iteration
except:
pass
caffemodel = args.working_directory + '/snapshot_iter_' + str(max_iteration) + '.caffemodel'
deploy_prototxt_path = args.working_directory + '/deploy.prototxt'
assert max_iteration > 0, "could not find a solverstate or snaphot file to resume"
assert os.path.exists(caffemodel), "caffemodel %s not found" % caffemodel
assert os.path.exists(deploy_prototxt_path), "prototxt %s not found" % deploy_prototxt_path
net = caffe.Net(deploy_prototxt_path, caffemodel, caffe.TEST)
transformer = caffe.io.Transformer({'data': (1, 1, 28, 28)})
transformer.set_transpose('data', (2, 0, 1))
transformer.set_raw_scale('data', 1/255.)
assert os.path.exists(args.image), "image %s not found" % args.image
image = cv2.imread(args.image)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#image = 255 - image
image.resize((28, 28, 1))
cv2.imshow('image', image)
net.blobs['data'].reshape(1, 1, 28, 28)
net.blobs['data'].data[...] = transformer.preprocess('data', image)
net.forward()
scores = net.blobs['score'].data
x = range(10)
pyplot.bar(x, scores[0, :], 1/1.5, color = 'blue')
pyplot.gcf().subplots_adjust(bottom = 0.2)
pyplot.show()
if __name__ == '__main__':
parser = get_parser()
args = parser.parse_args()
if args.mode == 'train':
main_train()
elif args.mode == 'train_augmented':
main_train_augmented()
elif args.mode == 'resume':
main_resume()
elif args.mode == 'test':
main_test()
else:
print('Invalid mode.')