Skip to content

Instantly share code, notes, and snippets.

@prateekchandrayan
Last active November 25, 2017 08:56
Show Gist options
  • Save prateekchandrayan/058b8673c9c3cda07c82e10c7685f669 to your computer and use it in GitHub Desktop.
Save prateekchandrayan/058b8673c9c3cda07c82e10c7685f669 to your computer and use it in GitHub Desktop.
InceptionV3 model: finetune the last layer for Dogs vs Cats in Keras. Simple code
from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing import image
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras import backend as K
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Input
import cv2 # working with, mainly resizing, images
import numpy as np # dealing with arrays
import os # dealing with directories
from random import shuffle # mixing up or currently ordered data that might lead our network astray in training.
from tqdm import tqdm # a nice pretty percentage bar for tasks. Thanks to viewer Daniel BA1/4hler for this suggestion
import tensorflow as tf #Import Tensorflow
import glob #This will extract all files from the folder
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
from keras.engine.topology import get_source_inputs
from keras.utils.layer_utils import convert_all_kernels_in_model
from keras.utils.data_utils import get_file
from keras import backend as K
from keras.applications.imagenet_utils import decode_predictions
from keras.applications.imagenet_utils import _obtain_input_shape
from keras.preprocessing import image
from keras.applications.imagenet_utils import preprocess_input
img_width, img_height = 299, 299
input_shape = (img_width, img_height)
train_data_dir = 'D:/Kaggle_data/dogs_vs_cats/train' #contains two classes cats and dogs
validation_data_dir = 'D:/Kaggle_data/dogs_vs_cats/validation' #contains two classes cats and dogs
test_data_dir = 'D:/Kaggle_data/dogs_vs_cats/test1'
nb_train_samples = 12300
nb_validation_samples = 200
nb_epochs =1
batch_size = 10
fc_size = 1024
num_classes = len(glob.glob(train_data_dir + "/*"))
print('Number of classes found:', num_classes)
base_model = InceptionV3(weights='imagenet', include_top=False)
x = base_model.output
x = GlobalAveragePooling2D()(x)
# Add a fully-connected layer
x = Dense(1024, activation='relu')(x)
# and a sigmoid layer
predictions = Dense(1, activation='sigmoid')(x)
# this is the model we will train
model = Model(input=base_model.input, output=predictions)
model.summary()
# first: train only the top layers (which were randomly initialized)
# i.e. freeze all convolutional InceptionV3 layers
for layer in base_model.layers:
layer.trainable = False
model.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy'])
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
validation_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=input_shape,
batch_size=batch_size,
class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(
validation_data_dir,
target_size=input_shape,
batch_size=batch_size,
class_mode='binary')
model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=nb_epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples // batch_size)
model.save('inception_Dogs_Vs_Cats.h5')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment