Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


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

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

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

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

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


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels

In [3]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

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


Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.


In [6]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("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.


In [7]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

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


Number of faces detected: 3

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

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

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.


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

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

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

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

  • The percentage of the first 100 images in human_files have a detected human face is 99
  • The percentage of the first 100 images in human_files have a detected human face is 11

In [9]:
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.
h = 0
for i in range(len(human_files_short)):
    if face_detector(human_files_short[i]):
        h = h + 1
d = 0
for j in range(len(dog_files_short)):
    if face_detector(dog_files_short[j]):
        d = d + 1
print('The percentage of the first 100 images in human_files have a detected human face is' , h)
print('The percentage of the first 100 images in human_files have a detected human face is' , d)


The percentage of the first 100 images in human_files have a detected human face is 99
The percentage of the first 100 images in human_files have a detected human face is 11

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: In my opinion, yes its a reasonable expectation to pose on the user that we communicate to the user that we accept human images only when they provide a clear view of a face.

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


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

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.


In [10]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

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

$$ (\text{nb_samples}, 224, 224, 3). $$

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


In [11]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.


In [12]:
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).


In [13]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151))

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

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

Answer:

  • The percentage of the images in human_files_short have a detected dog is 0
  • The percentage of the images in dog_files_short have a detected dog is 100

In [14]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

d1 = 0
for i1 in range(len(human_files_short)):
    if dog_detector(human_files_short[i1]):
        d1 = d1 + 1
d2 = 0
for j1 in range(len(dog_files_short)):
    if dog_detector(dog_files_short[j1]):
        d2 = d2 + 1
print('The percentage of the images in human_files_short have a detected dog is' , d1)
print('The percentage of the images in dog_files_short have a detected dog is' , d2)


The percentage of the images in human_files_short have a detected dog is 0
The percentage of the images in dog_files_short have a detected dog is 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 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!

Pre-process the Data

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


In [15]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

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


100%|██████████| 6680/6680 [00:53<00:00, 123.93it/s]
100%|██████████| 835/835 [00:06<00:00, 138.40it/s]
100%|██████████| 836/836 [00:06<00:00, 138.62it/s]

(IMPLEMENTATION) Model Architecture

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: We have created 3 convolutional layers with 3 max pooling layers in between. Filters were increased from 16 to 64 in each of the convolutional layers. Also dropout was used along with flattening layer before using the fully connected layer. Number of noders in the last fully connected layer were setup as 133 along with softmax activation function. Relu activation function was used for all other layers.

3 convolutional layers were used to learn hierarchy of high level features. Max pooling layer is added to reduce the dimensionality. Flatten layer is added to reduce the matrix to row vector. This is because fully connected layer only accepts row vector. Dropout layers were added to reduce overfitting and ensure that the network generalizes well. The last fully connected layer with softmax activation function is added to obtain probabilities of the prediction.


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

model = Sequential()

model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu', input_shape=(224,224,3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
#model.add(GlobalAveragePooling1D())
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(133, activation='softmax'))

### TODO: Define your architecture.

model.summary()


_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 224, 224, 16)      208       
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 112, 112, 32)      2080      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 56, 56, 64)        8256      
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 28, 28, 64)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 28, 28, 64)        0         
_________________________________________________________________
flatten_2 (Flatten)          (None, 50176)             0         
_________________________________________________________________
dense_1 (Dense)              (None, 500)               25088500  
_________________________________________________________________
dropout_2 (Dropout)          (None, 500)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               66633     
=================================================================
Total params: 25,165,677
Trainable params: 25,165,677
Non-trainable params: 0
_________________________________________________________________

Compile the Model


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

(IMPLEMENTATION) Train the Model

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.


In [25]:
from keras.callbacks import ModelCheckpoint  

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

epochs = 100

