Created
December 11, 2019 07:42
-
-
Save JyotinderSingh/05e65a6623e8b64cf884b02ddd09f3bc to your computer and use it in GitHub Desktop.
Cats and Dogs Classifier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from tensorflow.keras.preprocessing.image import ImageDataGenerator | |
from tensorflow.keras.optimizers import RMSprop | |
import matplotlib.pyplot as plt | |
import matplotlib.image as mpimg | |
import os | |
import tensorflow as tf | |
import zipfile | |
base_dir = '/home/jyotinder/Programming/DeepLearning/dataset/dogs-vs-cats' | |
train_dir = os.path.join(base_dir, 'train') | |
validation_dir = os.path.join(base_dir, 'validation') | |
train_cats_dir = os.path.join(train_dir, 'cats') | |
train_dogs_dir = os.path.join(train_dir, 'dogs') | |
validation_cats_dir = os.path.join(validation_dir, 'cats') | |
validation_dogs_dir = os.path.join(validation_dir, 'dogs') | |
train_cat_fnames = os.listdir(train_cats_dir) | |
train_dog_fnames = os.listdir(train_dogs_dir) | |
print(train_cat_fnames[:10]) | |
print(train_dog_fnames[:10]) | |
# ----------------------------------------------------------------------------- | |
print('total training cat images :', len(os.listdir(train_cats_dir))) | |
print('total training dog images :', len(os.listdir(train_dogs_dir))) | |
print('total validation cat images :', len(os.listdir(validation_cats_dir))) | |
print('total validation dog images :', len(os.listdir(validation_dogs_dir))) | |
# ----------------------------------------------------------------------------- | |
# Parameters for our graph; we'll output images in a 4x4 configuration | |
# nrows = 4 | |
# ncols = 4 | |
# pic_index = 0 # Index for iterating over images | |
# ----------------------------------------------------------------------------- | |
# fig = plt.gcf() | |
# fig.set_size_inches(ncols*4, nrows*4) | |
# pic_index += 8 | |
# next_cat_pix = [os.path.join(train_cats_dir, fname) | |
# for fname in train_cat_fnames[pic_index-8:pic_index] | |
# ] | |
# next_dog_pix = [os.path.join(train_dogs_dir, fname) | |
# for fname in train_dog_fnames[pic_index-8:pic_index] | |
# ] | |
# for i, img_path in enumerate(next_cat_pix+next_dog_pix): | |
# # Set up subplot; subplot indices start at 1 | |
# sp = plt.subplot(nrows, ncols, i + 1) | |
# sp.axis('Off') # Don't show axes (or gridlines) | |
# img = mpimg.imread(img_path) | |
# plt.imshow(img) | |
# plt.show() | |
# ----------------------------------------------------------------------------- | |
checkpoint_path = "/home/jyotinder/Programming/DeepLearning/checkpoints_dogs_cats" | |
checkpoint_dir = os.path.dirname(checkpoint_path) | |
# Create a callback that saves the model's weights | |
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path, | |
save_weights_only=True, | |
verbose=1) | |
class myCallback(tf.keras.callbacks.Callback): | |
def on_epoch_end(self, epoch, logs={}): | |
if logs.get('accuracy') >= 0.95: | |
print("\nReached 95% accuracy so cancelling training!") | |
self.model.stop_training = True | |
callbacks = myCallback() | |
model = tf.keras.models.Sequential([ | |
# Note the input shape is the desired size of the image 150x150 with 3 bytes color | |
tf.keras.layers.Conv2D(16, (3, 3), activation='relu', | |
input_shape=(100, 100, 3)), | |
tf.keras.layers.MaxPooling2D(2, 2), | |
tf.keras.layers.Conv2D(32, (3, 3), activation='relu'), | |
tf.keras.layers.MaxPooling2D(2, 2), | |
tf.keras.layers.Conv2D(32, (3, 3), activation='relu'), | |
tf.keras.layers.MaxPooling2D(2, 2), | |
# Flatten the results to feed into a DNN | |
tf.keras.layers.Flatten(), | |
# 512 neuron hidden layer | |
tf.keras.layers.Dense(512, activation='relu'), | |
# Only 1 output neuron. It will contain a value from 0-1 where 0 for 1 class ('cats') and 1 for the other ('dogs') | |
tf.keras.layers.Dense(1, activation='sigmoid') | |
]) | |
# ----------------------------------------------------------------------------- | |
model.summary() | |
# ----------------------------------------------------------------------------- | |
model.compile(optimizer='adam', | |
loss='binary_crossentropy', | |
metrics=['accuracy']) | |
# ----------------------------------------------------------------------------- | |
# All images will be rescaled by 1./255. | |
train_datagen = ImageDataGenerator(rescale=1.0/255.) | |
test_datagen = ImageDataGenerator(rescale=1.0/255.) | |
# -------------------- | |
# Flow training images in batches of 20 using train_datagen generator | |
# -------------------- | |
train_generator = train_datagen.flow_from_directory(train_dir, | |
batch_size=600, | |
class_mode='binary', | |
target_size=(100, 100)) | |
# -------------------- | |
# Flow validation images in batches of 20 using test_datagen generator | |
# -------------------- | |
validation_generator = test_datagen.flow_from_directory(validation_dir, | |
batch_size=500, | |
class_mode='binary', | |
target_size=(100, 100)) | |
# ----------------------------------------------------------------------------- | |
history = model.fit_generator(train_generator, | |
validation_data=validation_generator, | |
steps_per_epoch=40, | |
epochs=30, | |
validation_steps=4, | |
verbose=1, | |
callbacks=[cp_callback, callbacks]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment