In [1]:
from theano.sandbox import cuda
cuda.use('gpu1')
In [2]:
%matplotlib inline
from importlib import reload
import utils; reload(utils)
from utils import *
from __future__ import division, print_function
In [3]:
batch_size = 64
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
Out[3]:
In [4]:
# Because MNIST is grey-scale images, it does not have the color column,
# Let's add one empty dim to the X data
X_test = np.expand_dims(X_test, 1)
X_train = np.expand_dims(X_train, 1)
X_train.shape
Out[4]:
In [5]:
y_train[:5]
Out[5]:
In [6]:
y_train = onehot(y_train)
y_test = onehot(y_test)
y_train[:5]
Out[6]:
Now, let's normalize the inputs
In [7]:
mean_px = X_train.mean().astype(np.float32)
std_px = X_train.std().astype(np.float32)
In [8]:
def norm_input(x): return (x-mean_px)/std_px
Why not we just fine-tune the imagenet model?
Because imageNet is 214 x 214 and is full-color. Here we have 28 x 28 and greyscale.
So we need to start from scratch.
In [9]:
def get_lin_model():
model = Sequential([
Lambda(norm_input, input_shape=(1,28,28)),
Flatten(),
Dense(10, activation='softmax')
])
model.compile(Adam(), loss='categorical_crossentropy', metrics=['accuracy'])
return model
lm = get_lin_model()
In [10]:
gen = image.ImageDataGenerator()
batches = gen.flow(X_train, y_train, batch_size=64)
test_batches = gen.flow(X_test, y_test, batch_size=64)
In [17]:
lm.fit_generator(batches, batches.N, nb_epoch=1,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[17]:
It's always recommended to start with epoch 1 and a low learning rate. Defaut is 0.0001
In [18]:
lm.optimizer.lr = 0.1
lm.fit_generator(batches, batches.N, nb_epoch=3,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[18]:
In [11]:
def get_fc_model():
model = Sequential([
Lambda(norm_input, input_shape=(1,28,28)),
Flatten(),
Dense(512, activation='softmax'),
Dense(10, activation='softmax')
])
model.compile(Adam(), loss='categorical_crossentropy', metrics=['accuracy'])
return model
fc = get_fc_model()
As before, let's start with 1 epoch and a default low learning rate.
In [12]:
fc.fit_generator(batches, batches.N, nb_epoch=1,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[12]:
In [14]:
fc.optimizer.lr=0.01
fc.fit_generator(batches, batches.N, nb_epoch=4,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[14]:
In [15]:
def get_model():
model = Sequential([
Lambda(norm_input, input_shape=(1,28, 28)),
Convolution2D(32,3,3, activation='relu'),
Convolution2D(32,3,3, activation='relu'),
MaxPooling2D(),
Convolution2D(64,3,3, activation='relu'),
Convolution2D(64,3,3, activation='relu'),
MaxPooling2D(),
Flatten(),
Dense(512, activation='relu'),
Dense(10, activation='softmax')
])
model.compile(Adam(), loss='categorical_crossentropy', metrics=['accuracy'])
return model
In [16]:
model = get_model()
model.fit_generator(batches, batches.N, nb_epoch=1,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[16]:
In [25]:
model.optimizer.lr=0.1
model.fit_generator(batches, batches.N, nb_epoch=1,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[25]:
In [26]:
model.optimizer.lr=0.01
model.fit_generator(batches, batches.N, nb_epoch=8,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[26]:
In [17]:
model = get_model()
In [19]:
# Now, we don't user the default settings for ImageDataGenerator
gen = image.ImageDataGenerator(rotation_range=8, width_shift_range=0.08, shear_range=0.3,
height_shift_range=0.08, zoom_range=0.08)
batches = gen.flow(X_train, y_train, batch_size=64)
test_batches = gen.flow(X_test, y_test, batch_size=64)
In [20]:
model.fit_generator(batches, batches.N, nb_epoch=1,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[20]:
In [21]:
model.optimizer.lr=0.1
model.fit_generator(batches, batches.N, nb_epoch=4,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[21]:
In [22]:
model.optimizer.lr=0.01
model.fit_generator(batches, batches.N, nb_epoch=8,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[22]:
In [23]:
def get_model_bn():
model = Sequential([
Lambda(norm_input, input_shape=(1,28,28)),
Convolution2D(32,3,3, activation='relu'),
BatchNormalization(axis=1),
Convolution2D(32,3,3, activation='relu'),
MaxPooling2D(),
BatchNormalization(axis=1),
Convolution2D(64,3,3, activation='relu'),
BatchNormalization(axis=1),
Convolution2D(64,3,3, activation='relu'),
MaxPooling2D(),
Flatten(),
BatchNormalization(),
Dense(512, activation='relu'),
BatchNormalization(),
Dense(10, activation='softmax')
])
model.compile(Adam(), loss='categorical_crossentropy', metrics=['accuracy'])
return model
In [25]:
model = get_model_bn()
model.fit_generator(batches, batches.N, nb_epoch=1,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[25]:
In [26]:
model.optimizer.lr=0.1
model.fit_generator(batches, batches.N, nb_epoch=4,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[26]:
In [27]:
model.optimizer.lr=0.001
model.fit_generator(batches, batches.N, nb_epoch=12,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[27]:
In [28]:
def get_model_bn_do():
model = Sequential([
Lambda(norm_input, input_shape=(1,28,28)),
Convolution2D(32,3,3, activation='relu'),
BatchNormalization(axis=1),
Convolution2D(32,3,3, activation='relu'),
MaxPooling2D(),
BatchNormalization(axis=1),
Convolution2D(64,3,3, activation='relu'),
BatchNormalization(axis=1),
Convolution2D(64,3,3, activation='relu'),
MaxPooling2D(),
Flatten(),
BatchNormalization(),
Dense(512, activation='relu'),
BatchNormalization(),
Dropout(0.5),
Dense(10, activation='softmax')
])
model.compile(Adam(), loss='categorical_crossentropy', metrics=['accuracy'])
return model
In [29]:
model = get_model_bn_do()
In [30]:
model.optimizer.lr=0.01
model.fit_generator(batches, batches.N, nb_epoch=12,
validation_data=test_batches, nb_val_samples=test_batches.N)
Out[30]:
Ensembling is a way that can often improve your accuracy. It takes many models and combines them together.
In [33]:
def fit_model():
model = get_model_bn_do()
model.fit_generator(batches, batches.N, nb_epoch=1, verbose=0,
validation_data=test_batches, nb_val_samples=test_batches.N)
model.optimizer.lr=0.1
model.fit_generator(batches, batches.N, nb_epoch=4, verbose=0,
validation_data=test_batches, nb_val_samples=test_batches.N)
model.optimizer.lr=0.01
model.fit_generator(batches, batches.N, nb_epoch=12, verbose=0,
validation_data=test_batches, nb_val_samples=test_batches.N)
# model.optimizer.lr=0.001
# model.fit_generator(batches, batches.N, nb_epoch=18, verbose=0,
# validation_data=test_batches, nb_val_samples=test_batches.N)
return model
In [34]:
# Return a list of models
models = [fit_model() for i in range(6)]
In [35]:
path = 'data/mnist/'
model_path = path + 'models/'
In [37]:
for i, m in enumerate(models):
m.save_weights(model_path+'cnn-mnist23-'+str(i)+'.pkl')
In [38]:
evals = np.array([m.evaluate(X_test, y_test, batch_size=256) for m in models])
In [39]:
evals.mean(axis=0)
Out[39]:
In [41]:
all_preds = np.stack([m.predict(X_test, batch_size=256) for m in models])
all_preds.shape
Out[41]:
In [42]:
avg_preds = all_preds.mean(axis=0)
In [43]:
keras.metrics.categorical_accuracy(y_test, avg_preds).eval()
Out[43]:
In [ ]: