Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


For this project, I implemented a neural network that is capable of identifying a dog's breed from its' picture. I explore face recognition, convolutional neural networks, and transfer learning.

The backbone and structure of this project was created by Udacity, and I built on it.


Why We're Here

This notebook constitutes the first steps towards 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. The image below displays potential sample output of the finished project.

Sample Dog Output

For this project, I piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image is be different from the CNN that infers dog breed. The result is an algorithm that is far from perfect, yet it manages a high accuracy level. This imperfect solution will nonetheless create a fun user experience!

The Road Ahead

Steps in the notebook. 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('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/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("lfw/*/*"))
random.shuffle(human_files)

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 following code cell, we demonstrate how to use this detector to find human faces in the first ten sample images.

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')

for i in range(0,10):

    # load color (BGR) image
    img = cv2.imread(human_files[i])
    # 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
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
Number of faces detected: 1
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.

Write 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

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You 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.

Answer:

In [5]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]

## Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.    
def loop(files, function):
    """Goes through all files in array 'files' and applies 'function' to each of them
    Input:
        files: numpy array containing strings
        function: a python function that takes a string as an argument and returns boolean. 
                  String is a valid path to an image.
    Output:
        count: number of files for which the output of 'function' is True.
    """
    count = 0
    for i in files:
        count += function(i)
    return count
In [12]:
humans = loop(human_files_short, face_detector)
dogs = loop(dog_files_short, face_detector)
humans_all = loop(human_files, face_detector)
dogs_all = loop(train_files, face_detector)
In [13]:
print(str(humans) + " % of the first 100 images in HUMAN_FILES have a detected HUMAN face, but only " + str(round(humans_all*1.0/len(human_files)*100,2)) + " % of ALL human files detected a human face" +"\n")

print(str(dogs) + " % of the first 100 images in DOG_FILES have a detected HUMAN face, and " + str(round(dogs_all*1.0/len(train_files)*100,2)) + " % of ALL dog files detected a human face")
100 % of the first 100 images in HUMAN_FILES have a detected HUMAN face, but only 98.75 % of ALL human files detected a human face

11 % of the first 100 images in DOG_FILES have a detected HUMAN face, and 10.9 % of ALL dog files detected a human face

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!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

Detecting human faces in images that are not clearly presented would require an algorithm that connects to more than one possibility for "human face". Higher order images can be one of the set: profile, eye hidden, mouth hidden, etc. This also requires that it be trained on images that are not a front picture with all features clearly presented. A convolutional neural network would be well equipped to deal with this.


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 [10]:
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 [==============================] - 1s 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 the dataset!

In [6]:
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 [7]:
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, we notice 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 [8]:
### 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)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Test the performance of the dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [11]:
### Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
human_files_short = human_files[:100]
dog_files_short = train_files[:100]

humans_as_dogs = loop(human_files_short, dog_detector)
dogs_as_dogs = loop(dog_files_short, dog_detector)
In [12]:
print(str(humans_as_dogs) + " % of the images in human_files_short have detected a dog \n")
print(str(dogs_as_dogs) + " % of the images in dog_files_short have detected a dog")
0 % of the images in human_files_short have detected a dog 

100 % of the images in dog_files_short have detected a dog
In [24]:
humans_as_dogs = loop(human_files, dog_detector)
In [25]:
print(str(humans_as_dogs)  + " total images, or " + str(round(100.0 * humans_as_dogs/len(human_files),2)) + " % of ALL the " + str(len(human_files)) + " human images have detected a dog")
121 total images, or 0.91 % of ALL the 13233 human images have detected a dog

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. This CNN will be created from scratch (no transfer learning yet!), and I will try to attain a test accuracy of at least 1%. In Step 5 of this notebook, I will use transfer learning to create a CNN that attains greatly improved accuracy.

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, labradors come in yellow, chocolate, and black. This vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

Also, 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%.

Finally, we must notice that the practice is far ahead of the theory in deep learning. So experimenting with many different architectures is essential.

Pre-process the Data

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

In [24]:
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:12<00:00, 92.77it/s] 
100%|██████████| 835/835 [00:07<00:00, 104.74it/s]
100%|██████████| 836/836 [00:08<00:00, 104.38it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed.

Question 4: Outline of the steps to get to the final CNN architecture.

Answer:

I decided to create a series of filters that would decrease in granularity, so that the network would learn from broader to more specific features. That is way there is a progression of layers doubling the number of filters of the previous one.

I believe that setting measures to control for overfitting when the model is learning is a good idea, and comparing my architecture with and without the dropout confirms it.

Lastly, the 200-node dense layer before the output was the result of comparing models with and without it, and with different numbers of nodes. There is no particular argument for it.

In [8]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### Define the architecture.

model = Sequential()
model.add(Conv2D(filters=12, kernel_size=2, padding='same', activation='relu', 
                        input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.1))
model.add(Conv2D(filters=23, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.15))
model.add(Conv2D(filters=56, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.2))
model.add(Conv2D(filters=112, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.25))
model.add(Conv2D(filters=224, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(200, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(133, activation='softmax'))

# Summarize the layers of the model
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 224, 224, 12)      156       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 112, 112, 12)      0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 112, 112, 12)      0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 112, 112, 23)      1127      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 56, 56, 23)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 56, 56, 23)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 56, 56, 56)        5208      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 28, 28, 56)        0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 28, 28, 56)        0         
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 28, 28, 112)       25200     
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 14, 14, 112)       0         
_________________________________________________________________
dropout_4 (Dropout)          (None, 14, 14, 112)       0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 14, 14, 224)       100576    
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 7, 7, 224)         0         
_________________________________________________________________
dropout_5 (Dropout)          (None, 7, 7, 224)         0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 10976)             0         
_________________________________________________________________
dense_1 (Dense)              (None, 200)               2195400   
_________________________________________________________________
dropout_6 (Dropout)          (None, 200)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               26733     
=================================================================
Total params: 2,354,400
Trainable params: 2,354,400
Non-trainable params: 0
_________________________________________________________________