### 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/100
6660/6680 [============================>.] - ETA: 0s - loss: 4.8819 - acc: 0.0134Epoch 00000: val_loss improved from inf to 4.65395, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 31s - loss: 4.8818 - acc: 0.0133 - val_loss: 4.6539 - val_acc: 0.0467
Epoch 2/100
6660/6680 [============================>.] - ETA: 0s - loss: 4.4216 - acc: 0.0581Epoch 00001: val_loss improved from 4.65395 to 4.27265, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 33s - loss: 4.4216 - acc: 0.0579 - val_loss: 4.2726 - val_acc: 0.0743
Epoch 3/100
6660/6680 [============================>.] - ETA: 0s - loss: 3.8952 - acc: 0.1282Epoch 00002: val_loss improved from 4.27265 to 4.19297, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 32s - loss: 3.8956 - acc: 0.1283 - val_loss: 4.1930 - val_acc: 0.0731
Epoch 4/100
6660/6680 [============================>.] - ETA: 0s - loss: 3.0713 - acc: 0.2746Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 3.0726 - acc: 0.2746 - val_loss: 4.2727 - val_acc: 0.0922
Epoch 5/100
6660/6680 [============================>.] - ETA: 0s - loss: 2.0729 - acc: 0.4841Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 2.0731 - acc: 0.4840 - val_loss: 4.5653 - val_acc: 0.0970
Epoch 6/100
6660/6680 [============================>.] - ETA: 0s - loss: 1.2367 - acc: 0.6794Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 1.2368 - acc: 0.6795 - val_loss: 5.4835 - val_acc: 0.0946
Epoch 7/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.7212 - acc: 0.8033Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.7200 - acc: 0.8036 - val_loss: 6.2500 - val_acc: 0.0838
Epoch 8/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.4599 - acc: 0.8791Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.4600 - acc: 0.8790 - val_loss: 6.7035 - val_acc: 0.0958
Epoch 9/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3510 - acc: 0.9116Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3509 - acc: 0.9117 - val_loss: 7.2097 - val_acc: 0.0886
Epoch 10/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2741 - acc: 0.9332Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2741 - acc: 0.9331 - val_loss: 7.5599 - val_acc: 0.0934
Epoch 11/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2295 - acc: 0.9413Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2292 - acc: 0.9415 - val_loss: 7.1249 - val_acc: 0.0994
Epoch 12/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1908 - acc: 0.9488Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1903 - acc: 0.9490 - val_loss: 7.3706 - val_acc: 0.0898
Epoch 13/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1908 - acc: 0.9523Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1904 - acc: 0.9522 - val_loss: 8.1242 - val_acc: 0.0886
Epoch 14/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1704 - acc: 0.9614Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1699 - acc: 0.9615 - val_loss: 8.5748 - val_acc: 0.0814
Epoch 15/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1790 - acc: 0.9551Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1787 - acc: 0.9551 - val_loss: 8.0984 - val_acc: 0.0743
Epoch 16/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1418 - acc: 0.9664Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1415 - acc: 0.9665 - val_loss: 8.3038 - val_acc: 0.0850
Epoch 17/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1604 - acc: 0.9632Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1601 - acc: 0.9632 - val_loss: 8.5833 - val_acc: 0.0958
Epoch 18/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1482 - acc: 0.9677Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1478 - acc: 0.9678 - val_loss: 8.7248 - val_acc: 0.0826
Epoch 19/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1740 - acc: 0.9614Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1735 - acc: 0.9615 - val_loss: 9.0062 - val_acc: 0.0910
Epoch 20/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1729 - acc: 0.9601Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1728 - acc: 0.9599 - val_loss: 8.1319 - val_acc: 0.0611
Epoch 21/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1941 - acc: 0.9578Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1938 - acc: 0.9579 - val_loss: 9.1735 - val_acc: 0.0910
Epoch 22/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1694 - acc: 0.9605Epoch 00021: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1689 - acc: 0.9606 - val_loss: 7.9534 - val_acc: 0.0910
Epoch 23/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1768 - acc: 0.9587Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1776 - acc: 0.9585 - val_loss: 8.6504 - val_acc: 0.0910
Epoch 24/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1894 - acc: 0.9590Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1900 - acc: 0.9587 - val_loss: 9.9274 - val_acc: 0.0934
Epoch 25/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2006 - acc: 0.9617Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2000 - acc: 0.9618 - val_loss: 9.8612 - val_acc: 0.1042
Epoch 26/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1992 - acc: 0.9598Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1986 - acc: 0.9599 - val_loss: 9.8286 - val_acc: 0.0778
Epoch 27/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1909 - acc: 0.9619Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1905 - acc: 0.9620 - val_loss: 9.3204 - val_acc: 0.0850
Epoch 28/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1957 - acc: 0.9626Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1955 - acc: 0.9627 - val_loss: 10.4542 - val_acc: 0.0802
Epoch 29/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2081 - acc: 0.9571Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2076 - acc: 0.9572 - val_loss: 9.6640 - val_acc: 0.0802
Epoch 30/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1934 - acc: 0.9613Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1931 - acc: 0.9612 - val_loss: 9.7261 - val_acc: 0.0862
Epoch 31/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2205 - acc: 0.9572Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2199 - acc: 0.9573 - val_loss: 10.3561 - val_acc: 0.0778
Epoch 32/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2194 - acc: 0.9578Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 31s - loss: 0.2205 - acc: 0.9575 - val_loss: 9.4664 - val_acc: 0.0743
Epoch 33/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2229 - acc: 0.9578Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2226 - acc: 0.9578 - val_loss: 9.7650 - val_acc: 0.0874
Epoch 34/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2148 - acc: 0.9584Epoch 00033: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2154 - acc: 0.9584 - val_loss: 10.9406 - val_acc: 0.0802
Epoch 35/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2080 - acc: 0.9572Epoch 00034: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2077 - acc: 0.9573 - val_loss: 10.6222 - val_acc: 0.0826
Epoch 36/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2128 - acc: 0.9596Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2122 - acc: 0.9597 - val_loss: 10.5779 - val_acc: 0.0862
Epoch 37/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1997 - acc: 0.9614Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1991 - acc: 0.9615 - val_loss: 10.4253 - val_acc: 0.0743
Epoch 38/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2408 - acc: 0.9584Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2404 - acc: 0.9584 - val_loss: 10.2149 - val_acc: 0.0707
Epoch 39/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2494 - acc: 0.9548Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2488 - acc: 0.9549 - val_loss: 9.6154 - val_acc: 0.0826
Epoch 40/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2183 - acc: 0.9599Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2200 - acc: 0.9599 - val_loss: 10.5865 - val_acc: 0.0838
Epoch 41/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2328 - acc: 0.9577Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2321 - acc: 0.9578 - val_loss: 9.9355 - val_acc: 0.0814
Epoch 42/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2553 - acc: 0.9521Epoch 00041: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2546 - acc: 0.9522 - val_loss: 12.2505 - val_acc: 0.0802
Epoch 43/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2268 - acc: 0.9610Epoch 00042: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2261 - acc: 0.9611 - val_loss: 10.9750 - val_acc: 0.0802
Epoch 44/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2509 - acc: 0.9572Epoch 00043: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2505 - acc: 0.9572 - val_loss: 10.7470 - val_acc: 0.0778
Epoch 45/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2264 - acc: 0.9629Epoch 00044: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2278 - acc: 0.9627 - val_loss: 11.4118 - val_acc: 0.0754
Epoch 46/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2510 - acc: 0.9560Epoch 00045: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2507 - acc: 0.9560 - val_loss: 8.5620 - val_acc: 0.0719
Epoch 47/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2427 - acc: 0.9581Epoch 00046: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2419 - acc: 0.9582 - val_loss: 10.8191 - val_acc: 0.0802
Epoch 48/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2743 - acc: 0.9556Epoch 00047: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2758 - acc: 0.9552 - val_loss: 10.3577 - val_acc: 0.0731
Epoch 49/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2004 - acc: 0.9641Epoch 00048: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2023 - acc: 0.9641 - val_loss: 12.6827 - val_acc: 0.0886
Epoch 50/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2401 - acc: 0.9581Epoch 00049: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2394 - acc: 0.9582 - val_loss: 10.9080 - val_acc: 0.0790
Epoch 51/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2234 - acc: 0.9628Epoch 00050: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2228 - acc: 0.9627 - val_loss: 11.1793 - val_acc: 0.0826
Epoch 52/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.1903 - acc: 0.9629Epoch 00051: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.1907 - acc: 0.9629 - val_loss: 13.3289 - val_acc: 0.0790
Epoch 53/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2532 - acc: 0.9592Epoch 00052: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2527 - acc: 0.9591 - val_loss: 11.4363 - val_acc: 0.0910
Epoch 54/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2206 - acc: 0.9614Epoch 00053: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2203 - acc: 0.9614 - val_loss: 12.9692 - val_acc: 0.1006
Epoch 55/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2435 - acc: 0.9592Epoch 00054: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2437 - acc: 0.9591 - val_loss: 10.9014 - val_acc: 0.0743
Epoch 56/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2211 - acc: 0.9614Epoch 00055: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2205 - acc: 0.9615 - val_loss: 10.8059 - val_acc: 0.0671
Epoch 57/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2554 - acc: 0.9601Epoch 00056: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2547 - acc: 0.9602 - val_loss: 12.4410 - val_acc: 0.0874
Epoch 58/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2481 - acc: 0.9616Epoch 00057: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2474 - acc: 0.9617 - val_loss: 12.3923 - val_acc: 0.0850
Epoch 59/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2497 - acc: 0.9589Epoch 00058: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2498 - acc: 0.9588 - val_loss: 10.1701 - val_acc: 0.0754
Epoch 60/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2508 - acc: 0.9611Epoch 00059: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2500 - acc: 0.9612 - val_loss: 12.6764 - val_acc: 0.0826
Epoch 61/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2463 - acc: 0.9592Epoch 00060: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2456 - acc: 0.9593 - val_loss: 11.0931 - val_acc: 0.0790
Epoch 62/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3043 - acc: 0.9529Epoch 00061: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3046 - acc: 0.9528 - val_loss: 12.0819 - val_acc: 0.0766
Epoch 63/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2641 - acc: 0.9604Epoch 00062: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2633 - acc: 0.9605 - val_loss: 11.8100 - val_acc: 0.0790
Epoch 64/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2659 - acc: 0.9619- ETEpoch 00063: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2651 - acc: 0.9620 - val_loss: 12.6370 - val_acc: 0.0934
Epoch 65/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2976 - acc: 0.9514Epoch 00064: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2991 - acc: 0.9513 - val_loss: 12.9567 - val_acc: 0.0958
Epoch 66/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2711 - acc: 0.9538Epoch 00065: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2706 - acc: 0.9537 - val_loss: 11.9051 - val_acc: 0.0802
Epoch 67/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2733 - acc: 0.9616Epoch 00066: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2725 - acc: 0.9617 - val_loss: 12.4646 - val_acc: 0.0826
Epoch 68/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3199 - acc: 0.9541Epoch 00067: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3220 - acc: 0.9537 - val_loss: 12.5339 - val_acc: 0.0790
Epoch 69/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2723 - acc: 0.9568Epoch 00068: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2715 - acc: 0.9569 - val_loss: 12.1987 - val_acc: 0.0850
Epoch 70/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2920 - acc: 0.9595Epoch 00069: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2911 - acc: 0.9596 - val_loss: 11.9395 - val_acc: 0.0838
Epoch 71/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3096 - acc: 0.9509Epoch 00070: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3087 - acc: 0.9510 - val_loss: 11.2675 - val_acc: 0.0910
Epoch 72/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3014 - acc: 0.9565Epoch 00071: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3005 - acc: 0.9566 - val_loss: 11.7848 - val_acc: 0.0886
Epoch 73/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2734 - acc: 0.9631Epoch 00072: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2761 - acc: 0.9629 - val_loss: 11.7482 - val_acc: 0.0719
Epoch 74/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2735 - acc: 0.9632Epoch 00073: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2751 - acc: 0.9632 - val_loss: 12.8562 - val_acc: 0.0898
Epoch 75/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2914 - acc: 0.9608Epoch 00074: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2911 - acc: 0.9608 - val_loss: 12.2724 - val_acc: 0.0886
Epoch 76/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3231 - acc: 0.9541Epoch 00075: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3226 - acc: 0.9540 - val_loss: 11.6149 - val_acc: 0.0659
Epoch 77/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2435 - acc: 0.9656Epoch 00076: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2428 - acc: 0.9657 - val_loss: 12.9374 - val_acc: 0.0814
Epoch 78/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2734 - acc: 0.9667Epoch 00077: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2726 - acc: 0.9668 - val_loss: 13.1003 - val_acc: 0.0970
Epoch 79/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3089 - acc: 0.9623Epoch 00078: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3080 - acc: 0.9624 - val_loss: 13.3165 - val_acc: 0.0934
Epoch 80/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3192 - acc: 0.9580Epoch 00079: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3194 - acc: 0.9578 - val_loss: 13.3272 - val_acc: 0.0862
Epoch 81/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2743 - acc: 0.9613Epoch 00080: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2736 - acc: 0.9614 - val_loss: 13.3089 - val_acc: 0.0826
Epoch 82/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3029 - acc: 0.9577Epoch 00081: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3020 - acc: 0.9578 - val_loss: 13.2660 - val_acc: 0.0826
Epoch 83/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2917 - acc: 0.9625Epoch 00082: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2909 - acc: 0.9626 - val_loss: 13.0718 - val_acc: 0.0862
Epoch 84/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2796 - acc: 0.9623Epoch 00083: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2788 - acc: 0.9624 - val_loss: 12.7615 - val_acc: 0.0790
Epoch 85/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2985 - acc: 0.9617Epoch 00084: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2976 - acc: 0.9618 - val_loss: 12.9929 - val_acc: 0.0814
Epoch 86/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3196 - acc: 0.9587Epoch 00085: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3186 - acc: 0.9588 - val_loss: 13.1873 - val_acc: 0.0802
Epoch 87/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2985 - acc: 0.9595Epoch 00086: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2978 - acc: 0.9596 - val_loss: 11.8902 - val_acc: 0.0707
Epoch 88/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3024 - acc: 0.9644Epoch 00087: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3015 - acc: 0.9645 - val_loss: 13.0459 - val_acc: 0.0886
Epoch 89/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2936 - acc: 0.9611Epoch 00088: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2937 - acc: 0.9611 - val_loss: 12.0447 - val_acc: 0.0850
Epoch 90/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2442 - acc: 0.9673Epoch 00089: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2483 - acc: 0.9671 - val_loss: 13.3798 - val_acc: 0.0874
Epoch 91/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2635 - acc: 0.9649Epoch 00090: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2653 - acc: 0.9647 - val_loss: 12.5962 - val_acc: 0.0766
Epoch 92/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3105 - acc: 0.9679Epoch 00091: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3095 - acc: 0.9680 - val_loss: 12.5463 - val_acc: 0.0743
Epoch 93/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2901 - acc: 0.9643Epoch 00092: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2893 - acc: 0.9644 - val_loss: 13.4604 - val_acc: 0.0814
Epoch 94/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3059 - acc: 0.9650Epoch 00093: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3050 - acc: 0.9651 - val_loss: 13.7991 - val_acc: 0.0790
Epoch 95/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.3036 - acc: 0.9664Epoch 00094: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.3027 - acc: 0.9665 - val_loss: 13.6533 - val_acc: 0.0874
Epoch 96/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2897 - acc: 0.9674Epoch 00095: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2904 - acc: 0.9672 - val_loss: 13.1062 - val_acc: 0.0922
Epoch 97/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2908 - acc: 0.9671Epoch 00096: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2900 - acc: 0.9672 - val_loss: 13.4063 - val_acc: 0.0862
Epoch 98/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2769 - acc: 0.9730Epoch 00097: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2762 - acc: 0.9729 - val_loss: 14.2746 - val_acc: 0.0886
Epoch 99/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2669 - acc: 0.9715Epoch 00098: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2661 - acc: 0.9716 - val_loss: 12.8634 - val_acc: 0.0754
Epoch 100/100
6660/6680 [============================>.] - ETA: 0s - loss: 0.2935 - acc: 0.9704Epoch 00099: val_loss did not improve
6680/6680 [==============================] - 30s - loss: 0.2928 - acc: 0.9704 - val_loss: 13.8351 - val_acc: 0.0958
Out[25]:
<keras.callbacks.History at 0x7f660c3b5eb8>

