In [1]:
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
In [2]:
from keras.applications.vgg19 import VGG19
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint
In [3]:
vgg19 = VGG19(include_top=False,
weights='imagenet',
input_shape=(224,224,3),
pooling=None)
In [4]:
vgg19.layers
Out[4]:
In [5]:
vgg19.summary()
In [6]:
for layer in vgg19.layers:
layer.trainable = False
In [7]:
# Instantiate the sequential model and add the VGG19 model:
model = Sequential()
model.add(vgg19)
# Add the custom layers atop the VGG19 model:
model.add(Flatten(name='flattened'))
model.add(Dropout(0.5, name='dropout'))
model.add(Dense(2, activation='softmax', name='predictions'))
In [8]:
model.summary()
In [9]:
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
In [10]:
output_dir = 'model_output/transfer_VGG'
In [11]:
modelcheckpoint = ModelCheckpoint(filepath=output_dir+
"/weights.{epoch:02d}.hdf5")
In [12]:
if not os.path.exists(output_dir):
os.makedirs(output_dir)
The dataset is available for download here. You should download the zipfile and extract the contents into a folder called hot-dog-not-hot-dog
in the notebooks
directory.
In [13]:
# Instantiate two image generator classes:
train_datagen = ImageDataGenerator(
rescale=1.0/255,
data_format='channels_last',
rotation_range=30,
horizontal_flip=True,
fill_mode='reflect')
valid_datagen = ImageDataGenerator(
rescale=1.0/255,
data_format='channels_last')
In [14]:
# Define the batch size:
batch_size=32
In [15]:
# Define the train and validation generators:
train_generator = train_datagen.flow_from_directory(
directory='./hot-dog-not-hot-dog/train',
target_size=(224, 224),
classes=['hot_dog','not_hot_dog'],
class_mode='categorical',
batch_size=batch_size,
shuffle=True,
seed=42)
valid_generator = valid_datagen.flow_from_directory(
directory='./hot-dog-not-hot-dog/test',
target_size=(224, 224),
classes=['hot_dog','not_hot_dog'],
class_mode='categorical',
batch_size=batch_size,
shuffle=True,
seed=42)
In [16]:
model.fit_generator(train_generator, steps_per_epoch=15,
epochs=16, validation_data=valid_generator,
validation_steps=15, callbacks=[modelcheckpoint])
Out[16]:
In [17]:
model.load_weights('model_output/transfer_VGG/weights.02.hdf5')
In [ ]: