-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathtrain_net.py
321 lines (280 loc) · 13.2 KB
/
train_net.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
import numpy as np
import numpy.random as nr
import theano
import theano.tensor as T
import lasagne as nn
import data as data_
import metrics
import sys
from importlib import import_module
import time
import os
from itertools import izip
import cPickle
# set random seed
nr.seed(int(time.time()))
##########################################################################################
# parse the arguments
if len(sys.argv) < 2:
sys.exit('Usage: train_net.py <model_name> [resume_file] [no_test]')
model_name = sys.argv[1]
resume_path = os.path.join('models', model_name)
if not os.path.exists(resume_path):
os.mkdir(resume_path)
test_flag = True
if sys.argv[-1] == 'no_test' :
test_flag = False
print 'no_test'
# resume training if specified
if (test_flag is True and len(sys.argv) > 2) or (test_flag is False and len(sys.argv) > 3):
print 'resume'
resume_file = sys.argv[2]
if not os.path.exists(resume_file):
sys.exit('Resume_file does not exist')
resume_data = np.load(resume_file)
exp_id = resume_data['exp_id']
resume_path, _ = os.path.split(resume_file)
else:
exp_id = '%s' % time.strftime('%Y%m%d-%H%M%S', time.localtime())
resume_path = os.path.join('models', model_name, exp_id)
if not os.path.exists(resume_path):
os.mkdir(resume_path)
##########################################################################################
# build the model
print
print "Experiment ID: %s" % exp_id
print
print "Building model"
model = import_module('models.%s' % model_name)
l_out = model.build_model()
x_shared, y_shared, idx, lr, iter_train, iter_valid=\
model.build_train_valid(l_out)
chunk_idx = 0
metrics = model.metrics
metric_names = model.metric_names
losses_train = []
scores_train = []
scores_valid = []
best_record = [0, 0]
# resume history information if neccessary
if 'resume_data' in dir():
print 'resume'
nn.layers.set_all_param_values(l_out, resume_data['param_values'])
chunk_idx = resume_data['chunk_idx']
losses_train = resume_data['losses_train']
scores_train = resume_data['scores_train']
scores_valid = resume_data['scores_valid']
best_record = resume_data['best_record']
data_.neg_pool = resume_data['neg_pool']
chunk_idcs = np.arange(chunk_idx, model.train_data_params['num_chunks'])
##########################################################################################
# load data, and get the data generation functions for each section
data, labels = data_.load(model.data_path)
# exclude the second series of second subject
data[1,1]=np.zeros([0,32],'float32')
labels[1,1]=np.zeros([0,6],'float32')
# for subject-specific training
#data = data[model.subjects, :][:]
#labels = labels[model.subjects, :][:]
data_.init_sample_cells(labels, model.events, model.train_series, model.valid_series)
train_data_gen = lambda: data_.chunk_gen(
getattr(data_, model.train_data_params['chunk_gen_fun'])(data[:, model.train_series],
labels[:, model.train_series],
model.events,
model.train_data_params))
valid_data_gen = lambda: data_.chunk_gen(
getattr(data_, model.valid_data_params['chunk_gen_fun'])(data[:, model.valid_series],
labels[:, model.valid_series],
model.events,
model.valid_data_params))
bs_data_gen = lambda: data_.chunk_gen(
getattr(data_, model.bs_data_params['chunk_gen_fun'])(data[:, model.train_series],
labels[:, model.train_series],
model.events,
model.bs_data_params))
##########################################################################################
do_validation = True
if 'test_valid' in model.test_data_params and model.test_data_params['test_valid'] == True:
do_validation = True
else:
do_validation = False
valid_result_folder = 'model_combine/all_valid_results/'
test_result_folder = 'model_combine/all_test_results/'
##########################################################################################
# start training
very_start = time.time()
for chunk_idx, (x_chunk, y_chunk, _) in izip(chunk_idcs, train_data_gen()):
start_time = time.time()
lr.set_value(model.lr_schedule(chunk_idx))
x_shared.set_value(x_chunk)
y_shared.set_value(y_chunk)
if chunk_idx == chunk_idcs[0]:
losses = []
preds_train = np.zeros((0, model.num_events), 'float32')
y_train = np.zeros((0, model.num_events), 'int32')
y_train = np.concatenate([y_train, y_chunk], axis = 0)
num_batches_chunk = model.train_data_params['chunk_size'] / model.batch_size
for b in np.arange(num_batches_chunk):
loss, pred = iter_train(b)
if np.isnan(loss):
raise RuntimeError("NaN Detected.")
losses.append(loss)
preds_train = np.concatenate([preds_train, pred], axis = 0)
if ((chunk_idx + 1) % model.display_freq) == 0:
print
print "Chunk %d/%d, lr = %.7f" % (chunk_idx + 1,
model.train_data_params['num_chunks'],
lr.get_value())
mean_train_loss = np.mean(losses)
print " mean training loss:\t\t%.6f" % mean_train_loss
losses_train.append(mean_train_loss)
scores = [chunk_idx + 1]
for i, metric in enumerate(metrics):
scores.append(metric(y_train, preds_train))
print " %s:" % metric_names[i]
print scores[-1]
scores_train.append(scores)
print " The best score is %f, obtained in %d chunks" % (best_record[1], best_record[0])
end_time = time.time()
print " elapsed time is %f seconds" % (end_time - start_time)
print " system time is ", time.strftime('%Y%m%d-%H%M%S', time.localtime())
print " elapsed time from the begining is %f seconds" % (end_time - very_start)
losses = []
preds_train = np.zeros((0, model.num_events), 'float32')
y_train = np.zeros((0, model.num_events), 'int32')
if ((chunk_idx + 1) % model.valid_freq) == 0 and do_validation is True:
print
print "Evaluating valid set"
start_time = time.time()
preds_valid = np.zeros((0, model.num_events), 'float32')
y_valid = np.zeros((0, model.num_events), 'int32')
for x_chunk, y_chunk, chunk_length in valid_data_gen():
y_valid = np.concatenate([y_valid, y_chunk[:chunk_length, :]], axis = 0)
num_batches = int(np.ceil(chunk_length / float(model.batch_size)))
x_shared.set_value(x_chunk)
chunk_output = np.zeros((0, model.num_events), 'float32')
for b in np.arange(num_batches):
pred = iter_valid(b)
chunk_output = np.concatenate((chunk_output, pred), axis = 0)
chunk_output = chunk_output[:chunk_length, :]
preds_valid= np.concatenate((preds_valid, chunk_output), axis = 0)
scores = [chunk_idx + 1]
for i, metric in enumerate(metrics):
scores.append(metric(y_valid, preds_valid))
print " %s:" % metric_names[i]
print scores[-1]
scores_valid.append(scores)
if best_record[1] < scores[-1][-1]:
best_record[0] = chunk_idx + 1
best_record[1] = scores[-1][-1]
print " The best score is %f, obtained in %d chunks" % (best_record[1], best_record[0])
end_time = time.time()
print " elapsed time is %f seconds" % (end_time - start_time)
print
if ((chunk_idx + 1) % model.bs_freq == 0) and (chunk_idx != chunk_idcs[-1]):
print
print "Bootstrap the training set"
start_time = time.time()
preds_bs = np.zeros((0, model.num_events), 'float32')
y_bs = np.zeros((0, model.num_events), 'int32')
for x_chunk, y_chunk, chunk_length in bs_data_gen():
y_bs = np.concatenate([y_bs, y_chunk[:chunk_length, :]], axis = 0)
num_batches = int(np.ceil(chunk_length / float(model.batch_size)))
x_shared.set_value(x_chunk)
chunk_output = np.zeros((0, model.num_events), 'float32')
for b in np.arange(num_batches):
pred = iter_valid(b)
chunk_output = np.concatenate((chunk_output, pred), axis = 0)
chunk_output = chunk_output[:chunk_length, :]
preds_bs = np.concatenate((preds_bs, chunk_output), axis = 0)
scores = [chunk_idx + 1]
for i, metric in enumerate(metrics):
scores.append(metric(y_bs, preds_bs))
print " %s:" % metric_names[i]
print scores[-1]
data_.bootstrap(y_bs, preds_bs)
end_time = time.time()
print " elapsed time is %f seconds" % (end_time - start_time)
print
if ((chunk_idx + 1) % model.save_freq) == 0:
print
print "Saving model"
save_path = os.path.join(resume_path, '%d' % (chunk_idx + 1))
with open(save_path, 'w') as f:
cPickle.dump({
'model': model_name,
'exp_id': exp_id,
'chunk_idx': chunk_idx + 1,
'losses_train': losses_train,
'scores_train': scores_train,
'scores_valid': scores_valid,
'best_record': best_record,
'param_values': nn.layers.get_all_param_values(l_out),
'neg_pool': data_.neg_pool
}, f, cPickle.HIGHEST_PROTOCOL)
##########################################################################################
# test all valid and save results
if 'test_valid' in model.test_data_params and model.test_data_params['test_valid'] == True:
data, labels = data_.load(model.data_path)
test_valid_data_gen = lambda: data_.chunk_gen(
getattr(data_, model.test_valid_params['chunk_gen_fun'])(data[:, model.valid_series],
labels[:, model.valid_series],
model.events,
model.test_valid_params))
print
print "Testing all valid samples"
start_time = time.time()
preds_test = np.zeros((0, model.num_events), 'float32')
y_test = np.zeros((0, model.num_events), 'int32')
idx = 1
for x_chunk, y_chunk, chunk_length in test_valid_data_gen():
t1 = time.time()
y_test = np.concatenate([y_test, y_chunk[:chunk_length, :]], axis = 0)
num_batches = int(np.ceil(chunk_length / float(model.batch_size)))
x_shared.set_value(x_chunk)
chunk_output = np.zeros((0, model.num_events), 'float32')
for b in np.arange(num_batches):
pred = iter_valid(b)
chunk_output = np.concatenate((chunk_output, pred), axis = 0)
chunk_output = chunk_output[:chunk_length, :]
preds_test= np.concatenate((preds_test, chunk_output), axis = 0)
t2 = time.time()
idx += 1
save_valid_name = model_name[:-2] + str(model.valid_series[0]) + str(model.valid_series[1])
save_path = os.path.join(valid_result_folder, 'test_valid_' + save_valid_name + '.npy')
np.save(save_path, [y_test, preds_test])
end_time = time.time()
print " elapsed time is %f seconds" % (end_time - start_time)
##########################################################################################
# test
if ((not model.test_data_params.has_key('test')) or model.test_data_params['test'] == True) and test_flag is True:
data, labels = data_.load('eeg_test.npy')
model.test_data_params['section'] = 'test'
test_data_gen = lambda: data_.chunk_gen(
getattr(data_, model.test_data_params['chunk_gen_fun'])(data,
labels,
model.events,
model.test_data_params))
print
print "Testing"
start_time = time.time()
preds_test = np.zeros((0, model.num_events), 'float32')
y_test = np.zeros((0, model.num_events), 'int32')
idx = 1
for x_chunk, y_chunk, chunk_length in test_data_gen():
t1 = time.time()
y_test = np.concatenate([y_test, y_chunk[:chunk_length, :]], axis = 0)
num_batches = int(np.ceil(chunk_length / float(model.batch_size)))
x_shared.set_value(x_chunk)
chunk_output = np.zeros((0, model.num_events), 'float32')
for b in np.arange(num_batches):
pred = iter_valid(b)
chunk_output = np.concatenate((chunk_output, pred), axis = 0)
chunk_output = chunk_output[:chunk_length, :]
preds_test= np.concatenate((preds_test, chunk_output), axis = 0)
t2 = time.time()
idx += 1
save_path = os.path.join(test_result_folder, 'test_' + model_name + '.npy')
np.save(save_path, [y_test, preds_test])
end_time = time.time()
print " elapsed time is %f seconds" % (end_time - start_time)