Load the Model with the Best Validation Loss


In [18]:
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%.


In [19]:
# 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.3732%

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


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

Model Architecture

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


In [21]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()


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

Compile the Model


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

Train the Model


In [31]:
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.8340 - acc: 0.1113Epoch 00000: val_loss improved from inf to 11.73449, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 12.7952 - acc: 0.1136 - val_loss: 11.7345 - val_acc: 0.1701
Epoch 2/20
6440/6680 [===========================>..] - ETA: 0s - loss: 11.0648 - acc: 0.2422Epoch 00001: val_loss improved from 11.73449 to 11.17534, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 11.0723 - acc: 0.2424 - val_loss: 11.1753 - val_acc: 0.2347
Epoch 3/20
6620/6680 [============================>.] - ETA: 0s - loss: 10.7402 - acc: 0.2890Epoch 00002: val_loss improved from 11.17534 to 11.02409, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 10.7362 - acc: 0.2892 - val_loss: 11.0241 - val_acc: 0.2455
Epoch 4/20
6600/6680 [============================>.] - ETA: 0s - loss: 10.5387 - acc: 0.3109Epoch 00003: val_loss improved from 11.02409 to 10.93116, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 10.5419 - acc: 0.3106 - val_loss: 10.9312 - val_acc: 0.2575
Epoch 5/20
6560/6680 [============================>.] - ETA: 0s - loss: 10.4074 - acc: 0.3264Epoch 00004: val_loss improved from 10.93116 to 10.74244, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 10.4160 - acc: 0.3259 - val_loss: 10.7424 - val_acc: 0.2754
Epoch 6/20
6440/6680 [===========================>..] - ETA: 0s - loss: 10.2388 - acc: 0.3432Epoch 00005: val_loss improved from 10.74244 to 10.67702, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 10.2317 - acc: 0.3433 - val_loss: 10.6770 - val_acc: 0.2683
Epoch 7/20
6520/6680 [============================>.] - ETA: 0s - loss: 10.1123 - acc: 0.3511Epoch 00006: val_loss improved from 10.67702 to 10.57280, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 10.0986 - acc: 0.3519 - val_loss: 10.5728 - val_acc: 0.2886
Epoch 8/20
6560/6680 [============================>.] - ETA: 0s - loss: 10.0178 - acc: 0.3630Epoch 00007: val_loss improved from 10.57280 to 10.56421, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 10.0164 - acc: 0.3629 - val_loss: 10.5642 - val_acc: 0.2874
Epoch 9/20
6560/6680 [============================>.] - ETA: 0s - loss: 9.9114 - acc: 0.3691Epoch 00008: val_loss improved from 10.56421 to 10.34817, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.9106 - acc: 0.3687 - val_loss: 10.3482 - val_acc: 0.2994
Epoch 10/20
6460/6680 [============================>.] - ETA: 0s - loss: 9.7720 - acc: 0.3794Epoch 00009: val_loss improved from 10.34817 to 10.22538, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.7246 - acc: 0.3822 - val_loss: 10.2254 - val_acc: 0.3006
Epoch 11/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.6333 - acc: 0.3917Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 9.6386 - acc: 0.3915 - val_loss: 10.2369 - val_acc: 0.3090
Epoch 12/20
6640/6680 [============================>.] - ETA: 0s - loss: 9.6175 - acc: 0.3964Epoch 00011: val_loss improved from 10.22538 to 10.18943, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.6203 - acc: 0.3963 - val_loss: 10.1894 - val_acc: 0.3054
Epoch 13/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.6107 - acc: 0.3970Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 9.6036 - acc: 0.3973 - val_loss: 10.2359 - val_acc: 0.2970
Epoch 14/20
6520/6680 [============================>.] - ETA: 0s - loss: 9.5360 - acc: 0.4003Epoch 00013: val_loss improved from 10.18943 to 10.08691, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.5395 - acc: 0.4003 - val_loss: 10.0869 - val_acc: 0.3174
Epoch 15/20
6420/6680 [===========================>..] - ETA: 0s - loss: 9.4672 - acc: 0.4008Epoch 00014: val_loss improved from 10.08691 to 9.95143, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.4438 - acc: 0.4018 - val_loss: 9.9514 - val_acc: 0.3150
Epoch 16/20
6540/6680 [============================>.] - ETA: 0s - loss: 9.2090 - acc: 0.4127Epoch 00015: val_loss improved from 9.95143 to 9.74498, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.2368 - acc: 0.4106 - val_loss: 9.7450 - val_acc: 0.3222
Epoch 17/20
6460/6680 [============================>.] - ETA: 0s - loss: 9.0400 - acc: 0.4238Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 9.0325 - acc: 0.4234 - val_loss: 9.7474 - val_acc: 0.3281
Epoch 18/20
6440/6680 [===========================>..] - ETA: 0s - loss: 8.9056 - acc: 0.4339Epoch 00017: val_loss improved from 9.74498 to 9.60025, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.9145 - acc: 0.4332 - val_loss: 9.6002 - val_acc: 0.3365
Epoch 19/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.8479 - acc: 0.4418Epoch 00018: val_loss improved from 9.60025 to 9.55866, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.8447 - acc: 0.4421 - val_loss: 9.5587 - val_acc: 0.3377
Epoch 20/20
6440/6680 [===========================>..] - ETA: 0s - loss: 8.7555 - acc: 0.4452Epoch 00019: val_loss improved from 9.55866 to 9.49385, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.7420 - acc: 0.4460 - val_loss: 9.4938 - val_acc: 0.3449
Out[31]:
<keras.callbacks.History at 0x7f65d41d4ef0>

