2015-12-09 02:49:14 +00:00
|
|
|
'''Transfer learning toy example:
|
|
|
|
|
|
|
|
1- Train a simple convnet on the MNIST dataset the first 5 digits [0..4].
|
|
|
|
2- Freeze convolutional layers and fine-tune dense layers
|
|
|
|
for the classification of digits [5..9].
|
|
|
|
|
2016-01-29 21:31:53 +00:00
|
|
|
Run on GPU: THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python mnist_transfer_cnn.py
|
2015-12-09 02:49:14 +00:00
|
|
|
|
|
|
|
Get to 99.8% test accuracy after 5 epochs
|
|
|
|
for the first five digits classifier
|
|
|
|
and 99.2% for the last five digits after transfer + fine-tuning.
|
|
|
|
'''
|
|
|
|
|
2015-10-23 11:53:26 +00:00
|
|
|
from __future__ import print_function
|
|
|
|
import numpy as np
|
|
|
|
import datetime
|
|
|
|
|
|
|
|
np.random.seed(1337) # for reproducibility
|
|
|
|
|
|
|
|
from keras.datasets import mnist
|
|
|
|
from keras.models import Sequential
|
2016-05-12 01:45:37 +00:00
|
|
|
from keras.layers import Dense, Dropout, Activation, Flatten
|
|
|
|
from keras.layers import Convolution2D, MaxPooling2D
|
2015-10-23 11:53:26 +00:00
|
|
|
from keras.utils import np_utils
|
2016-09-06 22:53:56 +00:00
|
|
|
from keras import backend as K
|
2015-10-23 11:53:26 +00:00
|
|
|
|
|
|
|
now = datetime.datetime.now
|
|
|
|
|
|
|
|
batch_size = 128
|
|
|
|
nb_classes = 5
|
|
|
|
nb_epoch = 5
|
|
|
|
|
|
|
|
# input image dimensions
|
|
|
|
img_rows, img_cols = 28, 28
|
|
|
|
# number of convolutional filters to use
|
|
|
|
nb_filters = 32
|
|
|
|
# size of pooling area for max pooling
|
2016-09-06 22:53:56 +00:00
|
|
|
pool_size = 2
|
2015-10-23 11:53:26 +00:00
|
|
|
# convolution kernel size
|
2016-09-06 22:53:56 +00:00
|
|
|
kernel_size = 3
|
|
|
|
|
2017-01-13 23:39:04 +00:00
|
|
|
if K.image_data_format() == 'channels_first':
|
2016-09-06 22:53:56 +00:00
|
|
|
input_shape = (1, img_rows, img_cols)
|
|
|
|
else:
|
|
|
|
input_shape = (img_rows, img_cols, 1)
|
2015-10-23 11:53:26 +00:00
|
|
|
|
|
|
|
|
|
|
|
def train_model(model, train, test, nb_classes):
|
2016-09-06 22:53:56 +00:00
|
|
|
X_train = train[0].reshape((train[0].shape[0],) + input_shape)
|
|
|
|
X_test = test[0].reshape((test[0].shape[0],) + input_shape)
|
2015-12-09 02:49:14 +00:00
|
|
|
X_train = X_train.astype('float32')
|
|
|
|
X_test = X_test.astype('float32')
|
2015-10-23 11:53:26 +00:00
|
|
|
X_train /= 255
|
|
|
|
X_test /= 255
|
|
|
|
print('X_train shape:', X_train.shape)
|
|
|
|
print(X_train.shape[0], 'train samples')
|
|
|
|
print(X_test.shape[0], 'test samples')
|
|
|
|
|
|
|
|
# convert class vectors to binary class matrices
|
|
|
|
Y_train = np_utils.to_categorical(train[1], nb_classes)
|
|
|
|
Y_test = np_utils.to_categorical(test[1], nb_classes)
|
|
|
|
|
2016-03-19 16:07:15 +00:00
|
|
|
model.compile(loss='categorical_crossentropy',
|
|
|
|
optimizer='adadelta',
|
|
|
|
metrics=['accuracy'])
|
2015-10-23 11:53:26 +00:00
|
|
|
|
|
|
|
t = now()
|
2015-11-20 04:13:49 +00:00
|
|
|
model.fit(X_train, Y_train,
|
|
|
|
batch_size=batch_size, nb_epoch=nb_epoch,
|
2016-03-19 16:07:15 +00:00
|
|
|
verbose=1,
|
2015-10-23 11:53:26 +00:00
|
|
|
validation_data=(X_test, Y_test))
|
|
|
|
print('Training time: %s' % (now() - t))
|
2016-03-19 16:07:15 +00:00
|
|
|
score = model.evaluate(X_test, Y_test, verbose=0)
|
2015-10-23 11:53:26 +00:00
|
|
|
print('Test score:', score[0])
|
|
|
|
print('Test accuracy:', score[1])
|
|
|
|
|
|
|
|
|
|
|
|
# the data, shuffled and split between train and test sets
|
|
|
|
(X_train, y_train), (X_test, y_test) = mnist.load_data()
|
|
|
|
|
|
|
|
# create two datasets one with digits below 5 and one with 5 and above
|
|
|
|
X_train_lt5 = X_train[y_train < 5]
|
|
|
|
y_train_lt5 = y_train[y_train < 5]
|
|
|
|
X_test_lt5 = X_test[y_test < 5]
|
|
|
|
y_test_lt5 = y_test[y_test < 5]
|
|
|
|
|
|
|
|
X_train_gte5 = X_train[y_train >= 5]
|
|
|
|
y_train_gte5 = y_train[y_train >= 5] - 5 # make classes start at 0 for
|
|
|
|
X_test_gte5 = X_test[y_test >= 5] # np_utils.to_categorical
|
|
|
|
y_test_gte5 = y_test[y_test >= 5] - 5
|
|
|
|
|
|
|
|
# define two groups of layers: feature (convolutions) and classification (dense)
|
|
|
|
feature_layers = [
|
2016-09-06 22:53:56 +00:00
|
|
|
Convolution2D(nb_filters, kernel_size, kernel_size,
|
2015-11-20 04:13:49 +00:00
|
|
|
border_mode='valid',
|
2016-09-06 22:53:56 +00:00
|
|
|
input_shape=input_shape),
|
2015-10-23 11:53:26 +00:00
|
|
|
Activation('relu'),
|
2016-09-06 22:53:56 +00:00
|
|
|
Convolution2D(nb_filters, kernel_size, kernel_size),
|
2015-10-23 11:53:26 +00:00
|
|
|
Activation('relu'),
|
2016-09-06 22:53:56 +00:00
|
|
|
MaxPooling2D(pool_size=(pool_size, pool_size)),
|
2015-10-23 11:53:26 +00:00
|
|
|
Dropout(0.25),
|
|
|
|
Flatten(),
|
|
|
|
]
|
|
|
|
classification_layers = [
|
|
|
|
Dense(128),
|
|
|
|
Activation('relu'),
|
|
|
|
Dropout(0.5),
|
|
|
|
Dense(nb_classes),
|
|
|
|
Activation('softmax')
|
|
|
|
]
|
|
|
|
|
|
|
|
# create complete model
|
2016-09-06 22:53:56 +00:00
|
|
|
model = Sequential(feature_layers + classification_layers)
|
2015-10-23 11:53:26 +00:00
|
|
|
|
|
|
|
# train model for 5-digit classification [0..4]
|
2015-11-20 04:13:49 +00:00
|
|
|
train_model(model,
|
|
|
|
(X_train_lt5, y_train_lt5),
|
|
|
|
(X_test_lt5, y_test_lt5), nb_classes)
|
2015-10-23 11:53:26 +00:00
|
|
|
|
|
|
|
# freeze feature layers and rebuild model
|
|
|
|
for l in feature_layers:
|
|
|
|
l.trainable = False
|
|
|
|
|
|
|
|
# transfer: train dense layers for new classification task [5..9]
|
2015-11-20 04:13:49 +00:00
|
|
|
train_model(model,
|
|
|
|
(X_train_gte5, y_train_gte5),
|
|
|
|
(X_test_gte5, y_test_gte5), nb_classes)
|