Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App

In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.

Why We're Here

In this notebook, you will make 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, your 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 your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you 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. Your imperfect solution will nonetheless create a fun user experience!

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('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
# changed these lines, so that I can later use the random seed again
RS = 8675309

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

# 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
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
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: Use the code cell below to 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.


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.

Helper Functions

I am writing some helper functions for this task, since I will use them again later.

In [6]:
from mpl_toolkits.axes_grid1 import ImageGrid
from keras.preprocessing import image as keras_image_preprocess

## My functions are very general, since I want to reuse them later on

# Some helper functions 
# ------------------------------------------------------------------------

# returns the image as a numpy array
def read_img(filepath, size):
    img = keras_image_preprocess.load_img(filepath, target_size=size)
    array = keras_image_preprocess.img_to_array(img)
    return array

# shows images from list both as filepathes and as images in a grid
def show_image_grid(img_pathes):
    image_count = len(img_pathes)
    cols = min(image_count, 4) # nr of images in one row
    rows = (image_count // 4) + 1 # nr of rows
    fig_width = cols * 2
    fig_height = rows * 2
    fig = plt.figure(1, (fig_width, fig_height))
    grid = ImageGrid(fig, 111, # similar to subplot(111)
                    nrows_ncols = (rows, cols), # creates grid
                    axes_pad=0.1, # pad between axes in inch.

    for i in range(image_count):
        im = read_img(img_pathes[i], (224, 224))
        grid[i].imshow(im / 255.) # show image in grid element 

# Determines the accuracy on a list of images given by their pathes: 
# ------------------------------------------------------------------------
# Parameters:
# - title: the title to print out 
# - img_path_list: a list of image file pathes 
# - detector: a detector function, that takes the image path and returns a predicted value
# - groundtruth: List of groundtruth values for the image paths
# - show_fails: show incorrectly classified images in a grid
# Result:
# - has no output, but prints the accuracy and the images, that have been misclassified in a grid
def get_detector_accurancy(title, img_path_list, detector, ground_truth, show_fails=True):
    """the detector accuracy is determined, also the images that have been incorrectly classified 
    are remebered"""   
    detected = np.array([detector(img_path) for img_path in img_path_list])
    ground_truth = np.array(ground_truth)
    accuracy = 100*np.sum(detected==ground_truth)/len(detected)
    incorrect = img_path_list[np.where(detected!=ground_truth)]
    print("{} were classified with an accuracy of {} %\n".format(title, accuracy))
    # show incorrectly classified images in a grid
    if show_fails and len(incorrect) > 0:
        print("Incorrectly classified:", incorrect) 
In [7]:
                       ground_truth=[True for img_path in human_files_short])
Humans were classified with an accuracy of 98.0 %

Incorrectly classified: ['lfw/Muhammad_Ali/Muhammad_Ali_0001.jpg'
In [8]:
                       ground_truth=[False for img_path in dog_files_short])
Dogs were classified with an accuracy of 89.0 %

Incorrectly classified: ['dogImages/train/095.Kuvasz/Kuvasz_06442.jpg'

Answer to Question1

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

98 % of the first 100 images in human_files had a human face detected.

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

11.0 % of the first 100 images in dog_files had a human face detected.

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?


We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [9]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

Answer to Question2: Assess human face detector

Flaws of the face detector

The Human Face detecto:

  • does not detect faces, that do not show a frontal face.
  • it detects the faces for dogs as well

Are Haar cascades for face detection are an appropriate technique for human detection?

  • No, I don't think they are. The can point to were they suspect a face, but I think the measurements are not flexible enough to pick up on different head positions. Also they might take animal heads for humans if the proportions are similar. This seems to be the case for dogs.

My own your own face detection algorithm

Transfer Learning for Human Dog Detection

I decided to try Transfer Learning for Human Detection


I just used the data, that was already there: human_files for humans and dog_files for dogs


My idea was to explore the bottleneck features od ResNet50 for this task. For the dogs the bottleneck feature were already given. I just had to produce them for the humans.


I usually try to visualize how good the features are for the task at hand by looking at a TSNE projection whenever that is possible.

Categorical Crossentropy

I was aiming for Categorical Entrophy rather then Binary Classification since I was hoping to detect, that an image was neither human nor a dog would be detectable by the propabilities for both classes being undecisive. That hpe turned out to be false though.

Human Dog Detector

It turned out that my detector has a bias towards dogs: everything not human was classified as dog. That made it actually useful in detecting humans.


You find my Implementation in the cells below. Whenever possible I try locally to get the data from files, in order to make the notebook faster to run through. It is not possible to store the file on github though.

Run Options

Since computing the HumanDetector is time expensive, I stored the results in files and give the option to recompute them with the variable RECOMPUTE_HUMAN_DOG_DETECTOR_MODEL, which is preset to False, but can be changed to True.

My Human Dog Detector

Human Dog Detector Step 1:

  • Loading the human images from human_files
  • stacking the dog_images all to one dog_file

Only recomputed on request

  • the computation of my model was time intense, therefore it is only recomputed on request: if you set RECOMPUTE_HUMAN_DOG_DETECTOR_MODELto True. I initially thought of storing the intermediated tensors, but this hit a storage limit in github. Therefore I chose this solution.
In [10]:
In [11]:
# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    human_files = np.array(data['filenames'])
    return human_files

    # load train, test, and validation datasets
    human_files = load_dataset('lfw')
    dog_files = np.hstack([train_files, valid_files, test_files])

    # print statistics about the dataset
    print('There are %s total human images.\n' % len(np.hstack([human_files])))
    print('There are %s total dog images.\n' % len(np.hstack([dog_files])))

Human Dog Detector Step 2: getting bottleneck features for the human_images

  • this is also needed for the prediction later on, so also in the case that the model is not recomputed.
In [12]:
from keras.applications.resnet50 import preprocess_input as resnet50_preprocess_input
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image

# the model is only defined once with top of since we want the features just before the imagenet classes are received.
model_resnet50 = ResNet50(include_top=False, weights='imagenet')

# computing the features by making a forward pass through resnet50 from keras
def get_resnet50_features(img_path):
    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
    x = np.expand_dims(x, axis=0)
    # get the feature by a forward pass through the model
    features = model_resnet50.predict(resnet50_preprocess_input(x))
    return features

Compute the human tensors

  • locally I stored them to a file, so that I had to compute them ony once. But the file turned out to be to big for Github.
In [13]:
# since this computationaly expensive I try to get the tensors from file if possible
        human_tensors = np.load('myfiles/HumanDogDetector/human_resnet50_tensors.npy')
    except FileNotFoundError:
        # initialize array
        human_tensors = np.zeros((human_files.shape[0], 2048))
        # compute features from pretrained resnet50
        for i in tqdm(range(human_tensors.shape[0])):
            human_tensors[i] = get_resnet50_features(human_files[i])
        # saving the bottleneckfeatures for later'myfiles/HumanDogDetector/human_resnet50_tensors', human_tensors) 
        print("Computed {} human tensors of shape {} and saved them to a file.".format(
            len(human_tensors), human_tensors.shape))
        print("Loaded {} human tensors of shape {} from file".format(len(human_tensors), human_tensors.shape))   

Human Dog Detector Step 3: getting bottleneck features for the dog_images

These features have been given to us, so that I can just load them from the given files

  • I stack test, train and validation data all together, since I have to shuffle and split the data again later anyway.
In [14]:
### Obtain bottleneck features from ResNet50 and squeeze them
    bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
    dog_tensors = np.vstack([bottleneck_features['train'], bottleneck_features['valid'], bottleneck_features['test']])
    dog_tensors = np.squeeze(dog_tensors)
    print("There are {} dog tensors of shape {}".format(len(dog_tensors), dog_tensors.shape))

Human Detector Step 4: Mixing the datasets and targets

  • stacking everything together: tensors and targets
  • one hot encoding of both classes humans and dogs
In [15]:
    ### Obtain bottleneck features from ResNet50 and squeeze them
    nr_classes = 2
    # one hot encoding humen classes
    human_targets = np.hstack([np.zeros((human_tensors.shape[0],1)), np.ones((human_tensors.shape[0],1))])
    print("Human targets are now of shape", human_targets.shape)
    print("Human targets look like", human_targets[0])
    # one hot encoding dog classes
    dog_targets = np.hstack([np.ones((dog_tensors.shape[0],1)), np.zeros((dog_tensors.shape[0],1))])
    print("Dog targets are now of shape", dog_targets.shape)
    print("Dog targets look like", dog_targets[0])
    # stacking tensors and targets together
    dh_tensors = np.vstack([dog_tensors, human_tensors])
    dh_targets = np.vstack([dog_targets, human_targets])
    print("Tensors have now shape", dh_tensors.shape)
    print("Targets have now shape", dh_targets.shape)
    print("""if run with RECOMPUTE_HUMAN_DOG_DETECTOR_MODEL, this cell produces the following output:
    Human targets are now of shape (13233, 2)
    Human targets look like [ 0.  1.]
    Dog targets are now of shape (8351, 2)
    Dog targets look like [ 1.  0.]
    Tensors have now shape (21584, 2048)
    Targets have now shape (21584, 2)""")
if run with RECOMPUTE_HUMAN_DOG_DETECTOR_MODEL, this cell produces the following output:
    Human targets are now of shape (13233, 2)
    Human targets look like [ 0.  1.]
    Dog targets are now of shape (8351, 2)
    Dog targets look like [ 1.  0.]
    Tensors have now shape (21584, 2048)
    Targets have now shape (21584, 2)

Human Dog Detector Step 5: Mixing the datasets and targets

  • shuffling the features and targets so that the humans and dogs get mixed
In [16]:
    # shuffle the datasets with Shuffle Split
    from sklearn.model_selection import ShuffleSplit

    splitter_train = ShuffleSplit(n_splits=1, test_size=0.2, random_state=0)
    splitter_train.get_n_splits(dh_tensors, dh_targets)

    # get split indexes
    dh_train_index, dh_test_index = next(splitter_train.split(dh_tensors, dh_targets))
    val_split = int(len(dh_test_index) / 2)
    dh_val_index = dh_test_index[:val_split]
    dh_test_index = dh_test_index[val_split:]

    x_dh_train, y_dh_train = dh_tensors[dh_train_index], dh_targets[dh_train_index]
    x_dh_test, y_dh_test = dh_tensors[dh_test_index], dh_targets[dh_test_index]
    x_dh_val, y_dh_val = dh_tensors[dh_val_index], dh_targets[dh_val_index]

    print("The shapes of train, validation and test tensors and targets are now:\nTensors: {}, {}, {}\nTargets: {}{}, {}"
          .format(x_dh_train.shape, x_dh_val.shape, x_dh_test.shape, y_dh_train.shape, y_dh_val.shape, y_dh_test.shape))
    print("""if run with RECOMPUTE_HUMAN_DOG_DETECTOR_MODEL, this cell produces the following output:
    The shapes of train, validation and test tensors and targets are now:
    Tensors: (17267, 2048), (2158, 2048), (2159, 2048)
    Targets: (17267, 2), (2158, 2), (2159, 2)""")
if run with RECOMPUTE_HUMAN_DOG_DETECTOR_MODEL, this cell produces the following output:
    The shapes of train, validation and test tensors and targets are now:
    Tensors: (17267, 2048), (2158, 2048), (2159, 2048)
    Targets: (17267, 2), (2158, 2), (2159, 2)

Human Dog Detector Step 6: Visualizing the features with TSNE

  • can the features set dogs and humans apart?
  • do they look promising? I am using the Validation set for this, just because it is smaller then the training dataset and I am just interested in a visualization of the features on a mixed dataset.
In [17]:
# applying TSNE algorithm 
from sklearn.manifold import TSNE

def perform_tsne(X):
    proj = TSNE(random_state=RS, verbose=1).fit_transform(X)
    return proj
In [18]:
    # preforming TSNE: this just projects distances of features, so the targets are not necessary
    filepath = 'myfiles/tsnedata/HumanDogResNet50TSNEData'
        proj_val = np.load(filepath + '.npy')
    except FileNotFoundError:
        proj_val = perform_tsne(x_dh_val), proj_val)
        print('TSNE projection computed and saved to file.')
        print('TSNE projection loaded from file.')
    print("""if run with RECOMPUTE_HUMAN_DOG_DETECTOR_MODEL, this cell produces the following output:
    TSNE projection loaded.""")
if run with RECOMPUTE_HUMAN_DOG_DETECTOR_MODEL, this cell produces the following output:
    TSNE projection loaded.

Helper functions

The plotting of the TSNE map is very general, since I will use it again later for the dog breeds.

  • I am getting the palette from file in case seaborn is not installed
In [19]:
# getting the palette for the colors from either seaborn or from file
    import seaborn as sns
    palette = np.array(sns.color_palette("hls", 25))
    np.random.shuffle(palette)'myfiles/palette/palette', palette)
except ImportError:
    palette = np.load('myfiles/palette/palette.npy')
In [20]:
# helper function for the tsne plot
import matplotlib.patches as mpatches

# scatter plotting the tsne data
# parameters:
# - x: the data is supposed to be 2 dimensional
# - colors: the target as color codes, the codes should be a range(n) for any integer n < 25: 0,1,2,3,..
# - title: the title of the plot
# - other_color: is there an 'other' class that should be kept in light grey?
# - filename: filename to store the plot
# Output:
# - the plot is displayed and gets saved to file
def scatter(x, colors, legend, title, file_path, other_color=None):
    """this function plots the result
    - x is a two dimensional vector
    - colors is a code that tells how to color them: it corresponds to the target
    - legend is a dictionary that tells what color means what label
    # We choose a color palette with seaborn.
    class_count = len(legend)
    palette_length = class_count
    if other_color:
        palette_length -= 1

    # seaborn
        palette = np.array(sns.color_palette("hls", palette_length))       
        palette = np.load('myfiles/palette/palette.npy')

    palette = palette[:palette_length]
    if other_color:
        other_color = np.array([0.9, 0.9, 0.9])
        palette = np.vstack([palette, other_color])  

    # We create a scatter plot.
    f = plt.figure(figsize=(10, 8))
    ax = plt.subplot(aspect='equal')
    sc = ax.scatter(x[:,0], x[:,1], lw=0, s=40, c=palette[colors.astype(])

    ax.axis('off') # the axis will not be shown
    ax.axis('tight') # makes sure all data is shown

    # set title
    plt.title(title, fontsize=25)

    # legend with color patches
    patches = []
    for i in range(class_count):
       patch = mpatches.Patch(color=palette[i], label=legend[i])
    plt.legend(handles=patches, fontsize=10, loc=4)
In [21]:
# helper function to display and image that is stored in a file
from IPython.display import Image, display
import matplotlib.image as mpimg

# just fetch an image form file and show it
def show_image(img_path):
    img = mpimg.imread(img_path)
    imgplot = plt.imshow(img)  
# show image in the original size
def show_image_original(img_path):
In [22]:
# plot TSNE projection
file_path = 'myfiles/tsneplots/HumanDogResNet50TSNE.png'
    # Now we call the scatter plot function on our data
    legend = {0:'Dogs', 1: 'Humans'}
    colors = y_dh_val[:, 1]
    scatter(proj_val, colors, legend, title="Resnet Transfer Learning: Humans Dogs", file_path=file_path)