Load the Model with the Best Validation Loss


In [23]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.


In [24]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

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


Test accuracy: 33.4928%

Predict Dog Breed with the Model


In [25]:
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:

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.

(IMPLEMENTATION) 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('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']

In [26]:
### TODO: Obtain bottleneck features from another pre-trained CNN.

bottleneck_features = np.load('bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features['train']
valid_Xception = bottleneck_features['valid']
test_Xception = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

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: the new data set is small and similar to the original training data, hence end of the network is sliced off and a fully connected layer that matches the number of classes in the new data set is added.Next the weights of the new fully connected layer are randomized; Aall the weights from the pre-trained network are frozen. Finally network is trained to update the weights of the new fully connected layer.


In [27]:
### TODO: Define your architecture.

Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
Xception_model.add(Dense(133, activation='softmax'))

Xception_model.summary()


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

(IMPLEMENTATION) Compile the Model


In [28]:
### TODO: Compile the model.

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

(IMPLEMENTATION) Train the Model

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.


In [26]:
### TODO: Train the model.
from keras.callbacks import ModelCheckpoint 

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

Xception_model.fit(train_Xception, train_targets, 
          validation_data=(valid_Xception, valid_targets),
          epochs=40, batch_size=20, callbacks=[checkpointer], verbose=1)


Train on 6680 samples, validate on 835 samples
Epoch 1/40
6620/6680 [============================>.] - ETA: 0s - loss: 1.0605 - acc: 0.7372Epoch 00000: val_loss improved from inf to 0.54558, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s - loss: 1.0543 - acc: 0.7385 - val_loss: 0.5456 - val_acc: 0.8012
Epoch 2/40
6620/6680 [============================>.] - ETA: 0s - loss: 0.3977 - acc: 0.8707Epoch 00001: val_loss improved from 0.54558 to 0.49065, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s - loss: 0.3988 - acc: 0.8707 - val_loss: 0.4906 - val_acc: 0.8467
Epoch 3/40
6600/6680 [============================>.] - ETA: 0s - loss: 0.3245 - acc: 0.8989Epoch 00002: val_loss improved from 0.49065 to 0.48327, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 3s - loss: 0.3243 - acc: 0.8987 - val_loss: 0.4833 - val_acc: 0.8539
Epoch 4/40
6660/6680 [============================>.] - ETA: 0s - loss: 0.2733 - acc: 0.9156Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.2728 - acc: 0.9157 - val_loss: 0.5034 - val_acc: 0.8467
Epoch 5/40
6640/6680 [============================>.] - ETA: 0s - loss: 0.2426 - acc: 0.9259Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.2426 - acc: 0.9260 - val_loss: 0.5549 - val_acc: 0.8503
Epoch 6/40
6580/6680 [============================>.] - ETA: 0s - loss: 0.2184 - acc: 0.9333Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.2177 - acc: 0.9335 - val_loss: 0.5355 - val_acc: 0.8539
Epoch 7/40
6600/6680 [============================>.] - ETA: 0s - loss: 0.1967 - acc: 0.9383Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.1964 - acc: 0.9385 - val_loss: 0.5493 - val_acc: 0.8575
Epoch 8/40
6640/6680 [============================>.] - ETA: 0s - loss: 0.1781 - acc: 0.9450Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.1775 - acc: 0.9452 - val_loss: 0.5540 - val_acc: 0.8479
Epoch 9/40
6640/6680 [============================>.] - ETA: 0s - loss: 0.1595 - acc: 0.9477Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.1605 - acc: 0.9479 - val_loss: 0.5850 - val_acc: 0.8515
Epoch 10/40
6580/6680 [============================>.] - ETA: 0s - loss: 0.1478 - acc: 0.9564Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.1472 - acc: 0.9567 - val_loss: 0.5558 - val_acc: 0.8599
Epoch 11/40
6540/6680 [============================>.] - ETA: 0s - loss: 0.1395 - acc: 0.9595Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.1387 - acc: 0.9597 - val_loss: 0.5756 - val_acc: 0.8599
Epoch 12/40
6560/6680 [============================>.] - ETA: 0s - loss: 0.1230 - acc: 0.9617Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.1227 - acc: 0.9620 - val_loss: 0.6193 - val_acc: 0.8587
Epoch 13/40
6580/6680 [============================>.] - ETA: 0s - loss: 0.1142 - acc: 0.9635Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.1153 - acc: 0.9632 - val_loss: 0.6028 - val_acc: 0.8467
Epoch 14/40
6640/6680 [============================>.] - ETA: 0s - loss: 0.1071 - acc: 0.9684Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.1066 - acc: 0.9686 - val_loss: 0.5926 - val_acc: 0.8599
Epoch 15/40
6660/6680 [============================>.] - ETA: 0s - loss: 0.1010 - acc: 0.9686Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.1033 - acc: 0.9684 - val_loss: 0.6227 - val_acc: 0.8647
Epoch 16/40
6620/6680 [============================>.] - ETA: 0s - loss: 0.0919 - acc: 0.9746Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0920 - acc: 0.9746 - val_loss: 0.6482 - val_acc: 0.8539
Epoch 17/40
6620/6680 [============================>.] - ETA: 0s - loss: 0.0855 - acc: 0.9752Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0864 - acc: 0.9750 - val_loss: 0.6304 - val_acc: 0.8683
Epoch 18/40
6640/6680 [============================>.] - ETA: 0s - loss: 0.0828 - acc: 0.9739Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0824 - acc: 0.9741 - val_loss: 0.6774 - val_acc: 0.8527
Epoch 19/40
6620/6680 [============================>.] - ETA: 0s - loss: 0.0763 - acc: 0.9766Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0758 - acc: 0.9768 - val_loss: 0.6870 - val_acc: 0.8515
Epoch 20/40
6580/6680 [============================>.] - ETA: 0s - loss: 0.0723 - acc: 0.9796Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0725 - acc: 0.9795 - val_loss: 0.6666 - val_acc: 0.8611
Epoch 21/40
6660/6680 [============================>.] - ETA: 0s - loss: 0.0677 - acc: 0.9800Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0685 - acc: 0.9799 - val_loss: 0.6923 - val_acc: 0.8587
Epoch 22/40
6560/6680 [============================>.] - ETA: 0s - loss: 0.0656 - acc: 0.9823Epoch 00021: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0651 - acc: 0.9825 - val_loss: 0.7081 - val_acc: 0.8575
Epoch 23/40
6660/6680 [============================>.] - ETA: 0s - loss: 0.0602 - acc: 0.9812Epoch 00022: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0608 - acc: 0.9811 - val_loss: 0.7162 - val_acc: 0.8527
Epoch 24/40
6640/6680 [============================>.] - ETA: 0s - loss: 0.0548 - acc: 0.9837Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0585 - acc: 0.9834 - val_loss: 0.7137 - val_acc: 0.8611
Epoch 25/40
6600/6680 [============================>.] - ETA: 0s - loss: 0.0569 - acc: 0.9838Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0564 - acc: 0.9838 - val_loss: 0.7458 - val_acc: 0.8647
Epoch 26/40
6660/6680 [============================>.] - ETA: 0s - loss: 0.0497 - acc: 0.9851Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0496 - acc: 0.9852 - val_loss: 0.7480 - val_acc: 0.8623
Epoch 27/40
6560/6680 [============================>.] - ETA: 0s - loss: 0.0508 - acc: 0.9858Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0501 - acc: 0.9861 - val_loss: 0.7492 - val_acc: 0.8611
Epoch 28/40
6600/6680 [============================>.] - ETA: 0s - loss: 0.0482 - acc: 0.9871Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0496 - acc: 0.9868 - val_loss: 0.7584 - val_acc: 0.8539
Epoch 29/40
6540/6680 [============================>.] - ETA: 0s - loss: 0.0453 - acc: 0.9884Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0448 - acc: 0.9883 - val_loss: 0.7816 - val_acc: 0.8527
Epoch 30/40
6580/6680 [============================>.] - ETA: 0s - loss: 0.0422 - acc: 0.9888Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0423 - acc: 0.9886 - val_loss: 0.7591 - val_acc: 0.8551
Epoch 31/40
6560/6680 [============================>.] - ETA: 0s - loss: 0.0400 - acc: 0.9880Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0407 - acc: 0.9874 - val_loss: 0.8226 - val_acc: 0.8563
Epoch 32/40
6600/6680 [============================>.] - ETA: 0s - loss: 0.0403 - acc: 0.9885Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0399 - acc: 0.9886 - val_loss: 0.8229 - val_acc: 0.8551
Epoch 33/40
6660/6680 [============================>.] - ETA: 0s - loss: 0.0382 - acc: 0.9899Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0381 - acc: 0.9900 - val_loss: 0.8130 - val_acc: 0.8611
Epoch 34/40
6600/6680 [============================>.] - ETA: 0s - loss: 0.0383 - acc: 0.9888Epoch 00033: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0379 - acc: 0.9889 - val_loss: 0.8390 - val_acc: 0.8563
Epoch 35/40
6640/6680 [============================>.] - ETA: 0s - loss: 0.0354 - acc: 0.9902Epoch 00034: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0353 - acc: 0.9903 - val_loss: 0.8384 - val_acc: 0.8503
Epoch 36/40
6560/6680 [============================>.] - ETA: 0s - loss: 0.0344 - acc: 0.9909Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0338 - acc: 0.9910 - val_loss: 0.8343 - val_acc: 0.8467
Epoch 37/40
6580/6680 [============================>.] - ETA: 0s - loss: 0.0336 - acc: 0.9906Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0333 - acc: 0.9907 - val_loss: 0.8554 - val_acc: 0.8623
Epoch 38/40
6620/6680 [============================>.] - ETA: 0s - loss: 0.0336 - acc: 0.9915Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0334 - acc: 0.9916 - val_loss: 0.8724 - val_acc: 0.8539
Epoch 39/40
6560/6680 [============================>.] - ETA: 0s - loss: 0.0302 - acc: 0.9922Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0301 - acc: 0.9922 - val_loss: 0.8614 - val_acc: 0.8563
Epoch 40/40
6580/6680 [============================>.] - ETA: 0s - loss: 0.0290 - acc: 0.9915Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0304 - acc: 0.9913 - val_loss: 0.9045 - val_acc: 0.8563
Out[26]:
<keras.callbacks.History at 0x7fe869f98cc0>

(IMPLEMENTATION) Load the Model with the Best Validation Loss


In [29]:
### TODO: Load the model weights with the best validation loss.
Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')

(IMPLEMENTATION) Test the Model

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


In [30]:
### TODO: Calculate classification accuracy on the test dataset.

# get index of predicted dog breed for each image in test set
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]

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


