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

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!
Steps in the notebook. Feel free to use the links below to navigate the notebook.
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 imagestrain_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels dog_names - list of string-valued dog breed names for translating labelsfrom 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))
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("lfw/*/*"))
random.shuffle(human_files)
print('There are %d total human images.' % len(human_files))
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.
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()
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.
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):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
return len(faces) > 0
Question 1: Test the performance of the face_detector function.
human_files have a detected human face? 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:
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
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)
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")
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.
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')
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!
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)
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))
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).
### 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))
Question 3: Test the performance of the dog_detector function.
human_files_short have a detected dog? dog_files_short have a detected dog?Answer:
### 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)
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")
humans_as_dogs = loop(human_files, dog_detector)
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")
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.
We rescale the images by dividing every pixel in every image by 255.
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
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.
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()
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
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)
model.load_weights('saved_models/weights.best.from_scratch.hdf5')
Try out the model on the test dataset of dog images.
# 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)
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']
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.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))
# Summarize the layers of the model
VGG16_model.summary()
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()
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
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)
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')
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)
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)]
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.
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']
!wget -P dog-project/bottleneck-features https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/DogVGG19Data.npz
### 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']
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.
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)
# 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)
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()
### Compile the model.
model.compile(loss='categorical_crossentropy', optimizer='rmsprop',
metrics=['accuracy'])
### 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)
### Load the model weights with the best validation loss.
model.load_weights('dogvgg16.weights.best.hdf5')
Try out the model on the test dataset of dog images.
### 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)
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:
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.
### Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
def predict_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
### 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
dog_or_human('dogImages/train/095.Kuvasz/Kuvasz_06442.jpg')
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()