The motion detector saves a lot of pictures, and most of them are nothing. I want to sort them into
“empty driveway”, “car” and “person”. I have a few hundred labelled images, not millions, so I am trying
transfer learning. In the middle of this, Keras 2.0 came out on 14 March 2017
(Keras blog), and my code from the week before printed warnings
everywhere. The announcement also said the Keras API will be part of TensorFlow from version 1.2, as
tf.keras. Standalone Keras stays and still supports Theano and TensorFlow.
Keras 2 renames
Old code still runs for now, with warnings. The renames I hit:
| Keras 1 | Keras 2 |
|---|---|
nb_epoch |
epochs |
samples_per_epoch (in samples) |
steps_per_epoch (in batches) |
nb_val_samples |
validation_steps (in batches) |
Dense(output_dim=...) |
Dense(units=...) |
init= |
kernel_initializer= |
W_regularizer= |
kernel_regularizer= |
Convolution2D |
Conv2D |
dim_ordering='tf' |
data_format='channels_last' |
Model(input=, output=) |
Model(inputs=, outputs=) |
Be careful with the generator arguments. steps_per_epoch counts batches, not samples. I renamed the
argument and kept the sample count, and each epoch became 32 times longer with batch size 32. It took me a
while to notice why training was so slow.
The full list is in the Keras 2.0 release notes.
Why transfer learning
VGG16 was trained on ImageNet, over a million images in 1000 classes. Its early layers detect edges and textures, and later layers detect parts of objects. These features are useful for almost any photo. So you keep the pretrained layers, drop the last classification layer, and train only a small new head for your own classes. With a few hundred images per class this works. Training a network from zero on so little data mostly learns the noise.
Data
data/
train/
car/ *.jpg
empty/ *.jpg
person/ *.jpg
val/
car/
empty/
person/
About 20 percent of the images go in val, and they come from different days than the training images. My
first split was random, and the validation accuracy looked great. But neighbouring frames from the same
minute are almost identical, so the model had seen the validation images already, more or less.
The code
from keras.applications.vgg16 import VGG16, preprocess_input
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Dense, Dropout, GlobalAveragePooling2D
from keras.models import Model
SIZE = (224, 224)
BATCH = 32
base = VGG16(weights="imagenet", include_top=False, input_shape=SIZE + (3,))
for layer in base.layers:
layer.trainable = False
x = GlobalAveragePooling2D()(base.output)
x = Dense(256, activation="relu")(x)
x = Dropout(0.5)(x)
out = Dense(3, activation="softmax")(x)
model = Model(inputs=base.input, outputs=out)
model.compile(optimizer="adam",
loss="categorical_crossentropy",
metrics=["accuracy"])
train_gen = ImageDataGenerator(
preprocessing_function=preprocess_input,
horizontal_flip=True,
rotation_range=10,
zoom_range=0.1,
).flow_from_directory("data/train", target_size=SIZE, batch_size=BATCH)
val_gen = ImageDataGenerator(
preprocessing_function=preprocess_input,
).flow_from_directory("data/val", target_size=SIZE, batch_size=BATCH,
shuffle=False)
model.fit_generator(
train_gen,
steps_per_epoch=train_gen.samples // BATCH,
epochs=10,
validation_data=val_gen,
validation_steps=val_gen.samples // BATCH,
)
model.save("classifier.h5")
print(train_gen.class_indices)
preprocess_input must match the base network. VGG16 expects its own mean subtraction, and
rescale=1./255 instead gives worse results. Use the same function and the same image size at prediction
time.
Augmentation (flip, small rotation, zoom) is only for the training data.
Save class_indices. It maps class names to output positions, and you need it to read the predictions.
Fine-tuning
When the head is trained, you can unfreeze the last convolution block and train again with a very small learning rate:
from keras.optimizers import SGD
for layer in base.layers[-4:]:
layer.trainable = True
model.compile(optimizer=SGD(lr=1e-4, momentum=0.9),
loss="categorical_crossentropy", metrics=["accuracy"])
Recompile after changing trainable, or the change has no effect. Only fine-tune after the head is trained.
Otherwise the large gradients from the random new head damage the pretrained weights. I have not seen a clear
gain from fine-tuning on my data yet, but I have also not tried hard.
Hardware
Training VGG16 on a CPU is slow, even for a few hundred images. Without a GPU, a faster way is to run the frozen base once over all images, save the features to disk, and train only the small head on them. You lose augmentation, but each epoch takes seconds.
VGG16 is large (over 500 MB of weights with the top layers, much less without them). It is too heavy to run often on a Raspberry Pi.
Before I trust the model
Most of my images are “empty”. A model that always says “empty” already gets high accuracy, so I look at a
confusion matrix, not only accuracy. And many examples online still use nb_epoch and sample counts, so I
convert those carefully when I copy from them.