-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain01.py
318 lines (219 loc) · 9.31 KB
/
train01.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
#!/usr/bin/env python
import time
import numpy as np
import os, sys
# Keras complains for the convolutional layers
# that border_mode 'same' is not supported with the
# Theano backend (see e.g. https://github.com/fchollet/keras/blob/master/keras/backend/theano_backend.py#L634 )
#
# but from here: https://www.tensorflow.org/versions/master/get_started/os_setup.html#pip-installation it
# looks like on MacOS, only CPU is supported, not the GPU...
#
# from here: https://github.com/fchollet/keras/wiki/Keras,-now-running-on-TensorFlow#performance
# it also looks like Theano is more performant in some cases (but much worse in others)
#
# edit the 'backend' parameter in ~/.keras/keras.json
sys.path.insert(0, os.path.expanduser("~/keras"))
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.optimizers import SGD
from keras.callbacks import EarlyStopping, ModelCheckpoint, Callback
from ROCModelCheckpoint import ROCModelCheckpoint
sys.path.append(os.path.expanduser("~/torchio")); import torchio
#----------------------------------------------------------------------
outputDir = "results/" + time.strftime("%Y-%m-%d-%H%M%S")
#----------------------------------------------------------------------
# see http://keras.io/callbacks/ for the Callback interface
class LossHistory(Callback):
def __init__(self, logfile = None):
self.fouts = [ sys.stdout ]
if logfile != None:
self.fouts.append(logfile)
#----------------------------------------
def on_train_begin(self, logs={}):
self.losses = []
#----------------------------------------
def on_batch_end(self, batch, logs={}):
# logs has the following keys:
# 'acc', 'loss', 'batch', 'size'
loss = logs.get('loss')
self.losses.append(loss)
def on_epoch_end(self, epoch, logs={}):
loss = np.mean(self.losses)
for fout in self.fouts:
print >> fout,"mean loss=",loss
fout.flush()
#----------------------------------------------------------------------
class EpochStartBanner(Callback):
# prints a banner when a new training epoch is started
def __init__(self, outputDir, logfile = None):
self.outputDir = outputDir
self.fouts = [ sys.stdout ]
if logfile != None:
self.fouts.append(logfile)
def on_epoch_begin(self, epoch, logs={}):
nowStr = time.strftime("%Y-%m-%d %H:%M:%S")
for fout in self.fouts:
print >> fout, "----------------------------------------"
print >> fout, "starting epoch %d at" % (epoch + 1), nowStr
print >> fout, "----------------------------------------"
print >> fout, "output directory is",self.outputDir
fout.flush()
#----------------------------------------------------------------------
class TrainingTimeMeasurement(Callback):
# use this as first callback (assuming no other callbacks do a significant
# amount of computation before the start of the batch)
def __init__(self, numTrainingSamples, logfile = None):
super(Callback, self).__init__()
self.numTrainingSamples = numTrainingSamples
self.fouts = [ sys.stdout ]
if logfile != None:
self.fouts.append(logfile)
def on_epoch_begin(self, epoch, logs={}):
self.epochStartTime = time.time()
def on_epoch_end(self, epoch, logs={}):
deltaT = time.time() - self.epochStartTime
for fout in self.fouts:
# TODO: need to know number of training samples
print >> fout, "time to learn 1 sample: %.3f ms" % ( deltaT / self.numTrainingSamples * 1000.0)
print >> fout, "time to train entire batch: %.2f min" % (deltaT / 60.0)
fout.flush()
#----------------------------------------------------------------------
def datasetLoadFunction(dataDesc, size, cuda):
# returns trainData, testData
assert dataDesc['inputDataIsSparse'], "non-sparse input data is currently not supported"
retval = []
for filesKey, sizeKey in (
('train_files', 'trsize'),
('test_files', 'tesize')):
# get the number of events to be read from each file
thisSize = dataDesc.get(sizeKey, None)
for fname in dataDesc[filesKey]:
print "opening",fname
thisData = torchio.read(fname)
# typical structure:
# {'y': <torchio.torch.FloatTensor instance at 0x7f05052000e0>,
# 'X': {
# 'y': <torchio.torch.IntTensor instance at 0x7f05054abcf8>,
# 'x': <torchio.torch.IntTensor instance at 0x7f05054abb90>,
# 'energy': <torchio.torch.FloatTensor instance at 0x7f05054ab998>,
# 'firstIndex': <torchio.torch.IntTensor instance at 0x7f05054abe60>,
# 'numRecHits': <torchio.torch.IntTensor instance at 0x7f05054ab878>},
# 'mvaid': <torchio.torch.FloatTensor instance at 0x7f0505200200>,
# 'weight': <torchio.torch.FloatTensor instance at 0x7f05054abfc8>}
return retval
#----------------------------------------------------------------------
# main
#----------------------------------------------------------------------
ARGV = sys.argv[1:]
assert len(ARGV) == 2, "usage: " + os.path.basename(sys.argv[0]) + " modelFile.py dataFile.py"
execfile(ARGV[0])
execfile(ARGV[1])
#----------
havePylab = False
try:
import pylab
havePylab = True
except ImportError:
pass
if havePylab:
pylab.close('all')
print "loading data"
cuda = True
trainData, trsize = datasetLoadFunction(dataDesc['train_files'], dataDesc['trsize'], cuda)
testData, tesize = datasetLoadFunction(dataDesc['test_files'], dataDesc['tesize'], cuda)
# convert labels from -1..+1 to 0..1 for cross-entropy loss
# must clone to assign
def cloneFunc(data):
return dict( [( key, np.copy(value) ) for key, value in data.items() ])
### retval = {}
### for key, value in data.items():
### retval[key] = np.
trainData = cloneFunc(trainData); testData = cloneFunc(testData)
# TODO: normalize these to same weight for positive and negative samples
trainWeights = trainData['weights']
testWeights = testData['weights']
#----------
print "building model"
model = makeModel()
#----------
if not os.path.exists(outputDir):
os.makedirs(outputDir)
logfile = open(os.path.join(outputDir, "train.log"), "w")
#----------
# write out BDT/MVA id labels (for performance comparison)
#----------
for name, weights, label, output in (
('train', trainWeights, trainData['labels'], trainData['mvaid']),
('test', testWeights, testData['labels'], testData['mvaid']),
):
np.savez(os.path.join(outputDir, "roc-data-%s-mva.npz" % name),
weight = weights,
output = output,
label = label)
#----------
print "----------"
print "model:"
print model.summary()
print "----------"
print "the model has",model.count_params(),"parameters"
print >> logfile,"----------"
print >> logfile,"model:"
model.summary(file = logfile)
print >> logfile,"----------"
print >> logfile, "the model has",model.count_params(),"parameters"
logfile.flush()
# see e.g. https://github.com/ml-slac/deep-jets/blob/master/training/conv-train.py#L81
### model.compile(loss='binary_crossentropy', optimizer='adam', class_mode='binary')
model.compile(loss='binary_crossentropy',
# optimizer=SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True),
optimizer = 'adam',
)
print 'starting training at', time.asctime()
trainLossHistory = LossHistory(logfile)
trainAuc = ROCModelCheckpoint(outputDir, 'train', trainData['input'], trainData['labels'], trainWeights, verbose=True, logFile = logfile)
testAuc = ROCModelCheckpoint(outputDir, 'test', testData['input'], testData['labels'], testWeights, verbose=True, logFile = logfile)
callbacks = [
TrainingTimeMeasurement(len(trainData['labels']), logfile),
EpochStartBanner(outputDir, logfile),
trainAuc,
testAuc,
trainLossHistory,
]
# history will not be set if one presses CTRL-C...
history = None
try:
history = model.fit(
trainData['input'], trainData['labels'],
sample_weight = trainWeights,
# sample_weight=np.power(weights, 0.7))
batch_size = 32,
nb_epoch = 1000,
# show_accuracy = True,
shuffle = True, # shuffle at each epoch (but this is the default)
validation_data = (testData['input'], testData['labels']),
callbacks = callbacks,
)
except KeyboardInterrupt:
print
print 'interrupted'
#--------------------
def makePlots():
import pylab
# training loss
pylab.figure()
pylab.plot(trainLossHistory.losses)
pylab.xlabel('iteration')
pylab.ylabel('training loss')
pylab.title('train loss')
pylab.savefig(outputDir + "/" + "train-loss.png")
# test AUCs
pylab.figure()
pylab.plot(testAuc.aucs)
pylab.xlabel('epoch')
pylab.ylabel('test set AUC')
pylab.title('test AUC')
pylab.savefig(outputDir + "/" + "test-auc.png")
print "saved plots to",outputDir
#--------------------