In this project, a Convolutional Neural Network will be used to identify the dog breed in images containing a single dog. If the image of a human is supplied, the dog breed closest to the human is returned. All other images are ignored. Here is the code for this project which was a part of Udacity’s Deep Learning Nanodegree.

## 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
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
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

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

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

# print(dog_names)

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.

import random
random.seed(8675309)

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

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

There are 13233 total human images.


## Step 1: Detect Humans

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

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

import cv2
import matplotlib.pyplot as plt
%matplotlib inline

# extract pre-trained face detector

# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image

# 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,255,0),2)

# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()

Number of faces detected: 1


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

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

### 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.

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


### Assess the Human Face Detector

Looking at the output below,

• 100% of the first 100 images in human_files have a detected human face
• 11% of the first 100 images in dog_files have a detected human face
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.

# Sum is the % since we're considering just 100 files of each
num_humans_in_human_files_short = sum(1 for file in human_files_short if face_detector(file))
num_humans_in_dog_files_short = sum(1 for file in dog_files_short if face_detector(file))
print(num_humans_in_human_files_short, num_humans_in_dog_files_short)


100 11


Since the face detector above is not 100% accurate, the app will accept human images only when they have a clear view of the face. Depending on the application, this might be a reasonable restriction of the app.

However, this can be avoided by training the neural network with more auto generated images that are slightly rotated, translated etc. Providing original training images with faces that are not clearly presented should produce even better results.

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

from os import listdir

import urllib
import urllib.request


['haarcascade_frontalface_alt.xml']

def face_detector2(img_path):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return len(faces) > 0

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

# Sum is the % since we're considering just 100 files of each
num_humans_in_human_files_short = sum(1 for file in human_files_short if face_detector2(file))
num_humans_in_dog_files_short = sum(1 for file in dog_files_short if face_detector2(file))
print(num_humans_in_human_files_short, num_humans_in_dog_files_short)

100 20


Another OpenCV algorithm produces worse results as can be seen above -

• 100% of the first 100 images in human_files have a detected human face
• 20% of the first 100 images in dog_files have a detected human face

## 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.

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 [==============================] - 3s 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

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

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

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

from keras.preprocessing import image
from tqdm import tqdm

def path_to_tensor(img_path):
# loads RGB image as PIL.Image.Image type
# 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.

from keras.applications.resnet50 import preprocess_input, decode_predictions

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


### Write a Dog Detector

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

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

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


### Assess the Dog Detector

Testing the performance of the dog_detector function below,

• 0% of the images in human_files_short have a detected dog
• 100% of the images in dog_files_short have a detected dog
### TODO: 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]

# Sum is the % since we're considering just 100 files of each
num_dogs_in_human_files_short = sum([1 for file in human_files_short if dog_detector(file)])
num_dogs_in_dog_files_short = sum([1 for file in dog_files_short if dog_detector(file)])
print(num_dogs_in_human_files_short, num_dogs_in_dog_files_short)

0 100


## 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, you will create a CNN from scratch that classifies dog breeds.

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

### Pre-process the Data

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

from PIL import ImageFile

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255

100%|██████████| 6680/6680 [01:26<00:00, 48.99it/s]
100%|██████████| 835/835 [00:09<00:00, 85.09it/s]
100%|██████████| 836/836 [00:09<00:00, 84.99it/s]


### Model Architecture

I started off with the hinted architecture with a kernel_size of (7,7) and got a validation accuracy of < 0.02 after three epochs. I then reduced the kernel_size to reduce the total parameters to prevent over-fitting and could improve the validation accuracy to > 0.02.

To try a different approach to prevent overfitting, I added two hidden dropout layers with a rate of 0.5 and went back to a kernel_size of (7,7). This still had a validation accuracy of around 0.02 after 3 epochs so I changed my kernel_size to (5,5) and reduced my dropout rate to 0.3 to reduce the number of units dropped and retain more information but decrease the number of total parameters. After five epochs, the validation accuracy was still on the rise, so I changed the number of epochs to 10 and was able to achieve a validation accuracy of ~ 0.065.

In the end, the test accuracy was 8.7%.

