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.
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!).
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!
We break the notebook into separate steps. 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 labels#!!! ME: Re-organized the initial setup steps
# Python 3.6
import os
#os.chdir(r"D:\data") # if notebook is in different dir than data and external modules
import sys
print ("\n Python version is:", sys.version_info, "\n")
from tensorflow.python.client import device_lib
print ("\n Local devices: \n")
print (device_lib.list_local_devices() )
#for this project need to use the standalone Keras pkg, not the one embedded in TF
import keras
print("\n Keras version:", keras.__version__) #keras is 2.1.3
print("\n Keras backend:", keras.backend.backend()) #tensorflow
import time
# In[]: ## Step 0: Import Datasets
from sklearn.datasets import load_files
from keras.utils import np_utils
import numpy as np
np.random.seed(111)
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 = keras.utils.to_categorical(np.array(data['target']), 133) #updated call
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')
#create the number of breeds - used in several places below
breeds_count = train_targets.shape[1]
# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]
# print statistics about the dataset
print ('\n')
print('There are %d total dog categories (breeds).' % 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))
# Not that many - 6,6k images in the train set
# 133 breeds in own folders
# _targets are simply the Y vars - one hot encoded for each breed
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[]: Import Human Dataset
import random
random.seed(111) #always shuffle the same way, can change later
# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)
# print statistics about the dataset
print('\n')
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 next code cell, we demonstrate how to use this detector to find human faces in a sample image.
# In[]: Step 1: Detect Humans
# OpenCV's implementation of Haar feature-based cascade classifiers - Open Source Computer Vision
# from xml - Stump-based 20x20 gentle adaboost frontal face detector
# the best idea is the Cascade of Classifiers - Viola-Jones process
# check features in stages - starts by checking if an image window might be a face
# "C:\ProgramData\Anaconda3\Scripts\pip.exe" install opencv-python
import cv2
print("CV - Computer Vision version:", cv2.__version__ ) #OK
import matplotlib.pyplot as plt
%matplotlib inline
# extract pre-trained face detector - had to use my own and got plenty others now too
#face_cascade = cv2.CascadeClassifier('D:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_alt.xml')
#face_cascade = cv2.CascadeClassifier('C:\\Users\\rf\\Google Drive\\Education\\Python\\Codes\\ML_nano\\p4_cnn\\haarcascades\\haarcascade_frontalface_alt.xml')
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
# load color (BGR) image - one sample - morpheus
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print ('\n Will process grayscale image:')
plt.imshow(gray)
plt.show()
#more greenish that gray though
# find faces in image, execute the canned algorithm
faces = face_cascade.detectMultiScale(gray)
#coordinates of each detected face: x,y - top left corner, w,h are distances
# print number of faces detected in the image
print('\n 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()
#OK
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.
# In[]: Write a Human Face Detector
# simple detector if any face found - 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: Use the code cell below to 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:
See answer 1 below
# In[]: (IMPLEMENTATION) Assess the Human Face Detector
# Question 1: just how good is the algorithm in haarcascade_frontalface_alt.xml ?
# Can quickly assess by using face_detector fn on small samples
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.
# Answer 1
#just a simple loop?
results_h = []
for i in range(len(human_files_short)):
results_h.append(face_detector(human_files_short[i]))
print('Percentage of images from the human dataset with detected human faces:', sum(results_h)/len(results_h)*100)
results_d = []
for i in range(len(dog_files_short)):
results_d.append(face_detector(dog_files_short[i]))
print('Percentage of images from the dog dataset with detected human faces:', sum(results_d)/len(results_d)*100)
# or to get fancy could vectorize the fn to avoid looping - np.vectorize(face_detector)
Answer 1:
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 2:
Yes, I think it is totally reasonable to ask users to upload photos with a clear view of a face for the algorithm to test. I think of this as a "house-rule" requirement. Of course, it would be great for our algorithm to be both versatile and accurate but we also need to be realistic and practical.
For example, a profile photo is meant be clear and easily identifiable. I would train the algorithm just on good photos first and then ask users to upload good photos of their own. If they don't and the algorithm fails to detect a face, I would ask the users to upload a better photo.
For non-critical applications this Haar cascades algorithm will, probably, be sufficient.
That said, I can imagine other applications where we might not be able to obtain better photos and the algorithm still needs to be more versatile to detect faces even from bad photos.
ME: course text below
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 this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.
# In[]: Step 2: Detect Dogs
# using a canned model to score images - ResNet-50 (a huge CNN trained on tons of images)
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from tqdm import tqdm
from keras.applications.resnet50 import preprocess_input, decode_predictions
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
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!
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.
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, 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)) #imagenets dog labels are in 151-268 only
Question 3: Use the code cell below to test the performance of your dog_detector
function.
human_files_short
have a detected dog? dog_files_short
have a detected dog?Answer:
See Answer 3 below:
# Question 3: (IMPLEMENTATION) Assess the Dog Detector
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
# vectorized fn is fast than a simple loop
dog_det = np.vectorize(dog_detector)
# will the algorithm find dogs among the images of humans?
results_h_in_d = dog_det(human_files_short)
# Calculate and print percentage of faces in each set
print('Percentage of images from the human dataset detected as dogs:', sum(results_h_in_d)/len(results_h_in_d)*100)
#Nice, 1% turned out be dogs disguised as humans!
results_d_in_d = dog_det(dog_files_short)
print('Percentage of images from the dog dataset detected as dogs:', sum(results_d_in_d)/len(results_d_in_d)*100)
Answer 3:
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 that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.
Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.
We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.
Brittany | Welsh Springer Spaniel |
---|---|
![]() |
![]() |
It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).
Curly-Coated Retriever | American Water Spaniel |
---|---|
![]() |
![]() |
Likewise, recall that labradors come in yellow, chocolate, and black. Your 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 |
---|---|---|
![]() |
![]() |
![]() |
We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.
Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!
We rescale the images by dividing every pixel in every image by 255.
# In[]: Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
# Challenge - high intra-class variation - meaning there within class variation that gets in the way of separating between class variation
# Baseline model - random guess 1/133= 0.75% - so any model has to beat at least this first.
# Pre-process the Data
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
# pre-process the data for Keras - Need to do this in the graded workflow
b_gpu = time.time()
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
d_gpu = time.time() - b_gpu
print ("Time to unpack in seconds: ",round(d_gpu))
#85 seconds
#Got the 4D tensors now modeling
# ME: - for internal - pickle them to avoid unpacking every time. Yes, faster.
'''
import pickle
pickle.dump(train_tensors, open('train_tensors.pkl','wb'), protocol=4)
pickle.dump(valid_tensors, open('valid_tensors.pkl','wb'), protocol=4)
pickle.dump(test_tensors, open('test_tensors.pkl','wb'), protocol=4)
b_gpu = time.time()
train_tensors = pickle.load(open('train_tensors.pkl','rb'))
valid_tensors = pickle.load(open('valid_tensors.pkl','rb'))
test_tensors = pickle.load(open('test_tensors.pkl','rb'))
d_gpu = time.time() - b_gpu
print ("Time to unpickle in seconds: ",round(d_gpu))
#21 seconds
'''
Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:
model.summary()
We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:
Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.
Answer 4:
I used the textbook sequential CNN architecture of three pairs of convolution and pooling layers but instead of the last global average pooling layer (GAP) and the final dense layer I finished the network by a flattening step, first dense layer, a dropout layer and a final dense layer.
I replaced the GAP because I felt that it might lose too much of the useful information in the data. To keep the number of trainable parameters feasible, I optimized the parameters of the three pairs of convolution and pooling layers as well. My final result was a decent model that trained fairly quickly.
# (IMPLEMENTATION) - Step 3 - Model Architecture
# Using only KERAS
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
keras.backend.clear_session() #clear up every time to avoid a mess
model = keras.models.Sequential()
#conv1 - parameters: 1216 = 5x5x3x16 + 16
model.add(
keras.layers.Conv2D(
kernel_size=(5,5)
, data_format='channels_last'
, input_shape=(224,224,3) #color 224x224 square images
, filters=16
, activation='relu'
, strides=(1, 1)
, padding='same'
, kernel_initializer='glorot_uniform'
, bias_initializer='zeros'
, name='conv2d_1st'
))
#pooling2 - (224, 224, 16) -> (56,56,16)
model.add(
keras.layers.MaxPooling2D(
pool_size=(4, 4)
, strides=(4, 4)
, padding='valid'
, data_format='channels_last'
))
#conv2 - parameters - 12832 = 5*5*16*32+32
model.add(
keras.layers.Conv2D(
kernel_size=(5,5)
, data_format='channels_last'
, input_shape=(56,56,16)
, filters=32
, activation='relu'
, strides=(1, 1)
, padding='same'
, kernel_initializer='glorot_uniform'
, bias_initializer='zeros'
, name='conv2d_2nd'
))
#pooling2 (56, 56, 32) -> (14, 14, 32)
model.add(
keras.layers.MaxPooling2D(
pool_size=(4, 4)
, strides=(4, 4)
, padding='valid'
, data_format='channels_last'
))
#conv3 - parameters - 25632 = 5*5*32*32+32
model.add(
keras.layers.Conv2D(
kernel_size=(5,5)
, data_format='channels_last'
, input_shape=(14,14,32)
, filters=32
, activation='relu'
, strides=(1, 1)
, padding='same'
, kernel_initializer='glorot_uniform'
, bias_initializer='zeros'
, name='conv2d_3rd'
))
#pooling3 (14, 14, 32) -> (7, 7, 32)
model.add(
keras.layers.MaxPooling2D(
pool_size=(2, 2)
, strides=(2, 2)
, padding='valid'
, data_format='channels_last'
))
#flatten 7*7*32 -> 1568
model.add(keras.layers.Flatten())
# or GAP - global average pooling - how is it different?
# averages each feature map to 1 pixel, so only 32 features for next layer - too harsh?
#model.add(keras.layers.GlobalAveragePooling2D())
#dense1 - using 1568 features to create 200 sigmoids - 1568*200+200 = 313800 parameters
model.add(
keras.layers.Dense(
units=200 #sigmoids
, input_dim=1568
, kernel_initializer='glorot_uniform'
, bias_initializer='zeros'
, activation='relu'
, name='dense_1st'
))
#dropout does its magic here
model.add(keras.layers.Dropout(rate=0.5, seed=1))
#output layer - using 200 features to create 133 sigmoids = 133*200+200 = 26800 (some parameters got lost?)
model.add(
keras.layers.Dense(
units=breeds_count # classes
, input_dim=200 #previous layer's outputs become features
, kernel_initializer='glorot_uniform'
, bias_initializer='zeros'
, activation='softmax'
, name='dense_2nd'
))
#model.get_config() #full config of all layers
model.summary()
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.
You are welcome to augment the training data, but this is not a requirement.
Step 3 - Train the Model
# Step 3 - Train the Model
#ME: creating my own set up so I can use callbacks for tensorboard as well
v_epoch=5 #even 1 was OK, 5 is enough
v_batchsize=50 #max is 50, recommended is 20
b_gpu = time.time()
#Create directories if don't exist
new_dir = os.path.join(os.getcwd() ,'saved_models') #adds a \ in between
if not os.path.exists(new_dir):
os.makedirs(new_dir)
new_dir = os.path.join(os.getcwd() ,'tensorboard') #adds a \ in between
if not os.path.exists(new_dir):
os.makedirs(new_dir)
checkpointer = keras.callbacks.ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', verbose=1
, save_best_only=True)
#directory path does not work - errors, but w/o directory saves OK
tensorboard = keras.callbacks.TensorBoard(log_dir='tensorboard', histogram_freq=0, write_graph=True, write_images=False)
model.fit(train_tensors, train_targets,
validation_data=(valid_tensors, valid_targets),
epochs=v_epoch, batch_size=v_batchsize,
callbacks=[checkpointer,tensorboard],
verbose=2) #2 shows metrics at the end of each epoch only
#completed very quickly on GPU's
d_gpu = time.time() - b_gpu
print ("My own CNN, batchsize",v_batchsize,", total time",round(d_gpu,2), ", epochs"
,v_epoch, ", time per epoch", round(d_gpu / v_epoch,2))
#rmsprop - batch=20, 20 secs per epoch is OK
#with gap also 20secs per epoch
#for tensorboard - looks OK, sequential, easy to trace
# Launch Tensorboard
# "C:\ProgramData\Anaconda3\Scripts\tensorboard.exe" --logdir "D:\data\tensorboard"
# In[]: Load the Model with the Best Validation Loss
model.load_weights('saved_models/weights.best.from_scratch.hdf5')
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('My own CNN test accuracy: %.4f%%' % test_accuracy)
#rmsprop Accuracy at epoch=5 - 9% - pretty good, I'll take it
#adam - same options - 3.34%
#with GAP - 2.7% quite a loss
Step 3 - Test the Model
# Step 4: Obtain Bottleneck Features
# Use a canned CNN to Classify Dog Breeds - this is called "transfer learning"
bottleneck_features = np.load('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.
# Step 4: Model Architecture
# We use the last convo output from VGG-16 as our input
# All we add is the global average pooling layer and the fully connected layer output layer
# notice we are just adding the last two layers onto the pre-processed data - Transfer Learning
keras.backend.clear_session() #clear memory
VGG16_model = keras.models.Sequential()
VGG16_model.add(keras.layers.GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(keras.layers.Dense(133, activation='softmax'))
VGG16_model.summary()
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
#ME: train using course parameters
v_epoch=20
v_batchsize=20 #max is 200
b_gpu = time.time()
checkpointer = keras.callbacks.ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', verbose=1, save_best_only=True)
#directory path does not work - errors, but w/o directory saves OK
VGG16_model.fit(train_VGG16, train_targets
, validation_data=(valid_VGG16, valid_targets)
, epochs=v_epoch, batch_size=v_batchsize
, callbacks=[checkpointer]
, verbose=0) #use 0 for summary output only
d_gpu = time.time() - b_gpu
print ("VGG16_model, batchsize",v_batchsize,", total time",round(d_gpu,2), ", epochs"
,v_epoch, ", time per epoch", round(d_gpu / v_epoch,2))
#2.4 secs per epoch!
# In[]: Load the Model with the Best Validation Loss
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('VGG16_model 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)]
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:
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
. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/
folder in the repository.
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('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
### TODO: Obtain bottleneck features from another pre-trained CNN.
network = 'DogXceptionData' #just update this: DogVGG19Data DogResnet50Data DogInceptionV3Data DogXceptionData
path = network + '.npz'
train_obj = 'train_'+network
valid_obj = 'valid_'+network
test_obj = 'test_'+network
bottleneck_features = np.load(network + '.npz')
train_obj = bottleneck_features['train']
valid_obj = bottleneck_features['valid']
test_obj = bottleneck_features['test']
print (train_obj.shape[1:])
Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:
<your model's name>.summary()
Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.
Answer 5:
I used global average pooling (GAP) to reduce the dimensionality. Then added a dense layer with L2 regularization and followed by a dropout layer to reduce overfitting. I finished with a fully connected layer as usual with softmax which gives the probabilities for each breed that add up to 1. This resulted in good performance.
### Step 5: Define your architecture. - t_model = transfer model
keras.backend.clear_session() #clear up every time to avoid weird suffixes
t_model = keras.models.Sequential()
t_model.add(keras.layers.GlobalAveragePooling2D(input_shape=train_obj.shape[1:]))
t_model.add(keras.layers.Dense(200, activation='relu', kernel_regularizer=keras.regularizers.l2(0.005)))
t_model.add(keras.layers.Dropout(0.5))
t_model.add(keras.layers.Dense(breeds_count, activation='softmax'))
t_model.summary()
### Step 5: Compile the model.
v_epoch=20 #should be enough
v_batchsize=20 #smaller should be better
t_model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.
You are welcome to augment the training data, but this is not a requirement.
### Step 5: Train the model.
#using checkpointing to save the best model weights
checkpointer = keras.callbacks.ModelCheckpoint(filepath='weights.best.'+ network+'.hdf5',
verbose=1, save_best_only=True)
# can glue strings together here too
t_model.fit(train_obj, train_targets
, validation_data=(valid_obj, valid_targets)
, epochs=v_epoch
, batch_size=v_batchsize
, callbacks=[checkpointer]
, verbose=0)
### Step 5: Load the model weights with the best validation loss. - can load later too, do not have to re-train every time
t_model.load_weights('weights.best.'+ network+'.hdf5')
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
network_predictions = [np.argmax(t_model.predict(np.expand_dims(feature, axis=0))) for feature in test_obj]
# report test accuracy
test_accuracy = 100*np.sum(np.array(network_predictions)==np.argmax(test_targets, axis=1))/len(network_predictions)
print('My model test accuracy for ',network, ': %.4f%%' % test_accuracy)
#OK, 80% is way above 60%
Step 5: Accuracy: 81.46% which is higher than the required 60%
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:
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
.
### Step 5: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
# In[]: OK, now can call Keras directly - w/o tf
from extract_bottleneck_features import extract_Xception
# choose any of these that correspond to the model chosen above: extract_VGG16 extract_VGG19 extract_Resnet50 extract_Xception extract_InceptionV3
#single picture input only - can vectorize later if needed
def pred_breed(img_path, v_model=t_model, extractor=extract_Xception):
#specify the path relative to the cwd or the full path
one_img = path_to_tensor(img_path) #transforms to pixels
bottleneck_feature = extractor(one_img)
pred_probs = v_model.predict(bottleneck_feature)
pred_class = np.argmax(pred_probs)
pred_breed = dog_names[pred_class]
pred_prob = round(pred_probs[:,pred_class][0],2)
print ('\n', pred_breed,'with the probability of ',pred_prob)
return pred_breed, pred_prob
#pred_breed(img_path='images/akash.jpg')
#pred_breed(human_files_short[5])
pred_breed(img_path='images/ally.jpg')
#OK
Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,
You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector
and dog_detector
functions developed above. You are required to use your CNN from Step 5 to predict dog breed.
Some sample output for our algorithm is provided below, but feel free to design your own user experience!
Our algorithm will need these ingredients:
Note: I am re-defining and reloading some stuff here that I already used above - I am doing this for easier comprehension of the functions.
### 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
# 1 Human face detector fn
def face_detector2(img_path, haar= 'haarcascades/haarcascade_frontalface_alt.xml'):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(haar)
faces = face_cascade.detectMultiScale(gray)
num_faces = len(faces)
# add bounding box to color image
if num_faces > 0:
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
print ('Number of human faces detected in the image below: ',num_faces)
else:
print ('No human faces have been detected in the image below.')
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.axis('off')
plt.imshow(cv_rgb)
plt.show()
return num_faces > 0
#face_detector2(human_files_short[5])
face_detector2('images/akash.jpg')
#Face detector OK - make sure has no dependencies
# 2 Dog detector canned model - use resnet for general dog detection first
from keras.applications.resnet50 import ResNet50
from keras.applications.resnet50 import preprocess_input, decode_predictions
from keras.preprocessing import image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
b_gpu = time.time()
ResNet50_model = ResNet50(weights='imagenet')
d_gpu = time.time() - b_gpu
print ("Load time:",d_gpu)
#18 secs
# Auxiliary functions, repeating them here for reference and understanding
# 3 tensors from images
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)
# 4 Pre-process and detect presence of a dog
def predict_labels(img_path, v_model):
# returns prediction vector for image located at img_path
img = preprocess_input(path_to_tensor(img_path))
return np.argmax(v_model.predict(img))
def dog_detector2(img_path, v_model=ResNet50_model):
prediction = predict_labels(img_path, v_model)
output = ((prediction <= 268) & (prediction >= 151)) #imagenets dog labels are in 151-268 only
if output > 0:
print ('A dog has been detected in the image below.')
img = mpimg.imread(img_path)
plt.axis('off')
plt.imshow(img)
plt.show()
else:
print ('No dog has been detected in the image below.')
return output
#dog_detector2(human_files_short[3])
dog_detector2('images/akash.jpg')
#5 Final function - can accept 1 image at a time
# Note that I am using ResNet50_model only to detect the presence of a dog
# While the actual breed is predicted by my CNN from Step 5= t_model
#Switch needs to check if human or dog detected first, only then find the resembling dog breed
def detect_predict_breed (img_path, v_model1=ResNet50_model, v_model2=t_model , extractor=extract_Xception):
#check for a dog first, if not then human, if not, then out
#if either detected explain and then call the breed detector
print ('\n \n Analyzing your image:', img_path)
got_dog = dog_detector2(img_path, v_model=v_model1)
if got_dog:
print ('We think the image contains a dog of this breed...')
pred_breed(img_path, v_model=v_model2)
elif not got_dog:
got_human = face_detector2(img_path)
if got_human:
print ('We think the human in the image looks like this dog breed...')
pred_breed(img_path, v_model=v_model2)
else:
print ('ERROR: No dogs or humans have been detected.')
print ('Analysis completed:', img_path)
#detect_predict_breed(human_files_short[5]) #4 has 1 face, 5 has 2 faces - processed OK
detect_predict_breed('images/akash.jpg') #akash is dog
#OK - dogs and humans - the only thing now is the lag while determining the breed
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 at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.
Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.
Answer 6:
My CNN from Step 5 performs better than I would have expected. My final function also has a sequential analysis approach which presents all the potentially useful information in an orderly fashion.
I think this process could be improved even further if I ever wanted to build a web app:
## 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.
# Test on one image first - "I want to see it work on a negative before I provide you with the positive."
detect_predict_breed('images/sample_cnn.png')
# The function can take only one image, so a simple loop will do just fine to process multiple images
selected_images=[
'images/alina.jpg'
,'images/amber.jpg'
,'images/chelsea.jpg'
,'images/headshot.jpg'
,'images/sample_human_output.png'
,'images/zoinks.jpg'
,'images/sample_cnn.png'
]
for i in selected_images:
detect_predict_breed(i)
Ideas for next steps.
I like the recommedation to turn this into a web app using Flask or Webpy. It would be a nice addition to my portfolio. Other good recommendations are overlaying dog ears over human heads or additional support for mixed breeds - which I will consider if time permits.