Compile the Model

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

(IMPLEMENTATION) Train the Model

In [27]:
from keras.callbacks import ModelCheckpoint  

### Specify the number of epochs to train the model.
epochs = 20


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/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.8955 - acc: 0.0090Epoch 00001: val_loss improved from inf to 4.86758, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 27s 4ms/step - loss: 4.8954 - acc: 0.0090 - val_loss: 4.8676 - val_acc: 0.0120
Epoch 2/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.7434 - acc: 0.0255Epoch 00002: val_loss improved from 4.86758 to 4.61061, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.7429 - acc: 0.0254 - val_loss: 4.6106 - val_acc: 0.0407
Epoch 3/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.4608 - acc: 0.0410Epoch 00003: val_loss improved from 4.61061 to 4.35723, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 25s 4ms/step - loss: 4.4603 - acc: 0.0410 - val_loss: 4.3572 - val_acc: 0.0479
Epoch 4/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.3031 - acc: 0.0550Epoch 00004: val_loss improved from 4.35723 to 4.28707, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 25s 4ms/step - loss: 4.3024 - acc: 0.0549 - val_loss: 4.2871 - val_acc: 0.0467
Epoch 5/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.1739 - acc: 0.0646Epoch 00005: val_loss improved from 4.28707 to 4.18675, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 25s 4ms/step - loss: 4.1731 - acc: 0.0644 - val_loss: 4.1868 - val_acc: 0.0647
Epoch 6/20
6660/6680 [============================>.] - ETA: 0s - loss: 4.0402 - acc: 0.0793Epoch 00006: val_loss improved from 4.18675 to 4.13903, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 25s 4ms/step - loss: 4.0411 - acc: 0.0792 - val_loss: 4.1390 - val_acc: 0.0707
Epoch 7/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.9310 - acc: 0.0938Epoch 00007: val_loss improved from 4.13903 to 4.08113, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 25s 4ms/step - loss: 3.9315 - acc: 0.0939 - val_loss: 4.0811 - val_acc: 0.0754
Epoch 8/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.8623 - acc: 0.1068Epoch 00008: val_loss improved from 4.08113 to 3.99353, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 3.8619 - acc: 0.1067 - val_loss: 3.9935 - val_acc: 0.0802
Epoch 9/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.7469 - acc: 0.1264Epoch 00009: val_loss improved from 3.99353 to 3.94194, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 25s 4ms/step - loss: 3.7459 - acc: 0.1266 - val_loss: 3.9419 - val_acc: 0.0862
Epoch 10/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.6701 - acc: 0.1338Epoch 00010: val_loss improved from 3.94194 to 3.91984, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 3.6698 - acc: 0.1341 - val_loss: 3.9198 - val_acc: 0.0970
Epoch 11/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.5652 - acc: 0.1647Epoch 00011: val_loss improved from 3.91984 to 3.89426, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 3.5653 - acc: 0.1644 - val_loss: 3.8943 - val_acc: 0.1066
Epoch 12/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.5013 - acc: 0.1698Epoch 00012: val_loss improved from 3.89426 to 3.87563, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 3.5014 - acc: 0.1699 - val_loss: 3.8756 - val_acc: 0.1042
Epoch 13/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.4143 - acc: 0.1805Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 24s 4ms/step - loss: 3.4141 - acc: 0.1805 - val_loss: 3.9190 - val_acc: 0.1030
Epoch 14/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.3429 - acc: 0.1947Epoch 00014: val_loss improved from 3.87563 to 3.78889, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 3.3412 - acc: 0.1949 - val_loss: 3.7889 - val_acc: 0.0958
Epoch 15/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.2408 - acc: 0.2089Epoch 00015: val_loss improved from 3.78889 to 3.76890, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 25s 4ms/step - loss: 3.2407 - acc: 0.2090 - val_loss: 3.7689 - val_acc: 0.1114
Epoch 16/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.1891 - acc: 0.2249Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 24s 4ms/step - loss: 3.1883 - acc: 0.2251 - val_loss: 3.8644 - val_acc: 0.0946
Epoch 17/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.1293 - acc: 0.2344Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 24s 4ms/step - loss: 3.1295 - acc: 0.2340 - val_loss: 3.8356 - val_acc: 0.1174
Epoch 18/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.0456 - acc: 0.2512Epoch 00018: val_loss improved from 3.76890 to 3.76755, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 3.0482 - acc: 0.2507 - val_loss: 3.7676 - val_acc: 0.1437
Epoch 19/20
6660/6680 [============================>.] - ETA: 0s - loss: 3.0127 - acc: 0.2596Epoch 00019: val_loss improved from 3.76755 to 3.70951, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 25s 4ms/step - loss: 3.0115 - acc: 0.2599 - val_loss: 3.7095 - val_acc: 0.1293
Epoch 20/20
6660/6680 [============================>.] - ETA: 0s - loss: 2.9830 - acc: 0.2716Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 24s 4ms/step - loss: 2.9829 - acc: 0.2716 - val_loss: 3.7234 - val_acc: 0.1317
Out[27]:
<keras.callbacks.History at 0x7fe2423f5828>