This architecture works because the series of convolution layers and max pooling layers learns simple to complex patterns as the network gets deeper. The convolution layers help capture spatial information while the max pooling layers help reduce the dimensions and number of parameters to be trained. The dropout layers help with overfitting by randomly dropping some of the nodes in the network during training. The global average pooling layer reduces the dimensions drastically and converts the 3D array into a vector before the final fully connected layer is used to produce the output.

from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

rows, columns, channels = 224, 224, 3
num_breeds = 133
kernel_size = (5,5)

model = Sequential()

model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_37 (Conv2D)           (None, 224, 224, 16)      1216
_________________________________________________________________
max_pooling2d_38 (MaxPooling (None, 112, 112, 16)      0
_________________________________________________________________
conv2d_38 (Conv2D)           (None, 112, 112, 32)      12832
_________________________________________________________________
dropout_8 (Dropout)          (None, 112, 112, 32)      0
_________________________________________________________________
max_pooling2d_39 (MaxPooling (None, 56, 56, 32)        0
_________________________________________________________________
conv2d_39 (Conv2D)           (None, 56, 56, 64)        51264
_________________________________________________________________
dropout_9 (Dropout)          (None, 56, 56, 64)        0
_________________________________________________________________
max_pooling2d_40 (MaxPooling (None, 28, 28, 64)        0
_________________________________________________________________
global_average_pooling2d_9 ( (None, 64)                0
_________________________________________________________________
dense_13 (Dense)             (None, 133)               8645
=================================================================
Total params: 73,957
Trainable params: 73,957
Non-trainable params: 0
_________________________________________________________________


### Compile the Model

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


### Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

from keras.callbacks import ModelCheckpoint

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

epochs = 10

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

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

model.fit(train_tensors, train_targets,
validation_data=(valid_tensors, valid_targets),
epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)

Train on 6680 samples, validate on 835 samples
Epoch 1/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6482 - acc: 0.0368Epoch 00001: val_loss improved from inf to 4.67439, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 4.6481 - acc: 0.0367 - val_loss: 4.6744 - val_acc: 0.0359
Epoch 2/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.5750 - acc: 0.0440Epoch 00002: val_loss improved from 4.67439 to 4.66203, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 4.5748 - acc: 0.0440 - val_loss: 4.6620 - val_acc: 0.0491
Epoch 3/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.5041 - acc: 0.0535Epoch 00003: val_loss improved from 4.66203 to 4.56691, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 4.5027 - acc: 0.0534 - val_loss: 4.5669 - val_acc: 0.0467
Epoch 4/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.4130 - acc: 0.0587Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 28s 4ms/step - loss: 4.4136 - acc: 0.0587 - val_loss: 4.5696 - val_acc: 0.0599
Epoch 5/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.3432 - acc: 0.0614Epoch 00005: val_loss improved from 4.56691 to 4.52009, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 4.3441 - acc: 0.0612 - val_loss: 4.5201 - val_acc: 0.0467
Epoch 6/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.2820 - acc: 0.0670Epoch 00006: val_loss improved from 4.52009 to 4.51935, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 4.2825 - acc: 0.0671 - val_loss: 4.5194 - val_acc: 0.0467
Epoch 7/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.2143 - acc: 0.0797Epoch 00007: val_loss improved from 4.51935 to 4.39414, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 4.2142 - acc: 0.0798 - val_loss: 4.3941 - val_acc: 0.0695
Epoch 8/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.1677 - acc: 0.0784Epoch 00008: val_loss improved from 4.39414 to 4.33589, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 4.1667 - acc: 0.0784 - val_loss: 4.3359 - val_acc: 0.0623
Epoch 9/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.1144 - acc: 0.0839Epoch 00009: val_loss improved from 4.33589 to 4.29221, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 4.1142 - acc: 0.0843 - val_loss: 4.2922 - val_acc: 0.0683
Epoch 10/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.0655 - acc: 0.0973Epoch 00010: val_loss improved from 4.29221 to 4.26527, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 28s 4ms/step - loss: 4.0657 - acc: 0.0970 - val_loss: 4.2653 - val_acc: 0.0647

<keras.callbacks.History at 0x7f9ff0ac29b0>


### Load the Model with the Best Validation Loss

model.load_weights('saved_models/weights.best.from_scratch.hdf5')


### Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

# 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: 8.7321%


## Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

### Obtain Bottleneck Features

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


### Model Architecture

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

VGG16_model = Sequential()

VGG16_model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
global_average_pooling2d_10  (None, 512)               0
_________________________________________________________________
dense_14 (Dense)             (None, 133)               68229
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________


### Compile the Model

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


### Train the Model

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
6480/6680 [============================>.] - ETA: 0s - loss: 12.6275 - acc: 0.1111Epoch 00001: val_loss improved from inf to 11.22334, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 360us/step - loss: 12.5899 - acc: 0.1145 - val_loss: 11.2233 - val_acc: 0.2048
Epoch 2/20
6460/6680 [============================>.] - ETA: 0s - loss: 10.8013 - acc: 0.2593Epoch 00002: val_loss improved from 11.22334 to 10.87642, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 268us/step - loss: 10.7908 - acc: 0.2602 - val_loss: 10.8764 - val_acc: 0.2455
Epoch 3/20
6500/6680 [============================>.] - ETA: 0s - loss: 10.5135 - acc: 0.3048Epoch 00003: val_loss improved from 10.87642 to 10.69533, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 265us/step - loss: 10.4921 - acc: 0.3051 - val_loss: 10.6953 - val_acc: 0.2599
Epoch 4/20
6620/6680 [============================>.] - ETA: 0s - loss: 10.2809 - acc: 0.3299Epoch 00004: val_loss improved from 10.69533 to 10.59777, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 257us/step - loss: 10.2833 - acc: 0.3298 - val_loss: 10.5978 - val_acc: 0.2814
Epoch 5/20
6620/6680 [============================>.] - ETA: 0s - loss: 10.1360 - acc: 0.3438Epoch 00005: val_loss improved from 10.59777 to 10.48877, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 257us/step - loss: 10.1205 - acc: 0.3443 - val_loss: 10.4888 - val_acc: 0.2838
Epoch 6/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.8834 - acc: 0.3588Epoch 00006: val_loss improved from 10.48877 to 10.13822, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 257us/step - loss: 9.8822 - acc: 0.3590 - val_loss: 10.1382 - val_acc: 0.3006
Epoch 7/20
6580/6680 [============================>.] - ETA: 0s - loss: 9.7097 - acc: 0.3771Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s 256us/step - loss: 9.7057 - acc: 0.3771 - val_loss: 10.1695 - val_acc: 0.3162
Epoch 8/20
6640/6680 [============================>.] - ETA: 0s - loss: 9.5936 - acc: 0.3875Epoch 00008: val_loss improved from 10.13822 to 9.97016, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 255us/step - loss: 9.5870 - acc: 0.3879 - val_loss: 9.9702 - val_acc: 0.3138
Epoch 9/20
6660/6680 [============================>.] - ETA: 0s - loss: 9.3743 - acc: 0.3986Epoch 00009: val_loss improved from 9.97016 to 9.77749, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 255us/step - loss: 9.3764 - acc: 0.3985 - val_loss: 9.7775 - val_acc: 0.3317
Epoch 10/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.1844 - acc: 0.4062Epoch 00010: val_loss improved from 9.77749 to 9.74378, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 256us/step - loss: 9.1671 - acc: 0.4072 - val_loss: 9.7438 - val_acc: 0.3234
Epoch 11/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.9883 - acc: 0.4215Epoch 00011: val_loss improved from 9.74378 to 9.54629, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 258us/step - loss: 8.9902 - acc: 0.4210 - val_loss: 9.5463 - val_acc: 0.3437
Epoch 12/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.8943 - acc: 0.4312Epoch 00012: val_loss improved from 9.54629 to 9.46986, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 257us/step - loss: 8.8966 - acc: 0.4308 - val_loss: 9.4699 - val_acc: 0.3353
Epoch 13/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.8024 - acc: 0.4369Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 256us/step - loss: 8.7847 - acc: 0.4380 - val_loss: 9.4918 - val_acc: 0.3401
Epoch 14/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.7477 - acc: 0.4467Epoch 00014: val_loss improved from 9.46986 to 9.27337, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 257us/step - loss: 8.7390 - acc: 0.4473 - val_loss: 9.2734 - val_acc: 0.3641
Epoch 15/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.7235 - acc: 0.4502Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 254us/step - loss: 8.7247 - acc: 0.4500 - val_loss: 9.2828 - val_acc: 0.3665
Epoch 16/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.6543 - acc: 0.4548Epoch 00016: val_loss improved from 9.27337 to 9.14751, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 256us/step - loss: 8.6460 - acc: 0.4554 - val_loss: 9.1475 - val_acc: 0.3844
Epoch 17/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.4899 - acc: 0.4647Epoch 00017: val_loss improved from 9.14751 to 9.08938, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 257us/step - loss: 8.5168 - acc: 0.4629 - val_loss: 9.0894 - val_acc: 0.3701
Epoch 18/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.4565 - acc: 0.4679Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s 256us/step - loss: 8.4480 - acc: 0.4686 - val_loss: 9.1478 - val_acc: 0.3808
Epoch 19/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.3423 - acc: 0.4727Epoch 00019: val_loss improved from 9.08938 to 8.98412, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 256us/step - loss: 8.3406 - acc: 0.4729 - val_loss: 8.9841 - val_acc: 0.3832
Epoch 20/20
6640/6680 [============================>.] - ETA: 0s - loss: 8.2151 - acc: 0.4804Epoch 00020: val_loss improved from 8.98412 to 8.84610, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 256us/step - loss: 8.2270 - acc: 0.4796 - val_loss: 8.8461 - val_acc: 0.3844

<keras.callbacks.History at 0x7f9ff0b03c50>


### Load the Model with the Best Validation Loss

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.

# 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: 39.9522%


### Predict Dog Breed with the Model

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)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras. These are already in the workspace, at /data/bottleneck_features. If you wish to download them on a different machine, they can be found at:

The files are encoded as such:

Dog{network}Data.npz


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

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

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

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

### Obtain Bottleneck Features

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

bottleneck_features = np.load('/data/bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']

import numpy as np

### TODO: Obtain bottleneck features from another pre-trained CNN.
train_resnet = bottleneck_features['train']
valid_resnet = bottleneck_features['valid']
test_resnet = bottleneck_features['test']


### Model Architecture

Just like the previous example, I used a pre-trained model (Resnet50) and used the last layer as the input to a Global average pooling layer to reduce the dimenstions. I then fed this to a fully connected layer with 133 nodes - one for each category - for the output. I was happy with the 81% accuracy so didn’t tweak it further.

This architecture is suitable because we’re taking advantage of the information/patterns learned by the layers of the pre-trained model and training it further to learn what we want.

from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

resnet_model = Sequential()

resnet_model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
global_average_pooling2d_1 ( (None, 2048)              0
_________________________________________________________________
dense_1 (Dense)              (None, 133)               272517
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________


### Compile the Model

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


### Train the Model

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

resnet_model.fit(train_resnet, train_targets,
validation_data=(valid_resnet, valid_targets),
epochs=10, batch_size=20, callbacks=[checkpointer], verbose=1)

Train on 6680 samples, validate on 835 samples
Epoch 1/10
6640/6680 [============================>.] - ETA: 0s - loss: 1.6432 - acc: 0.5940Epoch 00001: val_loss improved from inf to 0.81957, saving model to saved_models/weights.best.resnet.hdf5
6680/6680 [==============================] - 2s 326us/step - loss: 1.6373 - acc: 0.5954 - val_loss: 0.8196 - val_acc: 0.7257
Epoch 2/10
6420/6680 [===========================>..] - ETA: 0s - loss: 0.4345 - acc: 0.8650Epoch 00002: val_loss improved from 0.81957 to 0.69938, saving model to saved_models/weights.best.resnet.hdf5
6680/6680 [==============================] - 2s 236us/step - loss: 0.4328 - acc: 0.8647 - val_loss: 0.6994 - val_acc: 0.7904
Epoch 3/10
6640/6680 [============================>.] - ETA: 0s - loss: 0.2627 - acc: 0.9136Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 2s 228us/step - loss: 0.2619 - acc: 0.9138 - val_loss: 0.7027 - val_acc: 0.7796
Epoch 4/10
6560/6680 [============================>.] - ETA: 0s - loss: 0.1715 - acc: 0.9473Epoch 00004: val_loss improved from 0.69938 to 0.66466, saving model to saved_models/weights.best.resnet.hdf5
6680/6680 [==============================] - 2s 230us/step - loss: 0.1716 - acc: 0.9473 - val_loss: 0.6647 - val_acc: 0.8012
Epoch 5/10
6540/6680 [============================>.] - ETA: 0s - loss: 0.1192 - acc: 0.9641Epoch 00005: val_loss improved from 0.66466 to 0.66143, saving model to saved_models/weights.best.resnet.hdf5
6680/6680 [==============================] - 2s 231us/step - loss: 0.1188 - acc: 0.9639 - val_loss: 0.6614 - val_acc: 0.8024
Epoch 6/10
6540/6680 [============================>.] - ETA: 0s - loss: 0.0842 - acc: 0.9746Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 2s 229us/step - loss: 0.0840 - acc: 0.9749 - val_loss: 0.6734 - val_acc: 0.8144
Epoch 7/10
6600/6680 [============================>.] - ETA: 0s - loss: 0.0630 - acc: 0.9829Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s 229us/step - loss: 0.0642 - acc: 0.9825 - val_loss: 0.7099 - val_acc: 0.8240
Epoch 8/10
6520/6680 [============================>.] - ETA: 0s - loss: 0.0458 - acc: 0.9887Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s 230us/step - loss: 0.0451 - acc: 0.9889 - val_loss: 0.7123 - val_acc: 0.8072
Epoch 9/10
6540/6680 [============================>.] - ETA: 0s - loss: 0.0348 - acc: 0.9902Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 228us/step - loss: 0.0352 - acc: 0.9901 - val_loss: 0.7720 - val_acc: 0.8084
Epoch 10/10
6540/6680 [============================>.] - ETA: 0s - loss: 0.0244 - acc: 0.9931Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 2s 229us/step - loss: 0.0265 - acc: 0.9928 - val_loss: 0.7822 - val_acc: 0.8228

<keras.callbacks.History at 0x7f9ff0836c50>


### Load the Model with the Best Validation Loss

### TODO: Load the model weights with the best validation loss.


### Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

### TODO: Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
resnet_predictions = [np.argmax(resnet_model.predict(np.expand_dims(feature, axis=0))) for feature in test_resnet]

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

Test accuracy: 81.2201%


### Predict Dog Breed with the Model

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, your function should have 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 your chosen CNN architecture, you need to use the function

extract_{network}


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

### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

from extract_bottleneck_features import *

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


## Step 6: Write your Algorithm

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

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

### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import cv2

def show_image(img_path):

# 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()

def dog_breed_classifier(img_path):

show_image(img_path)

if dog_detector(img_path):
print("This dog is likely a", resnet_predict_breed(img_path))
elif face_detector(img_path):
print("This human resembles a ", resnet_predict_breed(img_path))
else:
print("Error - this is neither a human nor a dog")



## Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog’s breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

### Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

The output was just as I expected - no trouble identifying dogs and humans but mixing up dog breeds that are very similar. The model correctly identified distinct dog breeds like the poodle but mixed up a pug with a bulldog and a husky with an Alaskan Malamute. This is expected as those breeds are very similar to each other.

Possible improvements:

1. Deeper models - Adding one more fully connected layer before the final output layer might produce more accurate results.
2. Tweak model architecture by adding other types of layers
3. More training data - more images of dog breeds that are similar to other dog breeds could help the model learn to differentiate these breeds better. Image augmentation by adding rotations/translations to the existing training images could also help with this.
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

import os
from os import listdir

def create_images_dir():
directory = 'test_images'
if not os.path.exists(directory):
os.makedirs(directory)

create_images_dir()

import urllib
import urllib.request

]

urllib.request.urlretrieve(url, "test_images/img" + str(i) + ".jpg")

print (listdir('test_images'))


['img3.jpg', 'dog1.jpg', 'img5.jpg', 'img4.jpg', 'img0.jpg', 'dog0.jpg', 'img1.jpg', 'img2.jpg', 'face0.jpg']

for img in listdir('test_images'):
dog_breed_classifier('test_images/' + img)


This dog is likely a Golden_retriever


This dog is likely a Bulldog


This dog is likely a Beauceron


This dog is likely a Alaskan_malamute


This dog is likely a Poodle


This dog is likely a Anatolian_shepherd_dog


This human resembles a  Silky_terrier


Error - this is neither a human nor a dog


This human resembles a  Silky_terrier


Tags:

Categories:

Updated: