-
Notifications
You must be signed in to change notification settings - Fork 181
/
train.lua
292 lines (234 loc) · 9.26 KB
/
train.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
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
-- TRAIN
require "torch"
require "nn"
require "image"
require "optim"
require "model"
require "DataLoader"
local utils = require "utils"
local cmd = torch.CmdLine()
-- Dataset options
cmd:option("-trainList", "data/one-indexed-files-notrash_train.txt") -- necessary
cmd:option("-valList", "data/one-indexed-files-notrash_val.txt") -- necessary
cmd:option("-testList", "data/one-indexed-files-notrash_test.txt") -- necessary
cmd:option("-numClasses", 5) -- necessary
cmd:option("-inputHeight", "384")
cmd:option("-inputWidth", "384")
cmd:option("-scaledHeight", "256") -- uses original height if unprovided
cmd:option("-scaledWidth", "256") -- uses original width if unprovided
cmd:option("-numChannels", 3)
cmd:option("-batchSize", 32)
cmd:option("-dataFolder", "data/pics")
-- Optimization options
cmd:option("-numEpochs", 100)
cmd:option("-learningRate", 1.25e-5) -- 2.5e-5 works well; 1e-5 is second best
cmd:option("-lrDecayFactor", 0.9, "newLR = oldLR * <lrDecayFactor>")
cmd:option("-lrDecayEvery", 20, "learning rate is decayed every <lrDecayEver> epochs")
cmd:option("-weightDecay", 2.5e-2, "L2 regularization")
cmd:option("-weightInitializationMethod", "kaiming", "heuristic, xavier, xavier_caffe, or none")
-- Output options
cmd:option("-printEvery", 1, "prints and saves the train and val acc and loss every <printEvery> epochs")
cmd:option("-checkpointEvery", 20, "saves a snapshot of the model every <checkpointEvery> epochs")
cmd:option("-checkpointName", "checkpoints/checkpoint", "checkpoint will be saved at ./<checkpointName>_#.t7")
-- Backend options
cmd:option("-cuda", 1)
cmd:option("-gpu", 0)
cmd:option("-scale", 1, "proportion of filters used in the architecture")
local opt = cmd:parse(arg)
-- Torch cmd parses user input as strings so we need to convert number strings to numbers
for k, v in pairs(opt) do
if tonumber(v) then
opt[k] = tonumber(v)
end
end
assert(opt.trainList ~= "", "Need a list of train items.")
assert(opt.valList ~= "", "Need a list of val items.")
assert(opt.testList ~= "", "Need a list of test items.")
assert(opt.numClasses ~= "", "Need the number of image classes.")
assert(opt.dataFolder ~= "", "Need the folder relative to this file where the pictures are stored.")
if opt.scaledHeight == "" then
opt.scaledHeight = opt.inputHeight
end
if opt.scaledWidth == "" then
opt.scaledWidth = opt.inputWidth
end
-- Set up GPU
opt.dtype = "torch.FloatTensor"
if opt.gpu >= 0 and opt.cuda == 1 then
require "cunn"
require "cutorch"
opt.dtype = "torch.CudaTensor"
cutorch.setDevice(opt.gpu + 1)
end
-- Initialize DataLoader to receive batch data
utils.printTime("Initializing DataLoader")
local loader = DataLoader(opt)
-- Initialize model and criterion
utils.printTime("Initializing model and criterion")
local model = model(opt):type(opt.dtype)
if opt.weightInitializationMethod ~= "none" then
model = require("weight-init")(model, opt.weightInitializationMethod)
end
local criterion = nn.ClassNLLCriterion():type(opt.dtype)
-- Initialize history tables
trainLossHistory = {}
trainAccHistory = {}
valLossHistory = {}
valAccHistory = {}
epochs = {}
--[[
Input:
- model: a CNN
Trains a fresh CNN from end to end. Uses the opt parameters declared above.
]]--
function train(model)
utils.printTime("Starting training for %d epochs" % opt.numEpochs)
local config = {
learningRate = opt.learningRate,
weightDecay = opt.weightDecay
}
local params, gradParams = model:getParameters()
local feval = function(x)
assert(x == params)
gradParams:zero()
local batch = loader:nextBatch("train", true)
if opt.cuda == 1 then
batch.data = batch.data:cuda()
batch.labels = batch.labels:cuda()
end
local scores = model:forward(batch.data) -- opt.batchSize x NUM_CLASSES
local loss = criterion:forward(scores, batch.labels)
local gradScores = criterion:backward(scores, batch.labels) -- opt.batchSize x NUM_CLASSES
model:backward(batch.data, gradScores)
return loss, gradParams
end
local epochLoss = {}
local iterationsPerEpoch = math.ceil(loader.splits.train.count / opt.batchSize)
local numIterations = opt.numEpochs * iterationsPerEpoch
-- Turn on Dropout
model:training()
for i = 1, numIterations do
collectgarbage()
local epoch = math.floor((i - 1) / iterationsPerEpoch) + 1
local _, loss = optim.adam(feval, params, config)
table.insert(epochLoss, loss[1])
local iterationCompleted = i % iterationsPerEpoch
if iterationCompleted == 0 then
iterationCompleted = iterationsPerEpoch
end
if iterationCompleted % 10 == -1 then
utils.printTime("Epoch %d/%d: finished %d/%d iterations" % {epoch, opt.numEpochs, iterationCompleted, iterationsPerEpoch})
end
-- end of an epoch
if #epochLoss % iterationsPerEpoch == 0 then
if epoch % opt.lrDecayEvery == 0 then
local oldLearningRate = config.learningRate
config = {
learningRate = oldLearningRate * opt.lrDecayFactor,
weightDecay = opt.weightDecay
}
end
-- Calculate and print the epoch loss
epochLoss = torch.mean(torch.Tensor(epochLoss))
if (opt.printEvery > 0 and epoch % opt.printEvery == 0) then
-- Add current epoch number to history
table.insert(epochs, epoch)
local _, trainAcc, _ = test(model, "train")
table.insert(trainLossHistory, epochLoss)
table.insert(trainAccHistory, trainAcc)
local valLoss, valAcc, _ = test(model, "val")
table.insert(valLossHistory, valLoss)
table.insert(valAccHistory, valAcc)
utils.printTime("Epoch %d/%d: train acc: %f, train loss: %f, val acc: %f, val loss: %f" % {epoch, opt.numEpochs, trainAcc, epochLoss, valAcc, valLoss})
-- Turn Dropout back on
model:training()
end
-- Clear this table for the next epoch
epochLoss = {}
-- Save a checkpoint of the model, its opt parameters, the training loss history, and the testing loss history
if (opt.checkpointEvery > 0 and epoch % opt.checkpointEvery == 0) or epoch == opt.numEpochs then
local checkpoint = {
opt = opt,
trainLossHistory = trainLossHistory,
trainAccHistory = trainAccHistory,
valLossHistory = valLossHistory,
valAccHistory = valAccHistory,
epochs = epochs
}
local filename
if epoch == opt.numEpochs then
filename = "%s_%s.t7" % {opt.checkpointName, "final"}
else
filename = "%s_%d.t7" % {opt.checkpointName, epoch}
end
-- Make sure the output directory exists before we try to write it
paths.mkdir(paths.dirname(filename))
-- Clear intermediate states in the model before saving to disk to save memory
model:clearState()
-- Cast model to float so it can be used on CPU
model:float()
checkpoint.model = model
torch.save(filename, checkpoint)
-- Cast model back so that it can continue to be used
model:type(opt.dtype)
params, gradParams = model:getParameters()
-- utils.printTime("Saved checkpoint model for epoch %d and opt at %s" % {epoch, filename})
collectgarbage()
end
end
end
utils.printTime("Finished training")
end
--[[
Inputs:
- model: a CNN
- split: "train", "val", or "test"
Outputs:
- loss: average loss per item in this split
- accuracy: accuracy on this split
- confusion: an optim.ConfusionMatrix object
Performs image classification using a given nn module.
]]--
function test(model, split)
assert(split == "train" or split == "val" or split == "test")
collectgarbage()
-- utils.printTime("Starting evaluation on the %s split" % split)
-- Turn off Dropout
model:evaluate()
local confusion = optim.ConfusionMatrix(opt.numClasses)
local evalData = {
predictedLabels = {},
trueLabels = {},
loss = {}
}
local numIterations = math.ceil(loader.splits[split].count / opt.batchSize)
for i = 1, numIterations do
local batch = loader:nextBatch(split, false)
if opt.cuda == 1 then
batch.data = batch.data:cuda()
batch.labels = batch.labels:cuda()
end
local scores = model:forward(batch.data) -- batchSize x numClasses
local _, predictedLabels = torch.max(scores, 2)
table.insert(evalData.predictedLabels, predictedLabels:double())
table.insert(evalData.trueLabels, batch.labels:reshape(batch:size(), 1):double())
local loss = criterion:forward(scores, batch.labels)
table.insert(evalData.loss, loss)
collectgarbage()
end
evalData.predictedLabels = torch.cat(evalData.predictedLabels, 1)
evalData.trueLabels = torch.cat(evalData.trueLabels, 1)
confusion:batchAdd(evalData.predictedLabels, evalData.trueLabels)
local loss = torch.mean(torch.Tensor(evalData.loss))
local accuracy = torch.sum(torch.eq(evalData.predictedLabels, evalData.trueLabels)) / evalData.trueLabels:size()[1]
return loss, accuracy, confusion
end
for k, v in pairs(opt) do
utils.printTime("%s = %s" % {k, v})
end
train(model)
utils.printTime("Final accuracy on the train set: %f" % trainAccHistory[#trainAccHistory])
utils.printTime("Final accuracy on the val set: %f" % valAccHistory[#valAccHistory])
local _, testAcc, testConfusion = test(model, "test", True)
utils.printTime("Final accuracy on the test set: %f" % testAcc)
print(testConfusion)