Test accuracy: 83.9713%

(IMPLEMENTATION) 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.


In [31]:
### 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 Xception_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = Xception_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.

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!

(IMPLEMENTATION) Write your Algorithm


In [37]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def image_detector(img_path1):
    imgf = cv2.imread(img_path1)
    cv_rgbf = cv2.cvtColor(imgf, cv2.COLOR_BGR2RGB)
    if dog_detector(img_path1):
        print("\n hello, dog")
        plt.imshow(cv_rgbf)
        plt.show()
        print("Your breed "+Xception_predict_breed(img_path1))
        return "dog"
    if face_detector(img_path1):
        print("\n hello, human! \n")
        plt.imshow(cv_rgbf)
        plt.show()
        print("Your look like a ... "+Xception_predict_breed(img_path1))        
        return "human"
    plt.imshow(cv_rgbf)
    plt.show()
    print("\n You are neither human or dog...your category may be other")
    return "other"

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?

(IMPLEMENTATION) 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.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: It appears the output it better than was expected. In the 2 dog images the accuracy is only 50%. It is only able to identify 1 image as dog. Although it is able to identify dogs and humans, its incorrectly predicting the breeds.The 1st two are the breeds that algorithm think that we look like. Also the algorithm is mistakenly thinking the cats to be humans.

