Project: Write an Algorithm for a Dog Identification App


Why We're Here

In this notebook, we will be developing an algorithm that could be used as part of a mobile or web app. At the end of this project, the code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling.

Sample Dog Output

In this real-world setting, we will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists.

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('/data/dog_images/train')
valid_files, valid_targets = load_dataset('/data/dog_images/valid')
test_files, test_targets = load_dataset('/data/dog_images/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("/data/dog_images/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("/data/lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [3]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Writing a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [4]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

Assessing the Human Face Detector

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. We will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

In [5]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
humans_rate = [face_detector(human) for human in human_files_short].count(True)/len(human_files_short)
dogs_rate = [face_detector(dog) for dog in dog_files_short].count(True)/len(dog_files_short)
humans_rate, dogs_rate
        
Out[5]:
(1.0, 0.11)

The rate for detected faces in the human files give us a 100 %, whereas 11 of the 100 dog pictures seem to be having human features as well. But this is an OK rate for this use case.

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). I think this is a reasonable expectation, because most pictures are all about capturing faces (this is what we usually consider as individual feature for people). Though, there are other ways to detect humans in images. For example, you could build a Convolutional Neural Network from scratch, upon labelled pictures with and without humans. A possible architecture could look like the following:

Image

The important part is to reduce the width and the height and add more depth to the model to extract the features that are related to humans - and not only the face. After extracting features, you will get a percentage for the image containing a human or not.

Another way to try to extract features - without having to train a complete new network, is transfer learning:

  • Transfer learning is based on the implication that the way a convolutional neural network behaves layer afer layer, is almost the same - even for datasets containing different sorts of pictures.
  • You basically adopt a trained model's layers until it gets too specific (there are ways to visualize what actually happens inside - but you can try it out)
  • Then you add the layers you want to extract the domain specific pictures with (this case: human/non-human)
  • And then train it on your data

For the purpose of this notebook, I don't want to include this part here.


Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [6]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5
102858752/102853048 [==============================] - 2s 0us/step

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [7]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [8]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [9]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

Assessing the Dog Detector

In [10]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
humans_rate = [dog_detector(human) for human in human_files_short].count(True)/len(human_files_short)
dogs_rate = [dog_detector(dog) for dog in dog_files_short].count(True)/len(dog_files_short)
humans_rate, dogs_rate
Out[10]:
(0.0, 1.0)

As you can see, the dog_detector detects 0% of humans as a dog, whereas 100% of the dogs are actually correctly identified as dogs. This indeed is a perfect prediction of the pre-trained model for our chosen data.


Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, we will create a CNN that classifies dog breeds. We must create your CNN from scratch (so, we can't use transfer learning yet!), and you must attain a test accuracy of at least 1%.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [11]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [01:26<00:00, 77.62it/s] 
100%|██████████| 835/835 [00:09<00:00, 85.80it/s] 
100%|██████████| 836/836 [00:09<00:00, 86.32it/s] 

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

As already outlined before, it is very important to extract small features and train them on the data respectively. Convolutional neural networks are very useful when it comes to feature extraction. In contrast to CNNs, MLPs make use of simple one column vectors, for which we can't identify patterns in diagonal pixels for example.

A very important architectural feature is to make our features deeper, which means that you reduce width and height of the actual input image and gain more insights about the patterns via consolidating specific parts that are presented by the layer parts (depth). In the end, you use a 'Dense layer' to weigh each feature fitted to the desired output (which the back propagation does for us).

Let's go though the layers I chose for the convolutional neural network:

  1. A Convolutional layer

    • using 16 filters that slide through the picture, creating a depth of 16
    • a kernel_size of 3 which look at a range of 3x3 pixels
    • relu activation to keep only positive numbers coming in
    • the input_shape mirrors the data we transformed above
    • padding = same which doesn't play a role in this case because the stride is set to 1 (1 step of the filter)
      • basically it tells us when the filter gets ahead of the border of the image, you fill in zeros for the part that goes beyond the borders
    • Let's quickly revise how a filter works to get a visual understanding of it

      3D Convolution Animation.gif
      By Michael Plotke - Own work, CC BY-SA 3.0, Link

  1. A Max Pooling layer
    • pool_size of 2 which means that another filter slides over the image (after the 1st layer) and takes the highest number out of the 2x2 window it uses
    • this way we lower the width and height which has been our goal
    • it still keeps the depth, the convolutional layer created before

Image Source: https://www.superdatascience.com/convolutional-neural-networks-cnn-step-2-max-pooling/

  1. Another convolutional layer & Max Pooling Layer
    • Conv. layer: The filters and the kernel_size are increased to increase depth and decrease width x height not as much
    • Max Pooling Layer: We again decrease the dimensions of width and height by 2
  1. Global Average Pooling
    • We use the pooling layer to create a flatten data vector which values are the average of each of the layers' remaining numbers
    • That way we can weight each of the features the model has learned to predict the class (dog breed in this case)

Image Source: https://alexisbcook.github.io/2017/global-average-pooling-layers-for-object-localization/

  1. Dense Layer
    • This one takes in the inputs of the weighted features and returns the probabilities of each dog breed by using a softmax activation function
    • We have 133 possible dog breeds so we use this number for the neurons

Image Source: https://www.learnopencv.com/image-classification-using-convolutional-neural-networks-in-keras/

All in all, I was inspired by the example architecture above and just tried some different parameters. What I thought was most important, was the number of features we ask the convolutional neural network to find out. I constructed the architecture to be able to find 64 different features about each dog breed. That's why I think this model works pretty well - at least better than I would do ;)

In case of unlimited computing power and time

If I had unlimited computing power and time, I would try the following:

  • Add another convolutional layer to extract even more abstract features from the pictures
  • The more layers we have, the higher the chance of overfitting; Prevention techniques e.g.:
    • Dropout layers
    • Regularization (L1 / L2)
  • Data Augmentation to have more data to train the network with
In [16]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

model.add(Conv2D(filters=16, kernel_size=3, padding='same', 
    activation='relu', input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=2, padding='valid'))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', 
    activation='relu'))
model.add(MaxPooling2D(pool_size=2, padding='valid'))
model.add(Conv2D(filters=64, kernel_size=2, padding='same', 
    activation='relu'))
