-
Notifications
You must be signed in to change notification settings - Fork 128
/
trainer.lua
223 lines (187 loc) · 5.93 KB
/
trainer.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
require 'nn'
require 'sys'
require 'torch'
require 'util'
local Trainer = torch.class('Trainer')
-- Perform one epoch of training.
function Trainer:train(train_data, train_labels, model, criterion, optim_method, layers, state, params, grads, opt)
model:training()
local train_size = train_data:size(1)
local timer = torch.Timer()
local time = timer:time().real
local total_err = 0
local classes = {}
for i = 1, opt.num_classes do
table.insert(classes, i)
end
local confusion = optim.ConfusionMatrix(classes)
confusion:zero()
local config -- for optim
if opt.optim_method == 'adadelta' then
config = { rho = 0.95, eps = 1e-6 }
elseif opt.optim_method == 'adam' then
config = {}
end
-- shuffle batches
local num_batches = math.floor(train_size / opt.batch_size)
local shuffle = torch.randperm(num_batches)
for i = 1, shuffle:size(1) do
local t = (shuffle[i] - 1) * opt.batch_size + 1
local batch_size = math.min(opt.batch_size, train_size - t + 1)
-- data samples and labels, in mini batches.
local inputs = train_data:narrow(1, t, batch_size)
local targets = train_labels:narrow(1, t, batch_size)
if opt.cudnn == 1 then
inputs = inputs:cuda()
targets = targets:cuda()
else
inputs = inputs:double()
targets = targets:double()
end
-- closure to return err, df/dx
local func = function(x)
-- get new parameters
if x ~= params then
params:copy(x)
end
-- reset gradients
grads:zero()
-- forward pass
local outputs = model:forward(inputs)
local err = criterion:forward(outputs, targets)
-- track errors and confusion
total_err = total_err + err * batch_size
for j = 1, batch_size do
confusion:add(outputs[j], targets[j])
end
-- compute gradients
local df_do = criterion:backward(outputs, targets)
model:backward(inputs, df_do)
if opt.model_type == 'static' then
-- don't update embeddings for static model
layers.w2v.gradWeight:zero()
elseif opt.model_type == 'multichannel' then
-- keep one embedding channel static
layers.chan1.gradWeight:zero()
end
return err, grads
end
-- gradient descent
optim_method(func, params, config, state)
-- reset padding embedding to zero
layers.w2v.weight[1]:zero()
if opt.model_type == 'multichannel' then
layers.chan1.weight[1]:zero()
end
if opt.skip_kernel > 0 then
-- keep skip kernel at zero
layers.skip_conv.weight:select(3,3):zero()
end
-- Renorm (Euclidean projection to L2 ball)
local renorm = function(row)
local n = row:norm()
row:mul(opt.L2s):div(1e-7 + n)
end
-- renormalize linear row weights
local w = layers.linear.weight
for j = 1, w:size(1) do
renorm(w[j])
end
end
if opt.debug == 1 then
print('Total err: ' .. total_err / train_size)
print(confusion)
end
-- time taken
time = timer:time().real - time
time = opt.batch_size * time / train_size
if opt.debug == 1 then
print("==> time to learn 1 batch = " .. (time*1000) .. 'ms')
end
-- return error percent
confusion:updateValids()
return confusion.totalValid
end
function Trainer:test(test_data, test_labels, model, criterion, layers, dump_features, opt)
model:evaluate()
local classes = {}
for i = 1, opt.num_classes do
table.insert(classes, i)
end
local confusion = optim.ConfusionMatrix(classes)
confusion:zero()
local preds_file
if opt.test_only == 1 and opt.preds_file ~= '' then
print('Writing predictions to ' .. opt.preds_file)
preds_file = io.open(opt.preds_file, 'w')
end
-- dump feature maps
local feature_maps
local conv_layer = get_layer(model, 'convolution')
local test_size = test_data:size(1)
local total_err = 0
for t = 1, test_size, opt.batch_size do
-- data samples and labels, in mini batches.
local batch_size = math.min(opt.batch_size, test_size - t + 1)
local inputs = test_data:narrow(1, t, batch_size)
local targets = test_labels:narrow(1, t, batch_size)
if opt.cudnn == 1 then
inputs = inputs:cuda()
targets = targets:cuda()
else
inputs = inputs:double()
targets = targets:double()
end
local outputs = model:forward(inputs)
-- dump feature maps from model forward
local cur_feature_maps
if dump_features then
if opt.cudnn == 1 then
cur_feature_maps = conv_layer.output:squeeze(4)
else
cur_feature_maps = conv_layer.output
end
if feature_maps == nil then
feature_maps = cur_feature_maps
else
feature_maps = torch.cat(feature_maps, cur_feature_maps, 1)
end
end
if opt.test_only == 1 and opt.preds_file ~= '' then
-- write predictions to file
local _,preds = torch.max(outputs, 2)
for j = 1, preds:size(1) do
-- zero index
preds_file:write((preds[j][1] - 1) .. '\n')
end
end
local err = criterion:forward(outputs, targets)
total_err = total_err + err * batch_size
for i = 1, batch_size do
confusion:add(outputs[i], targets[i])
end
end
if opt.debug == 1 then
print(confusion)
print('Total err: ' .. total_err / test_size)
end
if dump_features then
assert(#opt.kernels == 1, 'multiple kernels not yet supported')
local kernel = opt.kernels[1]
local word_idxs = test_data:narrow(2, kernel, test_data:size(2) - kernel + 1)
assert(feature_maps:size(1) == word_idxs:size(1), 'length mismatch')
local filename = opt.dump_feature_maps_file .. '.hdf5'
print('dumping features to ' .. filename)
local f = hdf5.open(filename, 'w')
f:write('feature_maps', feature_maps:double())
f:write('word_idxs', word_idxs:long())
f:close()
end
if opt.test_only == 1 and opt.preds_file ~= '' then
preds_file:close()
end
-- return error percent
confusion:updateValids()
return confusion.totalValid
end
return Trainer