Following are the points for improvement of the algorithm

  1. The algorithm might perform better if it was also trained on cat images
  2. Accuracy can also be improved if more data is collected and used for training
  3. We can also look at image augmentation and increasing the depth of the neural network to improve accuracy

In [38]:
## 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.

human_files_final = np.array(glob("final_images/human/*"))
cat_files_final = np.array(glob("final_images/cat/*"))
dog_files_final = np.array(glob("final_images/dog/*"))


                                
h2 = 0
for i2 in range(len(human_files_final)):
    if image_detector(human_files_final[i2]) == "human":
        h2 = h2 + 1
print('\n The percentage of the images in human_files_final have a detected human is' , (h2/len(human_files_final))*100)

c2 = 0
c3 = 0
for j2 in range(len(cat_files_final)):
    if image_detector(cat_files_final[j2]) == "human":
        c2 = c2 + 1
print('\n The percentage of the images in cat_files_final have a detected human is' , (c2/len(cat_files_final))*100)

for j3 in range(len(cat_files_final)):
    if image_detector(cat_files_final[j3]) == "dog":
        c3 = c3 + 1

print('\n The percentage of the images in cat_files_final have a detected dog is' , (c3/len(cat_files_final))*100)



d2 = 0
for k2 in range(len(dog_files_final)):
    if image_detector(dog_files_final[k2]) == "dog":
        d2 = d2 + 1
print('\n The percentage of the images in dog_files_final have a detected dog is' , (d2/len(dog_files_final))*100)


 hello, human! 

Your look like a ... Dachshund

 hello, human! 

Your look like a ... Cane_corso

 The percentage of the images in human_files_final have a detected human is 100.0

 hello, human! 

Your look like a ... French_bulldog

 hello, human! 

Your look like a ... Cardigan_welsh_corgi

 The percentage of the images in cat_files_final have a detected human is 100.0

 hello, human! 

Your look like a ... French_bulldog

 hello, human! 

Your look like a ... Cardigan_welsh_corgi

 The percentage of the images in cat_files_final have a detected dog is 0.0

 hello, human! 

Your look like a ... Alaskan_malamute

 hello, dog
Your breed Ibizan_hound

 The percentage of the images in dog_files_final have a detected dog is 50.0