model.add(GlobalAveragePooling2D())
model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_4 (Conv2D)            (None, 224, 224, 16)      448       
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 112, 112, 32)      2080      
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 56, 56, 64)        8256      
_________________________________________________________________
global_average_pooling2d_2 ( (None, 64)                0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               8645      
=================================================================
Total params: 19,429
Trainable params: 19,429
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [17]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

Train the Model

In [18]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 50

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.8806 - acc: 0.0089Epoch 00001: val_loss improved from inf to 4.85602, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 23s 3ms/step - loss: 4.8805 - acc: 0.0088 - val_loss: 4.8560 - val_acc: 0.0144
Epoch 2/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.8358 - acc: 0.0159Epoch 00002: val_loss improved from 4.85602 to 4.83055, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.8359 - acc: 0.0159 - val_loss: 4.8306 - val_acc: 0.0120
Epoch 3/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.8022 - acc: 0.0153Epoch 00003: val_loss improved from 4.83055 to 4.81445, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.8021 - acc: 0.0156 - val_loss: 4.8144 - val_acc: 0.0240
Epoch 4/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.7820 - acc: 0.0164Epoch 00004: val_loss improved from 4.81445 to 4.79680, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.7818 - acc: 0.0163 - val_loss: 4.7968 - val_acc: 0.0263
Epoch 5/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.7614 - acc: 0.0215Epoch 00005: val_loss improved from 4.79680 to 4.77011, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.7616 - acc: 0.0214 - val_loss: 4.7701 - val_acc: 0.0240
Epoch 6/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.7328 - acc: 0.0239Epoch 00006: val_loss improved from 4.77011 to 4.75541, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.7340 - acc: 0.0240 - val_loss: 4.7554 - val_acc: 0.0204
Epoch 7/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.7135 - acc: 0.0249Epoch 00007: val_loss improved from 4.75541 to 4.74309, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.7133 - acc: 0.0249 - val_loss: 4.7431 - val_acc: 0.0240
Epoch 8/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.6932 - acc: 0.0291Epoch 00008: val_loss improved from 4.74309 to 4.72495, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.6926 - acc: 0.0292 - val_loss: 4.7250 - val_acc: 0.0311
Epoch 9/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.6741 - acc: 0.0339Epoch 00009: val_loss improved from 4.72495 to 4.71325, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 23s 3ms/step - loss: 4.6734 - acc: 0.0341 - val_loss: 4.7132 - val_acc: 0.0299
Epoch 10/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.6536 - acc: 0.0345Epoch 00010: val_loss improved from 4.71325 to 4.69725, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.6542 - acc: 0.0346 - val_loss: 4.6973 - val_acc: 0.0287
Epoch 11/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.6370 - acc: 0.0339Epoch 00011: val_loss improved from 4.69725 to 4.68886, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.6370 - acc: 0.0338 - val_loss: 4.6889 - val_acc: 0.0299
Epoch 12/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.6184 - acc: 0.0380Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.6181 - acc: 0.0382 - val_loss: 4.6965 - val_acc: 0.0299
Epoch 13/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.5974 - acc: 0.0377Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.5971 - acc: 0.0379 - val_loss: 4.7075 - val_acc: 0.0311
Epoch 14/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.5766 - acc: 0.0387Epoch 00014: val_loss improved from 4.68886 to 4.66780, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 23s 3ms/step - loss: 4.5769 - acc: 0.0386 - val_loss: 4.6678 - val_acc: 0.0395
Epoch 15/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.5614 - acc: 0.0453Epoch 00015: val_loss improved from 4.66780 to 4.64564, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.5613 - acc: 0.0452 - val_loss: 4.6456 - val_acc: 0.0287
Epoch 16/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.5411 - acc: 0.0441Epoch 00016: val_loss improved from 4.64564 to 4.61735, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.5413 - acc: 0.0443 - val_loss: 4.6174 - val_acc: 0.0371
Epoch 17/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.5280 - acc: 0.0429Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.5287 - acc: 0.0431 - val_loss: 4.6448 - val_acc: 0.0299
Epoch 18/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.5077 - acc: 0.0467Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.5081 - acc: 0.0466 - val_loss: 4.6928 - val_acc: 0.0383
Epoch 19/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.5007 - acc: 0.0497Epoch 00019: val_loss improved from 4.61735 to 4.58181, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.5012 - acc: 0.0496 - val_loss: 4.5818 - val_acc: 0.0455
Epoch 20/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.4814 - acc: 0.0486Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.4815 - acc: 0.0487 - val_loss: 4.5963 - val_acc: 0.0347
Epoch 21/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.4666 - acc: 0.0514Epoch 00021: val_loss improved from 4.58181 to 4.56838, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.4665 - acc: 0.0513 - val_loss: 4.5684 - val_acc: 0.0371
Epoch 22/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.4478 - acc: 0.0565Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.4462 - acc: 0.0566 - val_loss: 4.6096 - val_acc: 0.0407
Epoch 23/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.4348 - acc: 0.0550Epoch 00023: val_loss improved from 4.56838 to 4.55175, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 23s 3ms/step - loss: 4.4344 - acc: 0.0549 - val_loss: 4.5518 - val_acc: 0.0371
Epoch 24/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.4115 - acc: 0.0574Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.4122 - acc: 0.0572 - val_loss: 4.5982 - val_acc: 0.0359
Epoch 25/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.4026 - acc: 0.0595Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.4022 - acc: 0.0596 - val_loss: 4.5523 - val_acc: 0.0431
Epoch 26/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.3822 - acc: 0.0611Epoch 00026: val_loss improved from 4.55175 to 4.53050, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.3830 - acc: 0.0611 - val_loss: 4.5305 - val_acc: 0.0419
Epoch 27/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.3684 - acc: 0.0649Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.3690 - acc: 0.0650 - val_loss: 4.5345 - val_acc: 0.0503
Epoch 28/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.3553 - acc: 0.0643Epoch 00028: val_loss improved from 4.53050 to 4.50540, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.3558 - acc: 0.0644 - val_loss: 4.5054 - val_acc: 0.0443
Epoch 29/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.3343 - acc: 0.0656Epoch 00029: val_loss improved from 4.50540 to 4.48441, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.3342 - acc: 0.0656 - val_loss: 4.4844 - val_acc: 0.0479
Epoch 30/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.3183 - acc: 0.0685Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.3177 - acc: 0.0684 - val_loss: 4.4996 - val_acc: 0.0587
Epoch 31/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.3022 - acc: 0.0679Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.3024 - acc: 0.0680 - val_loss: 4.5011 - val_acc: 0.0539
Epoch 32/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.2847 - acc: 0.0701Epoch 00032: val_loss improved from 4.48441 to 4.47967, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.2844 - acc: 0.0701 - val_loss: 4.4797 - val_acc: 0.0479
Epoch 33/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.2694 - acc: 0.0757Epoch 00033: val_loss improved from 4.47967 to 4.46459, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.2704 - acc: 0.0756 - val_loss: 4.4646 - val_acc: 0.0527
Epoch 34/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.2462 - acc: 0.0776Epoch 00034: val_loss improved from 4.46459 to 4.44946, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.2462 - acc: 0.0780 - val_loss: 4.4495 - val_acc: 0.0587
Epoch 35/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.2321 - acc: 0.0767Epoch 00035: val_loss improved from 4.44946 to 4.42790, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.2313 - acc: 0.0768 - val_loss: 4.4279 - val_acc: 0.0575
Epoch 36/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.2169 - acc: 0.0818Epoch 00036: val_loss improved from 4.42790 to 4.41144, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.2176 - acc: 0.0816 - val_loss: 4.4114 - val_acc: 0.0659
Epoch 37/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.1970 - acc: 0.0796Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.1958 - acc: 0.0798 - val_loss: 4.5105 - val_acc: 0.0635
Epoch 38/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.1852 - acc: 0.0830Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.1834 - acc: 0.0831 - val_loss: 4.4121 - val_acc: 0.0731
Epoch 39/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.1697 - acc: 0.0829Epoch 00039: val_loss improved from 4.41144 to 4.37460, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.1696 - acc: 0.0829 - val_loss: 4.3746 - val_acc: 0.0575
Epoch 40/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.1512 - acc: 0.0898Epoch 00040: val_loss improved from 4.37460 to 4.36767, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.1512 - acc: 0.0897 - val_loss: 4.3677 - val_acc: 0.0575
Epoch 41/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.1360 - acc: 0.0890Epoch 00041: val_loss improved from 4.36767 to 4.34547, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 23s 3ms/step - loss: 4.1355 - acc: 0.0889 - val_loss: 4.3455 - val_acc: 0.0623
Epoch 42/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.1224 - acc: 0.0932Epoch 00042: val_loss did not improve
6680/6680 [==============================] - 23s 3ms/step - loss: 4.1219 - acc: 0.0933 - val_loss: 4.3672 - val_acc: 0.0707
Epoch 43/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.1018 - acc: 0.0926Epoch 00043: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.1026 - acc: 0.0927 - val_loss: 4.3497 - val_acc: 0.0683
Epoch 44/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.0892 - acc: 0.0962Epoch 00044: val_loss improved from 4.34547 to 4.32110, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 23s 3ms/step - loss: 4.0885 - acc: 0.0963 - val_loss: 4.3211 - val_acc: 0.0695
Epoch 45/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.0787 - acc: 0.0944Epoch 00045: val_loss improved from 4.32110 to 4.31945, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0774 - acc: 0.0946 - val_loss: 4.3194 - val_acc: 0.0778
Epoch 46/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.0653 - acc: 0.1008Epoch 00046: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0642 - acc: 0.1010 - val_loss: 4.3330 - val_acc: 0.0731
Epoch 47/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.0453 - acc: 0.1006Epoch 00047: val_loss improved from 4.31945 to 4.29127, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0455 - acc: 0.1006 - val_loss: 4.2913 - val_acc: 0.0731
Epoch 48/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.0343 - acc: 0.1014Epoch 00048: val_loss improved from 4.29127 to 4.27281, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0329 - acc: 0.1013 - val_loss: 4.2728 - val_acc: 0.0707
Epoch 49/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.0209 - acc: 0.1020Epoch 00049: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0210 - acc: 0.1018 - val_loss: 4.2748 - val_acc: 0.0754
Epoch 50/50
6660/6680 [============================>.] - ETA: 0s - loss: 4.0094 - acc: 0.1090Epoch 00050: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0093 - acc: 0.1090 - val_loss: 4.2840 - val_acc: 0.0683
Out[18]:
<keras.callbacks.History at 0x7f0611b4a128>

Load the Model with the Best Validation Loss

In [19]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

In [20]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 7.7751%

Step 4: Use a CNN to Classify Dog Breeds

In the following step, we will take a chance to use transfer learning to train our own CNN.

Obtain Bottleneck Features

In [21]:
bottleneck_features = np.load('/data/bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [22]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 512)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [23]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [24]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6540/6680 [============================>.] - ETA: 0s - loss: 12.2736 - acc: 0.1228Epoch 00001: val_loss improved from inf to 10.61371, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 362us/step - loss: 12.2338 - acc: 0.1259 - val_loss: 10.6137 - val_acc: 0.2036
Epoch 2/20
6620/6680 [============================>.] - ETA: 0s - loss: 10.0879 - acc: 0.2846Epoch 00002: val_loss improved from 10.61371 to 9.85343, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 270us/step - loss: 10.0843 - acc: 0.2850 - val_loss: 9.8534 - val_acc: 0.3006
Epoch 3/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.5865 - acc: 0.3439Epoch 00003: val_loss improved from 9.85343 to 9.68828, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 247us/step - loss: 9.5965 - acc: 0.3437 - val_loss: 9.6883 - val_acc: 0.3126
Epoch 4/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.2648 - acc: 0.3737Epoch 00004: val_loss improved from 9.68828 to 9.39749, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 9.2565 - acc: 0.3743 - val_loss: 9.3975 - val_acc: 0.3234
Epoch 5/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.9905 - acc: 0.4023Epoch 00005: val_loss improved from 9.39749 to 9.27172, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 8.9581 - acc: 0.4042 - val_loss: 9.2717 - val_acc: 0.3473
Epoch 6/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.8536 - acc: 0.4208Epoch 00006: val_loss improved from 9.27172 to 9.18634, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 246us/step - loss: 8.8561 - acc: 0.4208 - val_loss: 9.1863 - val_acc: 0.3569
Epoch 7/20
6540/6680 [============================>.] - ETA: 0s - loss: 8.7786 - acc: 0.4291Epoch 00007: val_loss improved from 9.18634 to 9.07405, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 247us/step - loss: 8.7453 - acc: 0.4311 - val_loss: 9.0740 - val_acc: 0.3605
Epoch 8/20
6520/6680 [============================>.] - ETA: 0s - loss: 8.5256 - acc: 0.4436Epoch 00008: val_loss improved from 9.07405 to 8.94238, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 8.5254 - acc: 0.4433 - val_loss: 8.9424 - val_acc: 0.3749
Epoch 9/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.4472 - acc: 0.4571Epoch 00009: val_loss improved from 8.94238 to 8.90877, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 246us/step - loss: 8.4381 - acc: 0.4578 - val_loss: 8.9088 - val_acc: 0.3749
Epoch 10/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.2819 - acc: 0.4648Epoch 00010: val_loss improved from 8.90877 to 8.86491, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 246us/step - loss: 8.2871 - acc: 0.4647 - val_loss: 8.8649 - val_acc: 0.3713
Epoch 11/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.0658 - acc: 0.4674Epoch 00011: val_loss improved from 8.86491 to 8.60820, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 8.0730 - acc: 0.4666 - val_loss: 8.6082 - val_acc: 0.3916
Epoch 12/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.6094 - acc: 0.4962Epoch 00012: val_loss improved from 8.60820 to 8.13015, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 244us/step - loss: 7.6066 - acc: 0.4964 - val_loss: 8.1302 - val_acc: 0.4096
Epoch 13/20
6440/6680 [===========================>..] - ETA: 0s - loss: 7.2234 - acc: 0.5202Epoch 00013: val_loss improved from 8.13015 to 7.91897, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 247us/step - loss: 7.2439 - acc: 0.5195 - val_loss: 7.9190 - val_acc: 0.4132
Epoch 14/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.0621 - acc: 0.5386Epoch 00014: val_loss improved from 7.91897 to 7.73650, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 246us/step - loss: 7.0575 - acc: 0.5389 - val_loss: 7.7365 - val_acc: 0.4311
Epoch 15/20
6600/6680 [============================>.] - ETA: 0s - loss: 6.8767 - acc: 0.5492Epoch 00015: val_loss improved from 7.73650 to 7.56981, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 247us/step - loss: 6.8903 - acc: 0.5485 - val_loss: 7.5698 - val_acc: 0.4407
Epoch 16/20
6580/6680 [============================>.] - ETA: 0s - loss: 6.7685 - acc: 0.5641Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 269us/step - loss: 6.7787 - acc: 0.5632 - val_loss: 7.6606 - val_acc: 0.4371
Epoch 17/20
6500/6680 [============================>.] - ETA: 0s - loss: 6.7374 - acc: 0.5700Epoch 00017: val_loss improved from 7.56981 to 7.53296, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 280us/step - loss: 6.7245 - acc: 0.5707 - val_loss: 7.5330 - val_acc: 0.4587
Epoch 18/20
6580/6680 [============================>.] - ETA: 0s - loss: 6.6878 - acc: 0.5733Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 278us/step - loss: 6.6941 - acc: 0.5729 - val_loss: 7.6940 - val_acc: 0.4263
Epoch 19/20
6620/6680 [============================>.] - ETA: 0s - loss: 6.6379 - acc: 0.5766Epoch 00019: val_loss improved from 7.53296 to 7.51996, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 252us/step - loss: 6.6459 - acc: 0.5762 - val_loss: 7.5200 - val_acc: 0.4563
Epoch 20/20
6520/6680 [============================>.] - ETA: 0s - loss: 6.5927 - acc: 0.5836Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 251us/step - loss: 6.6080 - acc: 0.5828 - val_loss: 7.5270 - val_acc: 0.4515
Out[24]:
<keras.callbacks.History at 0x7f05e7f22cc0>

Load the Model with the Best Validation Loss

In [25]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [26]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 45.3349%

Predict Dog Breed with the Model

In [27]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, we must use the bottleneck features from a different pre-trained model. To make things easier, the features are pre-computed for all of the networks that are currently available in Keras. These are already in the workspace, at /data/bottleneck_features.

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception.

The above architectures are downloaded and stored for you in the /data/bottleneck_features/ folder.

This means the following will be in the /data/bottleneck_features/ folder:

DogVGG19Data.npz DogResnet50Data.npz DogInceptionV3Data.npz DogXceptionData.npz

Obtain Bottleneck Features

In the code block below, we extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('/data/bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [34]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features_VGG19 = np.load('/data/bottleneck_features/DogVGG19Data.npz')
train_VGG19 = bottleneck_features_VGG19['train']
valid_VGG19 = bottleneck_features_VGG19['valid']
test_VGG19 = bottleneck_features_VGG19['test']

### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features_Resnet50 = np.load('/data/bottleneck_features/DogResnet50Data.npz')
train_Resnet50 = bottleneck_features_Resnet50['train']
valid_Resnet50 = bottleneck_features_Resnet50['valid']
test_Resnet50 = bottleneck_features_Resnet50['test']


### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features_InceptionV3 = np.load('/data/bottleneck_features/DogInceptionV3Data.npz')
train_InceptionV3 = bottleneck_features_InceptionV3['train']
valid_InceptionV3 = bottleneck_features_InceptionV3['valid']
test_InceptionV3 = bottleneck_features_InceptionV3['test']

### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features_Xception = np.load('/data/bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features_Xception['train']
valid_Xception = bottleneck_features_Xception['valid']
test_Xception = bottleneck_features_Xception['test']

Model Architecture

  1. At first, I loaded the bottleneck features for all of the four pre-trained CNNs
  2. Secondly, I created the four models and added a Dense layer representing each breed
  3. Thirdly, I compiled the model with the suited optimizers and the accuracy metric
  4. The model is then trained to fit the bottleneck features to each breed given by the labelled data
  5. I then get four different results for accuracy for the validation data which you will see in the training epochs yourself:
  6. Choosing the best suited model: I chose Xception with an overall accuracy of 84.6890% on the test dataset

Why is Xception a great choice for our data?

At first, I want to mention that all of these models have been trained on the ImageNet dataset which has been described earlier. Xception is built upon the idea of inceptions (which were introduced by the Inception model which is Google's work). Inceptions. I found this great article about inceptions on medium (https://towardsdatascience.com/a-simple-guide-to-the-versions-of-the-inception-network-7fc52b863202):

The Premise: Salient parts in the image can have extremely large variation in size. Shown here:

Image of dog From left: A dog occupying most of the image, a dog occupying a part of it, and a dog occupying very little space (Images obtained from Unsplash).

  • Because of this huge variation in the location of the information, choosing the right kernel size for the convolution operation becomes tough. A larger kernel is preferred for information that is distributed more globally, and a smaller kernel is preferred for information that is distributed more locally.
  • Very deep networks are prone to overfitting.
  • It also hard to pass gradient updates through the entire network.
  • Naively stacking large convolution operations is computationally expensive.

The Solution: Why not have filters with multiple sizes operate on the same level? The network essentially would get a bit “wider” rather than “deeper”. The authors designed the inception module to reflect the same.

The below image is the “naive” inception module. It performs convolution on an input, with 3 different sizes of filters (1x1, 3x3, 5x5). Additionally, max pooling is also performed. The outputs are concatenated and sent to the next inception module.

This way, we gather more information in a more efficient way. This works well for our dataset, because the pictures vary in a lot of ways (like explained above). So we can improve the feature extraction with this model.

That's how the architecture of the Xception CNN works:

Xception

VGG-19 model

In [35]:
### TODO: Define your architecture.
VGG19_model = Sequential()
VGG19_model.add(GlobalAveragePooling2D(input_shape=train_VGG19.shape[1:]))
VGG19_model.add(Dense(133, activation='softmax'))

VGG19_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_5 ( (None, 512)               0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

ResNet 50

In [36]:
### TODO: Define your architecture.
Resnet50_model = Sequential()
Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
Resnet50_model.add(Dense(133, activation='softmax'))

Resnet50_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_6 ( (None, 2048)              0         
_________________________________________________________________
dense_6 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

Inception V3

In [37]:
### TODO: Define your architecture.
InceptionV3_model = Sequential()
InceptionV3_model.add(GlobalAveragePooling2D(input_shape=train_InceptionV3.shape[1:]))
InceptionV3_model.add(Dense(133, activation='softmax'))

InceptionV3_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_7 ( (None, 2048)              0         
_________________________________________________________________
dense_7 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

Xception

In [38]:
### TODO: Define your architecture.
Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
Xception_model.add(Dense(133, activation='softmax'))

Xception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_8 ( (None, 2048)              0         
_________________________________________________________________
dense_8 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

VGG-19

In [39]:
### TODO: Compile the model.
VGG19_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
Resnet50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
InceptionV3_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
Xception_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [40]:
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5', 
                               verbose=1, save_best_only=True)

VGG19_model.fit(train_VGG19, train_targets, 
          validation_data=(valid_VGG19, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6660/6680 [============================>.] - ETA: 0s - loss: 11.7838 - acc: 0.1275Epoch 00001: val_loss improved from inf to 10.14753, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 3s 377us/step - loss: 11.7804 - acc: 0.1275 - val_loss: 10.1475 - val_acc: 0.2335
Epoch 2/20
6640/6680 [============================>.] - ETA: 0s - loss: 9.3048 - acc: 0.3122Epoch 00002: val_loss improved from 10.14753 to 9.36719, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 304us/step - loss: 9.3094 - acc: 0.3121 - val_loss: 9.3672 - val_acc: 0.3006
Epoch 3/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.8140 - acc: 0.3838Epoch 00003: val_loss improved from 9.36719 to 9.06758, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 268us/step - loss: 8.8085 - acc: 0.3843 - val_loss: 9.0676 - val_acc: 0.3485
Epoch 4/20
6460/6680 [============================>.] - ETA: 0s - loss: 8.5144 - acc: 0.4223Epoch 00004: val_loss improved from 9.06758 to 8.82302, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 249us/step - loss: 8.5313 - acc: 0.4213 - val_loss: 8.8230 - val_acc: 0.3713
Epoch 5/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.2998 - acc: 0.4456Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 2s 285us/step - loss: 8.3153 - acc: 0.4446 - val_loss: 8.8359 - val_acc: 0.3749
Epoch 6/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.2008 - acc: 0.4616Epoch 00006: val_loss improved from 8.82302 to 8.69706, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 293us/step - loss: 8.2006 - acc: 0.4612 - val_loss: 8.6971 - val_acc: 0.3808
Epoch 7/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.0715 - acc: 0.4759Epoch 00007: val_loss improved from 8.69706 to 8.53559, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 280us/step - loss: 8.0517 - acc: 0.4774 - val_loss: 8.5356 - val_acc: 0.4096
Epoch 8/20
6460/6680 [============================>.] - ETA: 0s - loss: 8.0022 - acc: 0.4870Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s 253us/step - loss: 7.9953 - acc: 0.4870 - val_loss: 8.5729 - val_acc: 0.3964
Epoch 9/20
6520/6680 [============================>.] - ETA: 0s - loss: 7.8871 - acc: 0.4911Epoch 00009: val_loss improved from 8.53559 to 8.41363, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 258us/step - loss: 7.8912 - acc: 0.4913 - val_loss: 8.4136 - val_acc: 0.4036
Epoch 10/20
6520/6680 [============================>.] - ETA: 0s - loss: 7.7969 - acc: 0.5052Epoch 00010: val_loss improved from 8.41363 to 8.40161, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 254us/step - loss: 7.8181 - acc: 0.5040 - val_loss: 8.4016 - val_acc: 0.4204
Epoch 11/20
6480/6680 [============================>.] - ETA: 0s - loss: 7.7594 - acc: 0.5062Epoch 00011: val_loss improved from 8.40161 to 8.29198, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 254us/step - loss: 7.7724 - acc: 0.5049 - val_loss: 8.2920 - val_acc: 0.4192
Epoch 12/20
6500/6680 [============================>.] - ETA: 0s - loss: 7.4893 - acc: 0.5125Epoch 00012: val_loss improved from 8.29198 to 8.08135, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 252us/step - loss: 7.5099 - acc: 0.5111 - val_loss: 8.0813 - val_acc: 0.4263
Epoch 13/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.2374 - acc: 0.5257Epoch 00013: val_loss improved from 8.08135 to 7.86483, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 255us/step - loss: 7.2447 - acc: 0.5253 - val_loss: 7.8648 - val_acc: 0.4395
Epoch 14/20
6580/6680 [============================>.] - ETA: 0s - loss: 7.1369 - acc: 0.5407Epoch 00014: val_loss improved from 7.86483 to 7.83247, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 250us/step - loss: 7.1355 - acc: 0.5409 - val_loss: 7.8325 - val_acc: 0.4359
Epoch 15/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.0182 - acc: 0.5508Epoch 00015: val_loss improved from 7.83247 to 7.65418, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 249us/step - loss: 7.0323 - acc: 0.5500 - val_loss: 7.6542 - val_acc: 0.4551
Epoch 16/20
6480/6680 [============================>.] - ETA: 0s - loss: 6.9683 - acc: 0.5563Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 247us/step - loss: 6.9644 - acc: 0.5564 - val_loss: 7.6825 - val_acc: 0.4539
Epoch 17/20
6500/6680 [============================>.] - ETA: 0s - loss: 6.9472 - acc: 0.5620Epoch 00017: val_loss improved from 7.65418 to 7.60798, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 249us/step - loss: 6.9422 - acc: 0.5621 - val_loss: 7.6080 - val_acc: 0.4683
Epoch 18/20
6600/6680 [============================>.] - ETA: 0s - loss: 6.9084 - acc: 0.5635Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 249us/step - loss: 6.9176 - acc: 0.5629 - val_loss: 7.7285 - val_acc: 0.4503
Epoch 19/20
6560/6680 [============================>.] - ETA: 0s - loss: 6.7672 - acc: 0.5666Epoch 00019: val_loss improved from 7.60798 to 7.50291, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 251us/step - loss: 6.7734 - acc: 0.5660 - val_loss: 7.5029 - val_acc: 0.4551
Epoch 20/20
6560/6680 [============================>.] - ETA: 0s - loss: 6.6482 - acc: 0.5771Epoch 00020: val_loss improved from 7.50291 to 7.45366, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s 252us/step - loss: 6.6334 - acc: 0.5781 - val_loss: 7.4537 - val_acc: 0.4647
Out[40]:
<keras.callbacks.History at 0x7f05e7d17f98>
In [41]:
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5', 
                               verbose=1, save_best_only=True)

Resnet50_model.fit(train_Resnet50, train_targets, 
          validation_data=(valid_Resnet50, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6660/6680 [============================>.] - ETA: 0s - loss: 1.6407 - acc: 0.5970Epoch 00001: val_loss improved from inf to 0.81577, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s 279us/step - loss: 1.6381 - acc: 0.5975 - val_loss: 0.8158 - val_acc: 0.7497
Epoch 2/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.4355 - acc: 0.8670Epoch 00002: val_loss improved from 0.81577 to 0.69946, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 1s 223us/step - loss: 0.4352 - acc: 0.8671 - val_loss: 0.6995 - val_acc: 0.7856
Epoch 3/20
6480/6680 [============================>.] - ETA: 0s - loss: 0.2599 - acc: 0.9187Epoch 00003: val_loss improved from 0.69946 to 0.62906, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s 227us/step - loss: 0.2608 - acc: 0.9180 - val_loss: 0.6291 - val_acc: 0.8132
Epoch 4/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.1744 - acc: 0.9443Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 1s 223us/step - loss: 0.1749 - acc: 0.9445 - val_loss: 0.6426 - val_acc: 0.8156
Epoch 5/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1176 - acc: 0.9649Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 1s 222us/step - loss: 0.1185 - acc: 0.9644 - val_loss: 0.6597 - val_acc: 0.8156
Epoch 6/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.0845 - acc: 0.9759Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 1s 223us/step - loss: 0.0838 - acc: 0.9762 - val_loss: 0.7007 - val_acc: 0.8072
Epoch 7/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0642 - acc: 0.9811Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 1s 224us/step - loss: 0.0643 - acc: 0.9808 - val_loss: 0.6984 - val_acc: 0.8144
Epoch 8/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0479 - acc: 0.9868Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 1s 221us/step - loss: 0.0480 - acc: 0.9867 - val_loss: 0.6940 - val_acc: 0.8240
Epoch 9/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0355 - acc: 0.9898Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 235us/step - loss: 0.0355 - acc: 0.9898 - val_loss: 0.7380 - val_acc: 0.8228
Epoch 10/20
6440/6680 [===========================>..] - ETA: 0s - loss: 0.0267 - acc: 0.9933Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 1s 223us/step - loss: 0.0262 - acc: 0.9936 - val_loss: 0.7534 - val_acc: 0.8192
Epoch 11/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.0205 - acc: 0.9940Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s 226us/step - loss: 0.0218 - acc: 0.9940 - val_loss: 0.8210 - val_acc: 0.8168
Epoch 12/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.0152 - acc: 0.9963Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 1s 223us/step - loss: 0.0153 - acc: 0.9964 - val_loss: 0.8069 - val_acc: 0.8240
Epoch 13/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.0111 - acc: 0.9971Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 1s 224us/step - loss: 0.0119 - acc: 0.9970 - val_loss: 0.8089 - val_acc: 0.8251
Epoch 14/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0110 - acc: 0.9971Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 1s 222us/step - loss: 0.0109 - acc: 0.9972 - val_loss: 0.8305 - val_acc: 0.8180
Epoch 15/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0102 - acc: 0.9974Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 1s 222us/step - loss: 0.0102 - acc: 0.9975 - val_loss: 0.8234 - val_acc: 0.8251
Epoch 16/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0088 - acc: 0.9977Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 1s 224us/step - loss: 0.0088 - acc: 0.9978 - val_loss: 0.8184 - val_acc: 0.8240
Epoch 17/20
6420/6680 [===========================>..] - ETA: 0s - loss: 0.0087 - acc: 0.9981Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 1s 220us/step - loss: 0.0086 - acc: 0.9981 - val_loss: 0.8653 - val_acc: 0.8359
Epoch 18/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.0066 - acc: 0.9988Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 1s 222us/step - loss: 0.0065 - acc: 0.9988 - val_loss: 0.9587 - val_acc: 0.8168
Epoch 19/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0071 - acc: 0.9980Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 1s 222us/step - loss: 0.0071 - acc: 0.9981 - val_loss: 0.8868 - val_acc: 0.8347
Epoch 20/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.0052 - acc: 0.9986Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 1s 223us/step - loss: 0.0051 - acc: 0.9987 - val_loss: 0.9602 - val_acc: 0.8156
Out[41]:
<keras.callbacks.History at 0x7f05e4440f60>
In [42]:
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.InceptionV3.hdf5', 
                               verbose=1, save_best_only=True)

InceptionV3_model.fit(train_InceptionV3, train_targets, 
          validation_data=(valid_InceptionV3, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6560/6680 [============================>.] - ETA: 0s - loss: 1.1678 - acc: 0.7099Epoch 00001: val_loss improved from inf to 0.69237, saving model to saved_models/weights.best.InceptionV3.hdf5
6680/6680 [==============================] - 2s 367us/step - loss: 1.1587 - acc: 0.7115 - val_loss: 0.6924 - val_acc: 0.7904
Epoch 2/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.4716 - acc: 0.8553Epoch 00002: val_loss improved from 0.69237 to 0.67377, saving model to saved_models/weights.best.InceptionV3.hdf5
6680/6680 [==============================] - 2s 300us/step - loss: 0.4712 - acc: 0.8554 - val_loss: 0.6738 - val_acc: 0.8144
Epoch 3/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.3577 - acc: 0.8877Epoch 00003: val_loss improved from 0.67377 to 0.66898, saving model to saved_models/weights.best.InceptionV3.hdf5
6680/6680 [==============================] - 2s 299us/step - loss: 0.3576 - acc: 0.8874 - val_loss: 0.6690 - val_acc: 0.8383
Epoch 4/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.2882 - acc: 0.9112Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 2s 297us/step - loss: 0.2891 - acc: 0.9111 - val_loss: 0.7070 - val_acc: 0.8443
Epoch 5/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.2393 - acc: 0.9233Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 2s 323us/step - loss: 0.2400 - acc: 0.9234 - val_loss: 0.7836 - val_acc: 0.8395
Epoch 6/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.2073 - acc: 0.9330Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 2s 350us/step - loss: 0.2067 - acc: 0.9332 - val_loss: 0.7294 - val_acc: 0.8383
Epoch 7/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.1675 - acc: 0.9505Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s 321us/step - loss: 0.1687 - acc: 0.9501 - val_loss: 0.7898 - val_acc: 0.8479
Epoch 8/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.1506 - acc: 0.9517Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s 366us/step - loss: 0.1503 - acc: 0.9519 - val_loss: 0.7430 - val_acc: 0.8587
Epoch 9/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.1259 - acc: 0.9583Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 354us/step - loss: 0.1258 - acc: 0.9585 - val_loss: 0.8366 - val_acc: 0.8467
Epoch 10/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.1063 - acc: 0.9686Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s 344us/step - loss: 0.1066 - acc: 0.9684 - val_loss: 0.8006 - val_acc: 0.8587
Epoch 11/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.0927 - acc: 0.9685Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 3s 387us/step - loss: 0.0923 - acc: 0.9687 - val_loss: 0.7915 - val_acc: 0.8503
Epoch 12/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0785 - acc: 0.9748Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 3s 385us/step - loss: 0.0792 - acc: 0.9746 - val_loss: 0.8119 - val_acc: 0.8419
Epoch 13/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.0710 - acc: 0.9776Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 339us/step - loss: 0.0708 - acc: 0.9775 - val_loss: 0.9214 - val_acc: 0.8383
Epoch 14/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0625 - acc: 0.9805Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 2s 338us/step - loss: 0.0620 - acc: 0.9807 - val_loss: 0.8610 - val_acc: 0.8563
Epoch 15/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.0550 - acc: 0.9827Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 346us/step - loss: 0.0548 - acc: 0.9828 - val_loss: 0.8481 - val_acc: 0.8539
Epoch 16/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0476 - acc: 0.9838Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 326us/step - loss: 0.0473 - acc: 0.9840 - val_loss: 0.8816 - val_acc: 0.8599
Epoch 17/20
6500/6680 [============================>.] - ETA: 0s - loss: 0.0431 - acc: 0.9866Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 345us/step - loss: 0.0449 - acc: 0.9862 - val_loss: 0.9226 - val_acc: 0.8491
Epoch 18/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0349 - acc: 0.9891Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 326us/step - loss: 0.0349 - acc: 0.9891 - val_loss: 0.9728 - val_acc: 0.8527
Epoch 19/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.0347 - acc: 0.9891Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s 355us/step - loss: 0.0353 - acc: 0.9891 - val_loss: 0.9504 - val_acc: 0.8491
Epoch 20/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.0291 - acc: 0.9898Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 373us/step - loss: 0.0294 - acc: 0.9898 - val_loss: 0.9598 - val_acc: 0.8527
Out[42]:
<keras.callbacks.History at 0x7f05e41d9198>
In [43]:
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', 
                               verbose=1, save_best_only=True)

Xception_model.fit(train_Xception, train_targets, 
          validation_data=(valid_Xception, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6580/6680 [============================>.] - ETA: 0s - loss: 1.0789 - acc: 0.7336Epoch 00001: val_loss improved from inf to 0.53533, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 4s 578us/step - loss: 1.0699 - acc: 0.7349 - val_loss: 0.5353 - val_acc: 0.8275
Epoch 2/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.3958 - acc: 0.8729Epoch 00002: val_loss improved from 0.53533 to 0.48770, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s 414us/step - loss: 0.3962 - acc: 0.8731 - val_loss: 0.4877 - val_acc: 0.8527
Epoch 3/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.3173 - acc: 0.8977Epoch 00003: val_loss improved from 0.48770 to 0.46861, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s 446us/step - loss: 0.3175 - acc: 0.8979 - val_loss: 0.4686 - val_acc: 0.8587
Epoch 4/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.2801 - acc: 0.9136Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 3s 488us/step - loss: 0.2810 - acc: 0.9130 - val_loss: 0.4801 - val_acc: 0.8563
Epoch 5/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.2432 - acc: 0.9211Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 3s 457us/step - loss: 0.2440 - acc: 0.9204 - val_loss: 0.5320 - val_acc: 0.8539
Epoch 6/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.2154 - acc: 0.9337Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 3s 434us/step - loss: 0.2177 - acc: 0.9332 - val_loss: 0.5379 - val_acc: 0.8515
Epoch 7/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.1921 - acc: 0.9403Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 3s 499us/step - loss: 0.1916 - acc: 0.9404 - val_loss: 0.5153 - val_acc: 0.8623
Epoch 8/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1765 - acc: 0.9470Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 3s 503us/step - loss: 0.1782 - acc: 0.9466 - val_loss: 0.5433 - val_acc: 0.8587
Epoch 9/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1605 - acc: 0.9489Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 3s 446us/step - loss: 0.1597 - acc: 0.9493 - val_loss: 0.5233 - val_acc: 0.8587
Epoch 10/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.1464 - acc: 0.9535Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 3s 465us/step - loss: 0.1470 - acc: 0.9531 - val_loss: 0.5943 - val_acc: 0.8527
Epoch 11/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.1382 - acc: 0.9576Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 3s 435us/step - loss: 0.1378 - acc: 0.9576 - val_loss: 0.6305 - val_acc: 0.8467
Epoch 12/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1250 - acc: 0.9625Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 3s 468us/step - loss: 0.1249 - acc: 0.9626 - val_loss: 0.6196 - val_acc: 0.8539
Epoch 13/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.1160 - acc: 0.9665Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 3s 424us/step - loss: 0.1164 - acc: 0.9662 - val_loss: 0.6134 - val_acc: 0.8635
Epoch 14/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.1078 - acc: 0.9653Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 3s 478us/step - loss: 0.1093 - acc: 0.9647 - val_loss: 0.6094 - val_acc: 0.8587
Epoch 15/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.0986 - acc: 0.9716Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 3s 490us/step - loss: 0.0976 - acc: 0.9719 - val_loss: 0.6241 - val_acc: 0.8539
Epoch 16/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0886 - acc: 0.9709Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 3s 450us/step - loss: 0.0910 - acc: 0.9707 - val_loss: 0.6695 - val_acc: 0.8611
Epoch 17/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0856 - acc: 0.9748Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 3s 451us/step - loss: 0.0854 - acc: 0.9749 - val_loss: 0.6573 - val_acc: 0.8515
Epoch 18/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0815 - acc: 0.9751Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 3s 470us/step - loss: 0.0817 - acc: 0.9751 - val_loss: 0.6407 - val_acc: 0.8623
Epoch 19/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0748 - acc: 0.9777Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 3s 434us/step - loss: 0.0754 - acc: 0.9777 - val_loss: 0.7113 - val_acc: 0.8455
Epoch 20/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0699 - acc: 0.9801Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 3s 462us/step - loss: 0.0698 - acc: 0.9799 - val_loss: 0.6973 - val_acc: 0.8599
Out[43]:
<keras.callbacks.History at 0x7f05e41aae80>

Load the Model with the Best Validation Loss

In [44]:
### TODO: Load the model weights with the best validation loss.
Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')

Test the Model

In [45]:
# get index of predicted dog breed for each image in test set
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 84.6890%

Predict Dog Breed with the Model

In [46]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
def predict_dog_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = Xception_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 6: Write an Algorithm

We are going to write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

Write our Algorithm

In [114]:
import time
import matplotlib.image as mpimg

def print_after_sleep(txt,sec,end=''):
    time.sleep(sec)
    print(txt, end = end)

def my_algorithm(image):
    # probability for being human / dog
    human = face_detector(image)
    dog = dog_detector(image)
    dog_breed = predict_dog_breed(image).split(".")[1].replace("_"," ")
    while True:
        if human and not dog:
            print("Hello there!")
            print_after_sleep("You seem to be of human race. Let's investigate your potential dog breed though",1,end='')
            print_after_sleep(".",1,end='')
            print_after_sleep(".",1,end='')
            print_after_sleep(".",1,end='\n')
            print_after_sleep("I found out! It would be {}".format(dog_breed),1,end='\n')
            break

        elif (human and dog) or (not human and not dog):
            print("Hello there!")
            print_after_sleep("You don't seem to be a human or a dog. I'm not quite sure what kind of thing you are",1,end='')
            print_after_sleep(".",1,end='')
            print_after_sleep(".",1,end='')
            print_after_sleep(".",1,end='\n')
            print_after_sleep("I found out! You must be a human {}".format(dog_breed),1,end='\n')
            break

        elif dog and not human:
            print("Hello there!")
            print_after_sleep("You don't seem to be human",1,end='')
            print_after_sleep(".",1,end='')
            print_after_sleep(".",1,end='')
            print_after_sleep(".",1,end='\n')
            print_after_sleep("Ha! You are a {}".format(dog_breed),1,end='\n')
            break
        
        else:
            break
    print_after_sleep("This is what I got as image: ".format(dog_breed),1,end='\n\n\n')
    img = mpimg.imread(image)
    plt.imshow(img)

Step 7: Test the Algorithm

In [115]:
imgs = ["images/sunny1.JPG","images/sunny2.JPG","images/sunny3.JPG", "images/orisha.jpeg", "images/random.jpeg", "images/myself.JPG", "images/girl.jpg"]
In [116]:
my_algorithm(imgs[0])
Hello there!
You don't seem to be a human or a dog. I'm not quite sure what kind of thing you are...
I found out! You must be a human Chihuahua
This is what I got as image: 


In [117]:
my_algorithm(imgs[1])
Hello there!
You don't seem to be a human or a dog. I'm not quite sure what kind of thing you are...
I found out! You must be a human Chihuahua
This is what I got as image: 


In [118]:
my_algorithm(imgs[2])
Hello there!
You don't seem to be human...
Ha! You are a Finnish spitz
This is what I got as image: 


In [119]:
my_algorithm(imgs[3])
Hello there!
You don't seem to be human...
Ha! You are a German pinscher
This is what I got as image: 


In [120]:
my_algorithm(imgs[4])
Hello there!
You don't seem to be human...
Ha! You are a Chihuahua
This is what I got as image: 


In [121]:
my_algorithm(imgs[5])
Hello there!
You seem to be of human race. Let's investigate your potential dog breed though...
I found out! It would be Lowchen
This is what I got as image: 


Unfortunately, the algorithm doesn't do as well as expected. My dog was classified as human chihuahua twice and got once labelled as a Finnish Spitz. The fact that my dog is a mix of pinscher and spitz makes it pretty hard for the model to correctly tell us what dog breed it has.

  • Adding a breed for my dog: Adding another breed that would match would only partially solve the problem. The more breeds we have the more features the model would have to fit to the data.

  • Using data augmentation to provide more training dasta for each breed: Data Augmentation is a way that increases the variance of pictures. There might be positional aspects the model takes into account which we could lower the impact of. Data Augmentation uses shifts and rotations as well as changing colors (to black and white for example) or lightings or other methods to provide data that has more variance. This would only be usable if the model is built from scratch.

Data Augmentation in action: Data Augmentation Source: https://towardsdatascience.com/image-augmentation-14a0aafd0498

  • Epochs and batch sizes: The batch size defines the gradient and how often to update weights. An epoch is the entire training data exposed to the network, batch-by-batch. Small batch sizes with large epoch size and a large number of training epochs are common in modern deep learning implementations. This may or may not hold with the problem. E.g.:
    • Try batch size equal to training data size, memory depending (batch learning).
    • Try a batch size of one (online learning).
    • Try a grid search of different mini-batch sizes (8, 16, 32, …).
    • Try training for a few epochs and for a heck of a lot of epochs. This would require more time for training and finding the right parameters that are best suited for the model we're training.

Epochs and Batch Sizes

Source: https://www.quora.com/What-is-an-epoch-in-deep-learning