# -*- coding: utf-8 -*-
import datetime
from keras.models import Model
from keras.layers import *
from keras.preprocessing.image import ImageDataGenerator
def VGG16(input_shape=(224, 224, 3), classes=1000):
img_input = Input(shape=input_shape)
# Block 1
x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)
x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)
# Block 2
x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)
x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)
# Block 3
x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)
x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)
x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)
# Block 4
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)
# Block 5
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)
x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)
x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)
x = Flatten(name='flatten')(x)
x = Dense(4096, activation='relu', name='fc1')(x)
x = Dense(4096, activation='relu', name='fc2')(x)
if classes == 2:
x = Dense(1, activation='sigmoid', name='predictions')(x)
else:
x = Dense(classes, activation='softmax', name='predictions')(x)
model = Model(img_input, x, name='vgg16')
return model
def main():
width = 224
height = 224
batch_size = 2
generator = ImageDataGenerator(horizontal_flip=True,
vertical_flip=True,
validation_split=0.2)
train_generator = generator.flow_from_directory(directory="datasets/train",
target_size=(width, height),
batch_size=batch_size,
class_mode="binary",
subset="training")
val_generator = generator.flow_from_directory(directory="datasets/train",
target_size=(width, height),
batch_size=batch_size,
class_mode="binary",
subset="validation")
model = VGG16(classes=2)
model.summary()
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit_generator(train_generator, validation_data=val_generator, epochs=10, verbose=1)
if __name__ == '__main__':
tic = datetime.datetime.now()
main()
toc = datetime.datetime.now()
print("\nThis model took ", (toc - tic))