forked from torch/demos
-
Notifications
You must be signed in to change notification settings - Fork 22
/
train-on-mnist.lua
177 lines (144 loc) · 5.35 KB
/
train-on-mnist.lua
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
----------------------------------------------------------------------
-- A simple script that trains a ConvNet on the MNIST dataset,
-- using stochastic gradient descent.
--
-- C.Farabet
----------------------------------------------------------------------
require 'XLearn'
----------------------------------------------------------------------
-- parse options
--
op = OptionParser('%prog [options]')
op:add_option{'-l', '--load', action='store', dest='network',
help='path to existing [trained] network'}
op:add_option{'-s', '--save', action='store', dest='saveto',
help='file name to save network [saving is done after each epoch]'}
op:add_option{'-d', '--dataset', action='store', dest='dataset',
help='path to dataset'}
op:add_option{'-n', '--show', action='store', dest='nb_samples',
help='show N samples from dataset'}
op:add_option{'-f', '--full', action='store_true', dest='full',
help='use full dataset (60,000 samples) to train'}
op:add_option{'-r', '--randseed', action='store', dest='seed',
help='force random seed (if not provided, then initial conditions are random)'}
options,args = op:parse_args()
----------------------------------------------------------------------
-- To save networks
--
os.execute('mkdir -p scratch')
----------------------------------------------------------------------
-- ConvNet to train: CSCSCF
--
local nbClasses = 10
local connex = {6,16,120}
local fanin = {1,6,16}
-- use seed (for repeatable experiments)
if options.seed then
random.manualSeed(options.seed)
end
-- Build network
convnet = nn.Sequential()
convnet:add(nn.SpatialConvolution(1,connex[1], 5, 5))
convnet:add(nn.Tanh())
convnet:add(nn.SpatialSubSampling(connex[1], 2, 2, 2, 2))
convnet:add(nn.Tanh())
convnet:add(nn.SpatialConvolution(connex[1],connex[2], 5, 5))
convnet:add(nn.Tanh())
convnet:add(nn.SpatialSubSampling(connex[2], 2, 2, 2, 2))
convnet:add(nn.Tanh())
convnet:add(nn.SpatialConvolution(connex[2],connex[3], 5, 5))
convnet:add(nn.Tanh())
convnet:add(nn.SpatialLinear(connex[3],nbClasses))
----------------------------------------------------------------------
-- learning criterion: we modify the fprop to compute useful
-- error information
--
criterion = nn.MSECriterion()
criterion.sizeAverage = true
----------------------------------------------------------------------
-- trainer: std stochastic trainer
--
trainer = nn.StochasticTrainer(convnet, criterion)
trainer:setShuffle(false)
trainer.learningRate = 1e-2
trainer.learningRateDecay = 0
trainer.weightDecay = 1e-5
trainer.maxEpoch = 50
----------------------------------------------------------------------
-- load datasets
--
path_dataset = options.dataset or '../datasets/mnist/'
path_trainData = paths.concat(path_dataset,'train-images-idx3-ubyte')
path_trainLabels = paths.concat(path_dataset,'train-labels-idx1-ubyte')
path_testData = paths.concat(path_dataset,'t10k-images-idx3-ubyte')
path_testLabels = paths.concat(path_dataset,'t10k-labels-idx1-ubyte')
trainData = {}
testData = {}
nbTrainingPatches = 2000
nbTestingPatches = 1000
if options.full then
nbTrainingPatches = 60000
nbTestingPatches = 10000
else
print('# warning: only using 2000 samples to train quickly (use flag --full to use 60000 samples)')
end
-- load data+labels
local data = toolBox.loadIDX(path_trainData):resize(28,28,nbTrainingPatches)
local labels = toolBox.loadIDX(path_trainLabels):resize(nbTrainingPatches)
for i=1,data:size(3) do
local target = torch.Tensor(1,1,nbClasses):fill(-1)
target[1][1][labels[i]+1] = 1
local sample = torch.Tensor(32,32,1):fill(0)
sample:narrow(1,3,28):narrow(2,3,28):copy(data:narrow(3,i,1)):mul(0.01)
trainData[i] = {sample,target}
end
trainData.size = function (self) return #self end
-- load data+labels
data = toolBox.loadIDX(path_testData):resize(28,28,nbTestingPatches)
labels = toolBox.loadIDX(path_testLabels):resize(nbTestingPatches)
for i=1,data:size(3) do
local target = torch.Tensor(1,1,nbClasses):fill(-1)
target[1][1][labels[i]+1] = 1
local sample = torch.Tensor(32,32,1):fill(0)
sample:narrow(1,3,28):narrow(2,3,28):copy(data:narrow(3,i,1)):mul(0.01)
testData[i] = {sample,target}
end
testData.size = function (self) return #self end
-- display ?
if options.nb_samples then
local samples = {}
for i = 1,options.nb_samples do
table.insert(samples, trainData[i][1])
end
image.displayList{images=samples, gui=false}
end
----------------------------------------------------------------------
-- training hooks
--
confusion = nn.ConfusionMatrix(nbClasses)
trainer.hookTrainSample = function(trainer, sample)
-- update confusion matrix
confusion:add(trainer.module.output[1][1], sample[2][1][1])
end
trainer.hookTestSample = function(trainer, sample)
-- update confusion matrix
confusion:add(trainer.module.output[1][1], sample[2][1][1])
end
trainer.hookTrainEpoch = function(trainer)
-- print confusion
print(confusion)
confusion:zero()
-- run on test_set
trainer:test(testData)
-- print confusion
print(confusion)
confusion:zero()
-- save net
local filename = paths.concat('scratch', (options.saveto or 'network-mnist')..'-'..os.date("%Y_%m_%d@%X"))
print('# saving network to '..filename)
trainer.module:writef(filename)
end
----------------------------------------------------------------------
-- run trainer
--
trainer:train(trainData)