NOTE: This Use Case is not purposed for resource constrained devices.
In this notebook, we will classify the breed of a dog (among 5 selected breeds,) based on the image of a dog.¶
We will import all the required libraries¶
In [1]:
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import wget
import os
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import classification_report, log_loss, accuracy_score
from sklearn.model_selection import train_test_split
In [2]:
!pip install wget
Unzip the dataset so that we can use it in our notebook¶
In [3]:
!wget -N "https://cainvas-static.s3.amazonaws.com/media/user_data/cainvas-admin/dog_photos.zip"
!unzip -qo dog_photos.zip
In [4]:
directory = "dog_photos/train/"
Our dataset consists of the given 5 different breeds. Each folder is dedicated to a single breed and contains upto 120 different images of that breed.¶
In [5]:
Name=[]
for file in os.listdir(directory):
Name+=[file]
print(Name)
print(len(Name))
Map the classifications i.e. classes to an integer and display the list of all unique 5 breeds.¶
In [6]:
breed_map = dict(zip(Name, [t for t in range(len(Name))]))
print(breed_map)
r_breed_map=dict(zip([t for t in range(len(Name))],Name))
Displaying some images from our dataset.¶
In [7]:
Breed = 'dog_photos/train/pug'
import os
sub_class = os.listdir(Breed)
fig = plt.figure(figsize=(10,5))
for e in range(len(sub_class[:10])):
plt.subplot(2,5,e+1)
img = plt.imread(os.path.join(Breed,sub_class[e]))
plt.imshow(img, cmap=plt.get_cmap('gray'))
plt.axis('off')
In [8]:
def mapper(value):
return r_breed_map[value]
Perform data augmentation by using ImageDataGenerator so that we can acquire more relevant data from the existing images by making minor alterations to the dataset.¶
In [9]:
img_datagen = ImageDataGenerator(rescale=1./255,
vertical_flip=True,
horizontal_flip=True,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
zoom_range=0.1,
validation_split=0.2)
In [10]:
test_datagen = ImageDataGenerator(rescale=1./255)
Divide the training dataset into train set and validation set.¶
In [11]:
train_generator = img_datagen.flow_from_directory(directory,
shuffle=True,
batch_size=32,
subset='training',
target_size=(100, 100))
In [12]:
valid_generator = img_datagen.flow_from_directory(directory,
shuffle=True,
batch_size=16,
subset='validation',
target_size=(100, 100))
In [13]:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Conv2D,MaxPooling2D,Dropout,Flatten,Activation,BatchNormalization
from tensorflow.keras.models import model_from_json
from tensorflow.keras.models import load_model
from tensorflow.keras import regularizers
Train a sequential model.¶
In [14]:
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(3,3),input_shape=(100,100,3), activation='relu', padding = 'same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding = 'same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding = 'same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding = 'same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding = 'same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.3))
model.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding = 'same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(256))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(len(breed_map)))
model.add(Activation('softmax'))
model.summary()
In [15]:
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
In [16]:
history = model.fit(train_generator, validation_data=valid_generator,
steps_per_epoch=train_generator.n//train_generator.batch_size,
validation_steps=valid_generator.n//valid_generator.batch_size,
epochs=170)
Plot accuracy curves.¶
In [17]:
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.title('Training and validation accuracy')
plt.show()
Making Predictions¶
In [18]:
load_img("dog_photos/test/image4.jpg",target_size=(180,180))
Out[18]:
Randomly select an image from the test set and feed it to our model to make predictions.¶
In [19]:
image=load_img("dog_photos/test/image4.jpg",target_size=(100,100))
image=img_to_array(image)
image=image/255.0
prediction_image=np.array(image)
prediction_image= np.expand_dims(image, axis=0)
In [20]:
prediction=model.predict(prediction_image)
value=np.argmax(prediction)
move_name=mapper(value)
print("Prediction is {}.".format(move_name))
In [21]:
model.save('saved_models/DogBreed.tf')
deepCC¶
In [24]:
!deepCC 'saved_models/DogBreed.tf'