Load the Model with the Best Validation Loss

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

Test the Model

Try out the model on the test dataset of dog images.

In [29]:
# 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: 14.5933%

Step 4: Use a CNN to Classify Dog Breeds

In the following step, I will use transfer learning to train a CNN.

Obtain Bottleneck Features

In [10]:
bottleneck_features = np.load('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 [11]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

# Summarize the layers of the model
VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_1 ( (None, 512)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________
In [12]:
model = Sequential()
model.add(Conv2D(filters=12, kernel_size=2, padding='same', activation='relu', 
                        input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.1))
model.add(Conv2D(filters=23, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.15))
model.add(Conv2D(filters=56, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.2))
model.add(Conv2D(filters=112, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.25))
model.add(Conv2D(filters=224, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(200, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(133, activation='softmax'))

# Summarize the layers of the model
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_6 (Conv2D)            (None, 224, 224, 12)      156       
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 112, 112, 12)      0         
_________________________________________________________________
dropout_7 (Dropout)          (None, 112, 112, 12)      0         
_________________________________________________________________
conv2d_7 (Conv2D)            (None, 112, 112, 23)      1127      
_________________________________________________________________
max_pooling2d_7 (MaxPooling2 (None, 56, 56, 23)        0         
_________________________________________________________________
dropout_8 (Dropout)          (None, 56, 56, 23)        0         
_________________________________________________________________
conv2d_8 (Conv2D)            (None, 56, 56, 56)        5208      
_________________________________________________________________
max_pooling2d_8 (MaxPooling2 (None, 28, 28, 56)        0         
_________________________________________________________________
dropout_9 (Dropout)          (None, 28, 28, 56)        0         
_________________________________________________________________
conv2d_9 (Conv2D)            (None, 28, 28, 112)       25200     
_________________________________________________________________
max_pooling2d_9 (MaxPooling2 (None, 14, 14, 112)       0         
_________________________________________________________________
dropout_10 (Dropout)         (None, 14, 14, 112)       0         
_________________________________________________________________
conv2d_10 (Conv2D)           (None, 14, 14, 224)       100576    
_________________________________________________________________
max_pooling2d_10 (MaxPooling (None, 7, 7, 224)         0         
_________________________________________________________________
dropout_11 (Dropout)         (None, 7, 7, 224)         0         
_________________________________________________________________
flatten_2 (Flatten)          (None, 10976)             0         
_________________________________________________________________
dense_4 (Dense)              (None, 200)               2195400   
_________________________________________________________________
dropout_12 (Dropout)         (None, 200)               0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               26733     
=================================================================
Total params: 2,354,400
Trainable params: 2,354,400
Non-trainable params: 0
_________________________________________________________________

Compile the Model

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

Train the Model

In [35]:
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
6500/6680 [============================>.] - ETA: 0s - loss: 13.1753 - acc: 0.0908Epoch 00001: val_loss improved from inf to 11.73240, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 301us/step - loss: 13.1506 - acc: 0.0921 - val_loss: 11.7324 - val_acc: 0.1725
Epoch 2/20
6620/6680 [============================>.] - ETA: 0s - loss: 11.3729 - acc: 0.2221Epoch 00002: val_loss improved from 11.73240 to 11.10400, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 243us/step - loss: 11.3747 - acc: 0.2220 - val_loss: 11.1040 - val_acc: 0.2431
Epoch 3/20
6440/6680 [===========================>..] - ETA: 0s - loss: 10.9409 - acc: 0.2731Epoch 00003: val_loss improved from 11.10400 to 11.04253, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 241us/step - loss: 10.9243 - acc: 0.2746 - val_loss: 11.0425 - val_acc: 0.2575
Epoch 4/20
6480/6680 [============================>.] - ETA: 0s - loss: 10.7583 - acc: 0.3002Epoch 00004: val_loss improved from 11.04253 to 10.92344, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 240us/step - loss: 10.7799 - acc: 0.2988 - val_loss: 10.9234 - val_acc: 0.2754
Epoch 5/20
6460/6680 [============================>.] - ETA: 0s - loss: 10.7031 - acc: 0.3107Epoch 00005: val_loss improved from 10.92344 to 10.90337, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 239us/step - loss: 10.7148 - acc: 0.3100 - val_loss: 10.9034 - val_acc: 0.2862
Epoch 6/20
6460/6680 [============================>.] - ETA: 0s - loss: 10.5687 - acc: 0.3204Epoch 00006: val_loss improved from 10.90337 to 10.80287, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 240us/step - loss: 10.5575 - acc: 0.3214 - val_loss: 10.8029 - val_acc: 0.2826
Epoch 7/20
6460/6680 [============================>.] - ETA: 0s - loss: 10.4313 - acc: 0.3288Epoch 00007: val_loss improved from 10.80287 to 10.56685, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 240us/step - loss: 10.3984 - acc: 0.3308 - val_loss: 10.5669 - val_acc: 0.2994
Epoch 8/20
6460/6680 [============================>.] - ETA: 0s - loss: 10.3404 - acc: 0.3426Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s 239us/step - loss: 10.3074 - acc: 0.3446 - val_loss: 10.6157 - val_acc: 0.2970
Epoch 9/20
6500/6680 [============================>.] - ETA: 0s - loss: 10.2262 - acc: 0.3489Epoch 00009: val_loss improved from 10.56685 to 10.43529, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 239us/step - loss: 10.2110 - acc: 0.3499 - val_loss: 10.4353 - val_acc: 0.2958
Epoch 10/20
6440/6680 [===========================>..] - ETA: 0s - loss: 10.0812 - acc: 0.3635Epoch 00010: val_loss improved from 10.43529 to 10.41757, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 241us/step - loss: 10.1197 - acc: 0.3615 - val_loss: 10.4176 - val_acc: 0.3150
Epoch 11/20
6640/6680 [============================>.] - ETA: 0s - loss: 10.0188 - acc: 0.3678Epoch 00011: val_loss improved from 10.41757 to 10.32835, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 242us/step - loss: 10.0119 - acc: 0.3683 - val_loss: 10.3283 - val_acc: 0.3114
Epoch 12/20
6520/6680 [============================>.] - ETA: 0s - loss: 9.9392 - acc: 0.3755Epoch 00012: val_loss improved from 10.32835 to 10.23711, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 237us/step - loss: 9.9295 - acc: 0.3759 - val_loss: 10.2371 - val_acc: 0.3234
Epoch 13/20
6660/6680 [============================>.] - ETA: 0s - loss: 9.8361 - acc: 0.3793Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 240us/step - loss: 9.8381 - acc: 0.3792 - val_loss: 10.2392 - val_acc: 0.3198
Epoch 14/20
6460/6680 [============================>.] - ETA: 0s - loss: 9.8299 - acc: 0.3834Epoch 00014: val_loss improved from 10.23711 to 10.19622, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 240us/step - loss: 9.8086 - acc: 0.3847 - val_loss: 10.1962 - val_acc: 0.3210
Epoch 15/20
6500/6680 [============================>.] - ETA: 0s - loss: 9.7727 - acc: 0.3860Epoch 00015: val_loss improved from 10.19622 to 10.14682, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 239us/step - loss: 9.7627 - acc: 0.3868 - val_loss: 10.1468 - val_acc: 0.3222
Epoch 16/20
6480/6680 [============================>.] - ETA: 0s - loss: 9.7184 - acc: 0.3918Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 240us/step - loss: 9.7341 - acc: 0.3909 - val_loss: 10.1925 - val_acc: 0.3222
Epoch 17/20
6440/6680 [===========================>..] - ETA: 0s - loss: 9.6747 - acc: 0.3908Epoch 00017: val_loss improved from 10.14682 to 10.08711, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 241us/step - loss: 9.6652 - acc: 0.3916 - val_loss: 10.0871 - val_acc: 0.3234
Epoch 18/20
6480/6680 [============================>.] - ETA: 0s - loss: 9.5915 - acc: 0.3969Epoch 00018: val_loss improved from 10.08711 to 10.08410, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 240us/step - loss: 9.5976 - acc: 0.3964 - val_loss: 10.0841 - val_acc: 0.3234
Epoch 19/20
6500/6680 [============================>.] - ETA: 0s - loss: 9.4647 - acc: 0.4026Epoch 00019: val_loss improved from 10.08410 to 9.90801, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 238us/step - loss: 9.4639 - acc: 0.4028 - val_loss: 9.9080 - val_acc: 0.3305
Epoch 20/20
6480/6680 [============================>.] - ETA: 0s - loss: 9.3376 - acc: 0.4091Epoch 00020: val_loss improved from 9.90801 to 9.90097, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 240us/step - loss: 9.3447 - acc: 0.4090 - val_loss: 9.9010 - val_acc: 0.3293
Out[35]:
<keras.callbacks.History at 0x7fe240d9dbe0>

Load the Model with the Best Validation Loss

In [14]:
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 [15]:
# 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: 33.7321%

Predict Dog Breed with the Model

In [16]:
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, I will use the bottleneck features from a different pre-trained model. The following are the networks that are currently available in Keras:

The pre-computed features for all of the above models are encoded as:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. For the present project, I will pick one of the above architectures (VGG19), download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

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

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [39]:
!wget -P dog-project/bottleneck-features https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/DogVGG19Data.npz
--2018-05-09 02:07:13--  https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/DogVGG19Data.npz
Resolving s3-us-west-1.amazonaws.com (s3-us-west-1.amazonaws.com)... 52.219.24.25
Connecting to s3-us-west-1.amazonaws.com (s3-us-west-1.amazonaws.com)|52.219.24.25|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 850230376 (811M) [application/x-www-form-urlencoded]
Saving to: ‘dog-project/bottleneck-features/DogVGG19Data.npz.3’

DogVGG19Data.npz.3  100%[===================>] 810.84M  41.9MB/s    in 23s     

2018-05-09 02:07:36 (35.0 MB/s) - ‘dog-project/bottleneck-features/DogVGG19Data.npz.3’ saved [850230376/850230376]

In [17]:
### Obtain bottleneck features from another pre-trained CNN.
network = 'VGG19'
                                                                        
bottleneck_features = np.load('dog-project/bottleneck-features/Dog'+ network +'Data.npz')
train_ = bottleneck_features['train']
valid_ = bottleneck_features['valid']
test_ = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed.

Question 5: Steps to get to the final CNN architecture and reasoning.

Answer:

The data set on which the base architecture was trained is similar to the dataset for this project, which causes the images from each data set have similar higher level features. This makes most of the information from the pre-trained network revelant for the present dataset. In order to keep this knowledge, suitable for the target dataset, "I" sliced off the end of the pretained network (the bottleneck features provided), and used its body as the starting point of the present network.

I added a few fully connected layers over the pretrained architecture before ending the network with a layer that matches the number of classes in the new data set. The reasoning behind this is that my target of having the network learn the breeds is a step more refined than the knowledge of the pretrained architecture.

For comparison, I also created a "basic" model, in which the output dense layer is immediately after the pretrained architecture. After 20 epochs, the testing accuracy of the basic model hovers around 44%, whereas the more complex model with several dense layers over the pretrained architecture, has over 72% accuracy after 20 epochs.

Basic model

In [20]:
model_basic = Sequential()
# Dimensions reduced with GlobalAveragePooling2D
model_basic.add(GlobalAveragePooling2D(input_shape=(7, 7, 512)))
model_basic.add(Dense(133, activation='softmax'))

model_basic.summary()

# Compile
model_basic.compile(loss='categorical_crossentropy', optimizer='rmsprop', 
                  metrics=['accuracy'])

# Train
checkpointer = ModelCheckpoint(filepath='dogvgg16.weights.best.model_basic', verbose=1, 
                               save_best_only=True)
model_basic.fit(train_, train_targets, epochs=20, validation_data=(valid_, valid_targets), 
          callbacks=[checkpointer], verbose=1, shuffle=True)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 512)               0         
_________________________________________________________________
dense_7 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6464/6680 [============================>.] - ETA: 0s - loss: 11.7340 - acc: 0.1412Epoch 00001: val_loss improved from inf to 10.32378, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 195us/step - loss: 11.6719 - acc: 0.1452 - val_loss: 10.3238 - val_acc: 0.2359
Epoch 2/20
6496/6680 [============================>.] - ETA: 0s - loss: 9.5793 - acc: 0.2977Epoch 00002: val_loss improved from 10.32378 to 9.34774, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 177us/step - loss: 9.5721 - acc: 0.2984 - val_loss: 9.3477 - val_acc: 0.2946
Epoch 3/20
6432/6680 [===========================>..] - ETA: 0s - loss: 8.8572 - acc: 0.3742Epoch 00003: val_loss improved from 9.34774 to 9.12583, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 178us/step - loss: 8.8646 - acc: 0.3734 - val_loss: 9.1258 - val_acc: 0.3365
Epoch 4/20
6400/6680 [===========================>..] - ETA: 0s - loss: 8.5915 - acc: 0.4108Epoch 00004: val_loss improved from 9.12583 to 8.88946, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 179us/step - loss: 8.5673 - acc: 0.4117 - val_loss: 8.8895 - val_acc: 0.3581
Epoch 5/20
6432/6680 [===========================>..] - ETA: 0s - loss: 8.3425 - acc: 0.4389Epoch 00005: val_loss improved from 8.88946 to 8.70658, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 177us/step - loss: 8.3290 - acc: 0.4398 - val_loss: 8.7066 - val_acc: 0.3772
Epoch 6/20
6528/6680 [============================>.] - ETA: 0s - loss: 8.2020 - acc: 0.4579Epoch 00006: val_loss improved from 8.70658 to 8.62758, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 177us/step - loss: 8.1783 - acc: 0.4593 - val_loss: 8.6276 - val_acc: 0.3892
Epoch 7/20
6496/6680 [============================>.] - ETA: 0s - loss: 8.0973 - acc: 0.4752Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 1s 176us/step - loss: 8.1121 - acc: 0.4741 - val_loss: 8.6518 - val_acc: 0.3880
Epoch 8/20
6432/6680 [===========================>..] - ETA: 0s - loss: 8.1139 - acc: 0.4821Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 1s 176us/step - loss: 8.0797 - acc: 0.4843 - val_loss: 8.7182 - val_acc: 0.3820
Epoch 9/20
6432/6680 [===========================>..] - ETA: 0s - loss: 8.0291 - acc: 0.4893Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 1s 177us/step - loss: 8.0593 - acc: 0.4874 - val_loss: 8.6464 - val_acc: 0.3964
Epoch 10/20
6432/6680 [===========================>..] - ETA: 0s - loss: 8.0637 - acc: 0.4921Epoch 00010: val_loss improved from 8.62758 to 8.57318, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 178us/step - loss: 8.0345 - acc: 0.4934 - val_loss: 8.5732 - val_acc: 0.4084
Epoch 11/20
6432/6680 [===========================>..] - ETA: 0s - loss: 7.9721 - acc: 0.4974Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 1s 177us/step - loss: 7.9988 - acc: 0.4955 - val_loss: 8.5963 - val_acc: 0.3964
Epoch 12/20
6432/6680 [===========================>..] - ETA: 0s - loss: 7.9447 - acc: 0.4981Epoch 00012: val_loss improved from 8.57318 to 8.57082, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 178us/step - loss: 7.9384 - acc: 0.4984 - val_loss: 8.5708 - val_acc: 0.4048
Epoch 13/20
6496/6680 [============================>.] - ETA: 0s - loss: 7.7906 - acc: 0.5057Epoch 00013: val_loss improved from 8.57082 to 8.44795, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 178us/step - loss: 7.8134 - acc: 0.5042 - val_loss: 8.4479 - val_acc: 0.4132
Epoch 14/20
6464/6680 [============================>.] - ETA: 0s - loss: 7.6938 - acc: 0.5167Epoch 00014: val_loss improved from 8.44795 to 8.33224, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 179us/step - loss: 7.7349 - acc: 0.5142 - val_loss: 8.3322 - val_acc: 0.4216
Epoch 15/20
6464/6680 [============================>.] - ETA: 0s - loss: 7.7500 - acc: 0.5152Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 1s 176us/step - loss: 7.7165 - acc: 0.5172 - val_loss: 8.3367 - val_acc: 0.4156
Epoch 16/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.6036 - acc: 0.5203Epoch 00016: val_loss improved from 8.33224 to 8.29001, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 176us/step - loss: 7.5893 - acc: 0.5213 - val_loss: 8.2900 - val_acc: 0.4216
Epoch 17/20
6432/6680 [===========================>..] - ETA: 0s - loss: 7.5056 - acc: 0.5271Epoch 00017: val_loss improved from 8.29001 to 8.14251, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 178us/step - loss: 7.4863 - acc: 0.5284 - val_loss: 8.1425 - val_acc: 0.4228
Epoch 18/20
6528/6680 [============================>.] - ETA: 0s - loss: 7.4492 - acc: 0.5323Epoch 00018: val_loss improved from 8.14251 to 8.10620, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 176us/step - loss: 7.4366 - acc: 0.5332 - val_loss: 8.1062 - val_acc: 0.4407
Epoch 19/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.4121 - acc: 0.5375Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 1s 175us/step - loss: 7.4156 - acc: 0.5368 - val_loss: 8.1690 - val_acc: 0.4263
Epoch 20/20
6528/6680 [============================>.] - ETA: 0s - loss: 7.2986 - acc: 0.5421Epoch 00020: val_loss improved from 8.10620 to 7.98675, saving model to dogvgg16.weights.best.model_basic
6680/6680 [==============================] - 1s 176us/step - loss: 7.3231 - acc: 0.5407 - val_loss: 7.9867 - val_acc: 0.4443
Out[20]:
<keras.callbacks.History at 0x7fe6fc22dac8>
In [21]:
# Load the model weights with the best validation loss.
model_basic.load_weights('dogvgg16.weights.best.model_basic')

predictions = [np.argmax(model_basic.predict(np.expand_dims(feature, axis=0))) 
                     for feature in test_]

# Report test accuracy
test_accuracy = 100*np.sum(np.array(predictions)==
                           np.argmax(test_targets, axis=1))/len(predictions)
print('\nTest accuracy of the basic model: %.4f%%' % test_accuracy)
Test accuracy of the basic model: 43.8995%

Actual model

In [22]:
model = Sequential()
# Dimensions reduced with GlobalAveragePooling2D
model.add(GlobalAveragePooling2D(input_shape=(7, 7, 512)))
model.add(Dense(1000, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(100, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(1000, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(2000, activation='relu'))
model.add(Dropout(0.4))



model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_4 ( (None, 512)               0         
_________________________________________________________________
dense_8 (Dense)              (None, 1000)              513000    
_________________________________________________________________
dropout_13 (Dropout)         (None, 1000)              0         
_________________________________________________________________
dense_9 (Dense)              (None, 100)               100100    
_________________________________________________________________
dropout_14 (Dropout)         (None, 100)               0         
_________________________________________________________________
dense_10 (Dense)             (None, 1000)              101000    
_________________________________________________________________
dropout_15 (Dropout)         (None, 1000)              0         
_________________________________________________________________
dense_11 (Dense)             (None, 2000)              2002000   
_________________________________________________________________
dropout_16 (Dropout)         (None, 2000)              0         
_________________________________________________________________
dense_12 (Dense)             (None, 133)               266133    
=================================================================
Total params: 2,982,233
Trainable params: 2,982,233
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [23]:
### Compile the model.
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', 
                  metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

In [46]:
### Train the model.
checkpointer = ModelCheckpoint(filepath='dogvgg16.weights.best.hdf5', verbose=1, 
                               save_best_only=True)
model.fit(train_, train_targets, epochs=20, validation_data=(valid_, valid_targets), 
          callbacks=[checkpointer], verbose=1, shuffle=True)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6592/6680 [============================>.] - ETA: 0s - loss: 4.8771 - acc: 0.0366Epoch 00001: val_loss improved from inf to 4.42270, saving model to dogvgg16.weights.best.hdf5
6680/6680 [==============================] - 3s 507us/step - loss: 4.8746 - acc: 0.0365 - val_loss: 4.4227 - val_acc: 0.0707
Epoch 2/20
6592/6680 [============================>.] - ETA: 0s - loss: 4.1850 - acc: 0.1077Epoch 00002: val_loss improved from 4.42270 to 3.35075, saving model to dogvgg16.weights.best.hdf5
6680/6680 [==============================] - 3s 434us/step - loss: 4.1803 - acc: 0.1076 - val_loss: 3.3508 - val_acc: 0.1940
Epoch 3/20
6528/6680 [============================>.] - ETA: 0s - loss: 3.0821 - acc: 0.2454Epoch 00003: val_loss improved from 3.35075 to 2.03986, saving model to dogvgg16.weights.best.hdf5
6680/6680 [==============================] - 3s 429us/step - loss: 3.0746 - acc: 0.2458 - val_loss: 2.0399 - val_acc: 0.4287
Epoch 4/20
6656/6680 [============================>.] - ETA: 0s - loss: 2.2153 - acc: 0.4029Epoch 00004: val_loss improved from 2.03986 to 1.50846, saving model to dogvgg16.weights.best.hdf5
6680/6680 [==============================] - 3s 426us/step - loss: 2.2144 - acc: 0.4030 - val_loss: 1.5085 - val_acc: 0.5461
Epoch 5/20
6656/6680 [============================>.] - ETA: 0s - loss: 1.8136 - acc: 0.4904Epoch 00005: val_loss improved from 1.50846 to 1.25779, saving model to dogvgg16.weights.best.hdf5
6680/6680 [==============================] - 3s 432us/step - loss: 1.8127 - acc: 0.4906 - val_loss: 1.2578 - val_acc: 0.6204
Epoch 6/20
6592/6680 [============================>.] - ETA: 0s - loss: 1.5770 - acc: 0.5543Epoch 00006: val_loss improved from 1.25779 to 1.20163, saving model to dogvgg16.weights.best.hdf5
6680/6680 [==============================] - 3s 433us/step - loss: 1.5793 - acc: 0.5531 - val_loss: 1.2016 - val_acc: 0.6563
Epoch 7/20
6656/6680 [============================>.] - ETA: 0s - loss: 1.4269 - acc: 0.5942Epoch 00007: val_loss improved from 1.20163 to 1.11644, saving model to dogvgg16.weights.best.hdf5
6680/6680 [==============================] - 3s 423us/step - loss: 1.4279 - acc: 0.5943 - val_loss: 1.1164 - val_acc: 0.6671
Epoch 8/20
6528/6680 [============================>.] - ETA: 0s - loss: 1.3274 - acc: 0.6245Epoch 00008: val_loss improved from 1.11644 to 1.06343, saving model to dogvgg16.weights.best.hdf5
6680/6680 [==============================] - 3s 424us/step - loss: 1.3249 - acc: 0.6246 - val_loss: 1.0634 - val_acc: 0.6910
Epoch 9/20
6656/6680 [============================>.] - ETA: 0s - loss: 1.2715 - acc: 0.6423Epoch 00009: val_loss improved from 1.06343 to 1.05546, saving model to dogvgg16.weights.best.hdf5
6680/6680 [==============================] - 3s 422us/step - loss: 1.2729 - acc: 0.6418 - val_loss: 1.0555 - val_acc: 0.6874
Epoch 10/20
6528/6680 [============================>.] - ETA: 0s - loss: 1.2583 - acc: 0.6550Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 3s 403us/step - loss: 1.2583 - acc: 0.6542 - val_loss: 1.0763 - val_acc: 0.7054
Epoch 11/20
6624/6680 [============================>.] - ETA: 0s - loss: 1.1794 - acc: 0.6763Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 3s 407us/step - loss: 1.1783 - acc: 0.6763 - val_loss: 1.0751 - val_acc: 0.6934
Epoch 12/20
6656/6680 [============================>.] - ETA: 0s - loss: 1.1479 - acc: 0.6877Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 3s 412us/step - loss: 1.1499 - acc: 0.6873 - val_loss: 1.0878 - val_acc: 0.7066
Epoch 13/20
6560/6680 [============================>.] - ETA: 0s - loss: 1.0890 - acc: 0.7061Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 3s 412us/step - loss: 1.0882 - acc: 0.7061 - val_loss: 1.1522 - val_acc: 0.6874
Epoch 14/20
6624/6680 [============================>.] - ETA: 0s - loss: 1.1649 - acc: 0.7014Epoch 00014: val_loss improved from 1.05546 to 1.04449, saving model to dogvgg16.weights.best.hdf5
6680/6680 [==============================] - 3s 433us/step - loss: 1.1606 - acc: 0.7022 - val_loss: 1.0445 - val_acc: 0.7257
Epoch 15/20
6656/6680 [============================>.] - ETA: 0s - loss: 1.1188 - acc: 0.7102Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 3s 413us/step - loss: 1.1198 - acc: 0.7100 - val_loss: 1.2205 - val_acc: 0.6862
Epoch 16/20
6560/6680 [============================>.] - ETA: 0s - loss: 1.0915 - acc: 0.7215Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 3s 413us/step - loss: 1.0929 - acc: 0.7213 - val_loss: 1.1608 - val_acc: 0.7078
Epoch 17/20
6624/6680 [============================>.] - ETA: 0s - loss: 1.0912 - acc: 0.7249Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 3s 411us/step - loss: 1.0906 - acc: 0.7250 - val_loss: 1.1201 - val_acc: 0.7210
Epoch 18/20
6624/6680 [============================>.] - ETA: 0s - loss: 1.1397 - acc: 0.7281Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 3s 413us/step - loss: 1.1399 - acc: 0.7274 - val_loss: 1.1278 - val_acc: 0.7162
Epoch 19/20
6560/6680 [============================>.] - ETA: 0s - loss: 1.0730 - acc: 0.7338Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 3s 413us/step - loss: 1.0749 - acc: 0.7334 - val_loss: 1.1762 - val_acc: 0.7281
Epoch 20/20
6592/6680 [============================>.] - ETA: 0s - loss: 1.0580 - acc: 0.7404Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 3s 413us/step - loss: 1.0636 - acc: 0.7395 - val_loss: 1.1357 - val_acc: 0.7186
Out[46]:
<keras.callbacks.History at 0x7fe243a63be0>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [24]:
### Load the model weights with the best validation loss.
model.load_weights('dogvgg16.weights.best.hdf5')

(IMPLEMENTATION) Test the Model

Try out the model on the test dataset of dog images.

In [25]:
### Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
predictions = [np.argmax(model.predict(np.expand_dims(feature, axis=0))) 
                     for feature in test_]

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

(IMPLEMENTATION) Predict Dog Breed with the Model

In the next step, I write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, the function has three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to the chosen CNN architecture, I need to use the function

extract_{network}

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

In [26]:
### Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
In [32]:
def predict_breed(path):
    """Function that takes an image path as input and returns the dog breed
    Input
        Path: String, path where the picture is.
    Output
        Dog: String, dog breed predicted by the model.
    """

    ## Extract the bottleneck features corresponding to the chosen CNN model.
    from keras.preprocessing import image 
    img = image.load_img(path, target_size=(224,224))
    img
    tensor = image.img_to_array(img)
    tensor = np.expand_dims(tensor,axis=0) # extract_VGG19 is expectio a 1x M x N x O shape, add the 1 dimension.
    #tensor.shape
    botlNeck = extract_VGG19(tensor)

    ## Supply the bottleneck features as input to the model to return the predicted vector. 

    botlNeck = np.add.reduce(botlNeck, 0)
    index = np.argmax(model.predict(np.expand_dims(botlNeck,axis=0)))

    ## Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.
    dog = dog_names[index]
    
    return dog
In [33]:
### Function to direct image type and response
def dog_or_human(path):
    dog = dog_detector(path)
    human = face_detector(path)
    if ((dog == True) & (human == True)):
        response = "Dog-human chimera! " + predict_breed(path)
    elif ((dog == True) & (human == False)):
        response = "Dog! " + predict_breed(path)
    elif ((dog == False) & (human == True)):
        response = "Human! " + predict_breed(path)
    else:# ((dog == False) & (human == False)):
        response = ":-| the picture is neither a person nor a dog -- or else extremely strange looking ones"
        
    return response
In [40]:
dog_or_human('dogImages/train/095.Kuvasz/Kuvasz_06442.jpg')
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5
80142336/80134624 [==============================] - 1s 0us/step
Out[40]:
'Dog-human chimera! Kuvasz'

Step 7: Test Your Algorithm

This is the results section. Here, I test whether my algorithm predicts a given dog's breed accurately, and funny enough, a person's dog breed as well.

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

In [57]:
photos = ["queen-elizabeth","salchicha_puppy","salchichas_2","salchicha_negro","Kangaroo","whale","Castro","May","Irish-Terrier-1", "Kromfohrlander-1","Cesky-Terrier-1","Austrian-Pinscher-1","Yellen","Merkel","Welsh_springer_spaniel_08203","Labrador_retriever_06449","Labrador_retriever_06455"]
for i in photos:
    who = i
    print(dog_or_human("images/"+ who +".jpg"))
    ima = cv2.cvtColor(cv2.imread("images/" + who + ".jpg"), cv2.COLOR_BGR2RGB)    
    plt.imshow(ima)
    plt.show()
Human! Parson_russell_terrier
Dog! Dachshund
Dog! Dachshund
Dog! Dachshund
:-| the picture is neither a person nor a dog -- or else extremely strange looking ones
:-| the picture is neither a person nor a dog -- or else extremely strange looking ones
Human! Norwich_terrier
Human! Nova_scotia_duck_tolling_retriever
Dog! Irish_terrier
Dog! Australian_shepherd
Dog! Giant_schnauzer
Dog! Dachshund
Human! Silky_terrier
Human! Silky_terrier
Dog! Irish_red_and_white_setter
Dog! Labrador_retriever
Dog! Chesapeake_bay_retriever