-
Notifications
You must be signed in to change notification settings - Fork 1
/
keras_hierarchy.py
548 lines (479 loc) · 23.1 KB
/
keras_hierarchy.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
'''Train a simple deep CNN on the CIFAR10 small images dataset.
GPU run command:
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cifar10_cnn.py
It gets down to 0.65 test logloss in 25 epochs, and down to 0.55 after 50 epochs.
(it's still underfitting at that point, though).
Note: the data was pickled with Python 2, and some encoding issues might prevent you
from loading it in Python 3. You might have to load it in Python 2,
save it in a different format, load it in Python 3 and repickle it.
'''
# Concatenating the coarse and fine labels into one larger vector of 120 dimensions
from __future__ import print_function
pretrain = False # if the model should load pretrained weights
pretrain_name = '2output_original_rmsprop_categorical_crossentropy_e7_aFalse'
training = True # if the network should train, or just load the weights from elsewhere
optimizer = 'sgd'#'rmsprop'
model_style = 'split'#'wider'
nb_epoch = 10#500
learning_rate = 0.01#0.01
data_augmentation = False#True
objective = 'mse' # objective function to use
model_name = '%s_%s_%s_e%s_a%s' % (model_style, optimizer, objective, nb_epoch, data_augmentation)
if optimizer == 'sgd':
model_name += '_lr%s' % learning_rate
if pretrain:
model_name += '_pre'
gpu = 'gpu1'
import os
os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=%s,floatX=float32" % gpu
from keras.datasets import cifar10, cifar100
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, Graph
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.optimizers import SGD
from keras.utils import np_utils
import cPickle as pickle
import numpy as np
from network_utils import accuracy, accuracy_hierarchy, clean_hierarchy_vec
# Open an IPython session if an exception is found
import sys
from IPython.core import ultratb
sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=1)
batch_size = 32
nb_classes_fine = 100
nb_classes_coarse = 20
# input image dimensions
img_rows, img_cols = 32, 32
# the CIFAR10 images are RGB
img_channels = 3
# the data, shuffled and split between train and test sets
(X_train, y_train_fine), (X_test, y_test_fine) = cifar100.load_data(label_mode='fine')
(_, y_train_coarse), (_, y_test_coarse) = cifar100.load_data(label_mode='coarse')
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
print('y_train_fine shape:', y_train_fine.shape)
print('y_train_coarse shape:', y_train_coarse.shape)
# convert class vectors to binary class matrices
Y_train_fine = np_utils.to_categorical(y_train_fine, nb_classes_fine)
Y_train_coarse = np_utils.to_categorical(y_train_coarse, nb_classes_coarse)
Y_test_fine = np_utils.to_categorical(y_test_fine, nb_classes_fine)
Y_test_coarse = np_utils.to_categorical(y_test_coarse, nb_classes_coarse)
print('Y_train_fine shape:', Y_train_fine.shape)
print('Y_train_coarse shape:', Y_train_coarse.shape)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print(model_name)
Y_train = np.concatenate((Y_train_coarse, Y_train_fine), axis=1)
Y_test = np.concatenate((Y_test_coarse, Y_test_fine), axis=1)
model = Graph()
model.add_input(name='input', input_shape=(img_channels, img_rows, img_cols))
if model_style == 'original':
model.add_node(Convolution2D(32, 3, 3, border_mode='same',
input_shape=(img_channels, img_rows, img_cols)),
name='conv1', input='input')
model.add_node(Activation('relu'),
name='relu1', input='conv1')
model.add_node(Convolution2D(32, 3, 3),
name='conv2', input='relu1')
model.add_node(Activation('relu'),
name='relu2', input='conv2')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool1', input='relu2')
model.add_node(Dropout(0.25),
name='drop1', input='pool1')
model.add_node(Convolution2D(64, 3, 3, border_mode='same'),
name='conv3', input='drop1')
model.add_node(Activation('relu'),
name='relu3', input='conv3')
model.add_node(Convolution2D(64, 3, 3),
name='conv4', input='relu3')
model.add_node(Activation('relu'),
name='relu4', input='conv4')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool2', input='relu4')
model.add_node(Dropout(0.25),
name='drop2', input='pool2')
model.add_node(Flatten(),
name='flat1', input='drop2')
model.add_node(Dense(512),
name='dense1', input='flat1')
model.add_node(Activation('relu'),
name='relu5', input='dense1')
model.add_node(Dropout(0.5),
name='drop3', input='relu5')
#model.add_node(Dense(nb_classes_coarse + nb_classes_fine),
# name='dense2', input='drop3')
model.add_node(Dense(nb_classes_coarse),
name='dense_c', input='drop3')
model.add_node(Activation('softmax'),
name='soft_c', input='dense_c')
model.add_node(Dense(nb_classes_fine),
name='dense_f', input='drop3')
model.add_node(Activation('softmax'),
name='soft_f', input='dense_f')
if model_style == 'nodroporiginal':
model.add_node(Convolution2D(32, 3, 3, border_mode='same',
input_shape=(img_channels, img_rows, img_cols)),
name='conv1', input='input')
model.add_node(Activation('relu'),
name='relu1', input='conv1')
model.add_node(Convolution2D(32, 3, 3),
name='conv2', input='relu1')
model.add_node(Activation('relu'),
name='relu2', input='conv2')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool1', input='relu2')
model.add_node(Convolution2D(64, 3, 3, border_mode='same'),
name='conv3', input='pool1')
model.add_node(Activation('relu'),
name='relu3', input='conv3')
model.add_node(Convolution2D(64, 3, 3),
name='conv4', input='relu3')
model.add_node(Activation('relu'),
name='relu4', input='conv4')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool2', input='relu4')
model.add_node(Flatten(),
name='flat1', input='pool2')
model.add_node(Dense(512),
name='dense1', input='flat1')
model.add_node(Activation('relu'),
name='relu5', input='dense1')
#model.add_node(Dense(nb_classes_coarse + nb_classes_fine),
# name='dense2', input='drop3')
model.add_node(Dense(nb_classes_coarse),
name='dense_c', input='relu5')
model.add_node(Activation('softmax'),
name='soft_c', input='dense_c')
model.add_node(Dense(nb_classes_fine),
name='dense_f', input='relu5')
model.add_node(Activation('softmax'),
name='soft_f', input='dense_f')
elif model_style == 'moredense':
model.add_node(Convolution2D(32, 3, 3, border_mode='same',
input_shape=(img_channels, img_rows, img_cols)),
name='conv1', input='input')
model.add_node(Activation('relu'),
name='relu1', input='conv1')
model.add_node(Convolution2D(32, 3, 3),
name='conv2', input='relu1')
model.add_node(Activation('relu'),
name='relu2', input='conv2')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool1', input='relu2')
model.add_node(Dropout(0.25),
name='drop1', input='pool1')
model.add_node(Convolution2D(64, 3, 3, border_mode='same'),
name='conv3', input='drop1')
model.add_node(Activation('relu'),
name='relu3', input='conv3')
model.add_node(Convolution2D(64, 3, 3),
name='conv4', input='relu3')
model.add_node(Activation('relu'),
name='relu4', input='conv4')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool2', input='relu4')
model.add_node(Dropout(0.25),
name='drop2', input='pool2')
model.add_node(Flatten(),
name='flat1', input='drop2')
model.add_node(Dense(512),
name='dense1', input='flat1')
model.add_node(Activation('relu'),
name='relu5', input='dense1')
model.add_node(Dropout(0.25),
name='drop3', input='relu5')
model.add_node(Dense(512),
name='dense2', input='drop3')
model.add_node(Activation('relu'),
name='relu6', input='dense2')
model.add_node(Dropout(0.25),
name='drop4', input='relu6')
#model.add_node(Dense(nb_classes_coarse + nb_classes_fine),
# name='dense2', input='drop3')
model.add_node(Dense(nb_classes_coarse),
name='dense_c', input='drop4')
model.add_node(Activation('softmax'),
name='soft_c', input='dense_c')
model.add_node(Dense(nb_classes_fine),
name='dense_f', input='drop4')
model.add_node(Activation('softmax'),
name='soft_f', input='dense_f')
elif model_style == 'wider':
model.add_node(Convolution2D(48, 3, 3, border_mode='same',
input_shape=(img_channels, img_rows, img_cols)),
name='conv1', input='input')
model.add_node(Activation('relu'),
name='relu1', input='conv1')
model.add_node(Convolution2D(48, 3, 3),
name='conv2', input='relu1')
model.add_node(Activation('relu'),
name='relu2', input='conv2')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool1', input='relu2')
model.add_node(Dropout(0.25),
name='drop1', input='pool1')
model.add_node(Convolution2D(96, 3, 3, border_mode='same'),
name='conv3', input='drop1')
model.add_node(Activation('relu'),
name='relu3', input='conv3')
model.add_node(Convolution2D(96, 3, 3),
name='conv4', input='relu3')
model.add_node(Activation('relu'),
name='relu4', input='conv4')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool2', input='relu4')
model.add_node(Dropout(0.25),
name='drop2', input='pool2')
model.add_node(Flatten(),
name='flat1', input='drop2')
model.add_node(Dense(1024),
name='dense1', input='flat1')
model.add_node(Activation('relu'),
name='relu5', input='dense1')
model.add_node(Dropout(0.5),
name='drop3', input='relu5')
#model.add_node(Dense(nb_classes_coarse + nb_classes_fine),
# name='dense2', input='drop3')
model.add_node(Dense(nb_classes_coarse),
name='dense_c', input='drop3')
model.add_node(Activation('softmax'),
name='soft_c', input='dense_c')
model.add_node(Dense(nb_classes_fine),
name='dense_f', input='drop3')
model.add_node(Activation('softmax'),
name='soft_f', input='dense_f')
elif model_style == 'custom1':
model.add_node(Convolution2D(48, 5, 5, border_mode='same',
input_shape=(img_channels, img_rows, img_cols)),
name='conv1', input='input')
model.add_node(Activation('relu'),
name='relu1', input='conv1')
model.add_node(Convolution2D(48, 5, 5),
name='conv2', input='relu1')
model.add_node(Activation('relu'),
name='relu2', input='conv2')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool1', input='relu2')
model.add_node(Dropout(0.10),
name='drop1', input='pool1')
model.add_node(Convolution2D(96, 3, 3, border_mode='same'),
name='conv3', input='drop1')
model.add_node(Activation('relu'),
name='relu3', input='conv3')
model.add_node(Convolution2D(96, 3, 3),
name='conv4', input='relu3')
model.add_node(Activation('relu'),
name='relu4', input='conv4')
model.add_node(MaxPooling2D(pool_size=(3, 3)),
name='pool2', input='relu4')
model.add_node(Dropout(0.10),
name='drop2', input='pool2')
model.add_node(Flatten(),
name='flat1', input='drop2')
model.add_node(Dense(1024),
name='dense1', input='flat1')
model.add_node(Activation('relu'),
name='relu5', input='dense1')
model.add_node(Dropout(0.10),
name='drop3', input='relu5')
#model.add_node(Dense(nb_classes_coarse + nb_classes_fine),
# name='dense2', input='drop3')
model.add_node(Dense(nb_classes_coarse),
name='dense_c', input='drop3')
model.add_node(Activation('softmax'),
name='soft_c', input='dense_c')
model.add_node(Dense(nb_classes_fine),
name='dense_f', input='drop3')
model.add_node(Activation('softmax'),
name='soft_f', input='dense_f')
elif model_style == 'split': # have some convolutions for each of coarse and fine only
model.add_node(Convolution2D(32, 3, 3, border_mode='same',
input_shape=(img_channels, img_rows, img_cols)),
name='conv1', input='input')
model.add_node(Activation('relu'),
name='relu1', input='conv1')
model.add_node(Convolution2D(32, 3, 3),
name='conv2', input='relu1')
model.add_node(Activation('relu'),
name='relu2', input='conv2')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool1', input='relu2')
model.add_node(Dropout(0.25),
name='drop1', input='pool1')
model.add_node(Convolution2D(64, 3, 3, border_mode='same'),
name='conv3_c', input='drop1')
model.add_node(Activation('relu'),
name='relu3_c', input='conv3_c')
model.add_node(Convolution2D(64, 3, 3),
name='conv4_c', input='relu3_c')
model.add_node(Activation('relu'),
name='relu4_c', input='conv4_c')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool2_c', input='relu4_c')
model.add_node(Dropout(0.25),
name='drop2_c', input='pool2_c')
model.add_node(Flatten(),
name='flat1_c', input='drop2_c')
model.add_node(Dense(512),
name='dense1_c', input='flat1_c')
model.add_node(Activation('relu'),
name='relu5_c', input='dense1_c')
model.add_node(Dropout(0.5),
name='drop3_c', input='relu5_c')
#model.add_node(Dense(nb_classes_coarse + nb_classes_fine),
# name='dense2', input='drop3')
model.add_node(Dense(nb_classes_coarse),
name='dense_c', input='drop3_c')
model.add_node(Activation('softmax'),
name='soft_c', input='dense_c')
model.add_node(Convolution2D(64, 3, 3, border_mode='same'),
name='conv3_f', input='drop1')
model.add_node(Activation('relu'),
name='relu3_f', input='conv3_f')
model.add_node(Convolution2D(64, 3, 3),
name='conv4_f', input='relu3_f')
model.add_node(Activation('relu'),
name='relu4_f', input='conv4_f')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool2_f', input='relu4_f')
model.add_node(Dropout(0.25),
name='drop2_f', input='pool2_f')
model.add_node(Flatten(),
name='flat1_f', input='drop2_f')
model.add_node(Dense(512),
name='dense1_f', input='flat1_f')
model.add_node(Activation('relu'),
name='relu5_f', input='dense1_f')
model.add_node(Dropout(0.5),
name='drop3_f', input='relu5_f')
model.add_node(Dense(nb_classes_fine),
name='dense_f', input='drop3_f')
model.add_node(Activation('softmax'),
name='soft_f', input='dense_f')
elif model_style == 'nodrop_split': # have some convolutions for each of coarse and fine only
model.add_node(Convolution2D(32, 3, 3, border_mode='same',
input_shape=(img_channels, img_rows, img_cols)),
name='conv1', input='input')
model.add_node(Activation('relu'),
name='relu1', input='conv1')
model.add_node(Convolution2D(32, 3, 3),
name='conv2', input='relu1')
model.add_node(Activation('relu'),
name='relu2', input='conv2')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool1', input='relu2')
model.add_node(Convolution2D(64, 3, 3, border_mode='same'),
name='conv3_c', input='pool1')
model.add_node(Activation('relu'),
name='relu3_c', input='conv3_c')
model.add_node(Convolution2D(64, 3, 3),
name='conv4_c', input='relu3_c')
model.add_node(Activation('relu'),
name='relu4_c', input='conv4_c')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool2_c', input='relu4_c')
model.add_node(Flatten(),
name='flat1_c', input='pool2_c')
model.add_node(Dense(512),
name='dense1_c', input='flat1_c')
model.add_node(Activation('relu'),
name='relu5_c', input='dense1_c')
#model.add_node(Dense(nb_classes_coarse + nb_classes_fine),
# name='dense2', input='drop3')
model.add_node(Dense(nb_classes_coarse),
name='dense_c', input='relu5_c')
model.add_node(Activation('softmax'),
name='soft_c', input='dense_c')
model.add_node(Convolution2D(64, 3, 3, border_mode='same'),
name='conv3_f', input='pool1')
model.add_node(Activation('relu'),
name='relu3_f', input='conv3_f')
model.add_node(Convolution2D(64, 3, 3),
name='conv4_f', input='relu3_f')
model.add_node(Activation('relu'),
name='relu4_f', input='conv4_f')
model.add_node(MaxPooling2D(pool_size=(2, 2)),
name='pool2_f', input='relu4_f')
model.add_node(Flatten(),
name='flat1_f', input='pool2_f')
model.add_node(Dense(512),
name='dense1_f', input='flat1_f')
model.add_node(Activation('relu'),
name='relu5_f', input='dense1_f')
model.add_node(Dense(nb_classes_fine),
name='dense_f', input='relu5_f')
model.add_node(Activation('softmax'),
name='soft_f', input='dense_f')
model.add_output(name='output', inputs=['soft_c', 'soft_f'], merge_mode='concat')
if optimizer == 'sgd':
# let's train the model using SGD + momentum (how original).
sgd = SGD(lr=learning_rate, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss={'output':objective}, optimizer=sgd)
elif optimizer == 'rmsprop':
model.compile(loss={'output':objective}, optimizer='rmsprop')
else:
model.compile(loss={'output':objective}, optimizer=optimizer)
if pretrain:
model.load_weights('net_output/%s_weights.h5' % pretrain_name)
if training:
if not data_augmentation:
print('Not using data augmentation.')
history = model.fit({'input':X_train, 'output':Y_train}, batch_size=batch_size,
nb_epoch=nb_epoch, #show_accuracy=True,
validation_data={'input':X_test, 'output':Y_test}, shuffle=True)
else:
print('Using real-time data augmentation.')
# this will do preprocessing and realtime data augmentation
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=0, # randomly rotate images in the range (degrees, 0 to 180)
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip=True, # randomly flip images
vertical_flip=False) # randomly flip images
# compute quantities required for featurewise normalization
# (std, mean, and principal components if ZCA whitening is applied)
datagen.fit(X_train)
# fit the model on the batches generated by datagen.flow()
history = model.fit_generator(datagen.flow(X_train, Y_train, batch_size=batch_size),
samples_per_epoch=X_train.shape[0],
nb_epoch=nb_epoch, show_accuracy=True,
validation_data=(X_test, Y_test),
nb_worker=1)
model.save_weights('net_output/hierarchy_%s_weights.h5' % model_name)
json_string = model.to_json()
open('net_output/hierarchy_%s_architecture.json' % model_name, 'w').write(json_string)
pickle.dump(history.history, open('net_output/hierarchy_%s_history.p' % model_name,'w'))
print("saving to: hierarchy_%s" % model_name)
"""
model.save_weights('net_output/keras_cifar100_%s_weights.h5' % model_name)
json_string = model.to_json()
open('net_output/keras_cifar100_%s_architecture.json' % model_name, 'w').write(json_string)
pickle.dump(history.history, open('net_output/keras_cifar100_%s_history.p' % model_name,'w'))
print("saving to: keras_cifar100_%s" % model_name)
"""
else:
#model.load_weights('net_output/keras_cifar100_%s_weights.h5' % model_name)
model.load_weights('net_output/hierarchy_%s_weights.h5' % model_name)
Y_predict_test = model.predict({'input':X_test}, batch_size=batch_size, verbose=1)['output']
Y_predict_train = model.predict({'input':X_train}, batch_size=batch_size, verbose=1)['output']
# Convert floating point vector to a clean binary vector with only two 1's
Y_predict_test_clean = clean_hierarchy_vec(Y_predict_test)
Y_predict_train_clean = clean_hierarchy_vec(Y_predict_train)
test_accuracy, test_acc_coarse, test_acc_fine = accuracy_hierarchy(Y_predict_test_clean, Y_test)
print("hierarchy test accuracy: %f" % test_accuracy)
print("hierarchy test coarse accuracy: %f" % test_acc_coarse)
print("hierarchy test fine accuracy: %f" % test_acc_fine)
train_accuracy, train_acc_coarse, train_acc_fine = accuracy_hierarchy(Y_predict_train_clean, Y_train)
print("hierarchy train accuracy: %f" % train_accuracy)
print("hierarchy train coarse accuracy: %f" % train_acc_coarse)
print("hierarchy train fine accuracy: %f" % train_acc_fine)