Ariyo Sanmi, PhD

DATA SCIENTIST | MACHINE LEARNING ENGINEER

Ariyo Sanmi, PhD

Dog Breed Prediction using Convolutional Neural Network

Udacity DSND-CNN-Capstone-Project


 
 

Overview

Datasets

Model Design

Evaluation Metric

Accuracy

Step 0: Import Datasets

				
					# 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('data/dog_images/train')
valid_files, valid_targets = load_dataset('data/dog_images/valid')
test_files, test_targets = load_dataset('data/dog_images/test')

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

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
				
			
				
					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.
				
			

Step 1: Detect Humans

Human Detection

Step 2: Detect Dogs

				
					def detected_number(files, model):
    
    number = 0
    
    for item in files:
        if model(item):
            number += 1

    return number


human_faces = detected_number(human_files_short, face_detector)
print("total human faces detected in the human files is: ", human_faces)

false_human_detected = detected_number(dog_files_short, face_detector)
print("total human faces falsely detected in the dog files is: ", false_human_detected)
				
			
				
					total human faces detected in the human files is:  100
total human faces falsely detected in the dog files is:  11
				
			
Human-Dog Classification

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Model Summary

Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)

				
					bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']

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

VGG16_model.summary()
				
			
				
					
_________________________________________________________________
Layer (type)                 Output Shape              Param # 
=================================================================
global_average_pooling2d_4 ( (None, 512)               0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

				
			

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

				
					### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('/data/bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features['train']

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

Xception_model.summary()
				
			
				
					_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_5 ( (None, 2048)              0         
_________________________________________________________________
dense_6 (Dense)              (None, 500)               1024500   
_________________________________________________________________
dense_7 (Dense)              (None, 133)               66633     
=================================================================
Total params: 1,091,133
Trainable params: 1,091,133
Non-trainable params: 0
_________________________________________________________________

				
			

Step 6: Write your Algorithm

 
				
					def img_display(img_path):
    """
    This function displays images from a given file path
    
    Args:
        img_path: image path
    
    Returns:
        None
        Dsiplay the input image in RGB
    """    
    
    image = cv2.imread(img_path)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    plt.imshow(image_rgb)
    plt.show()

    
def predict_detected_breed(img_path):
    """
    This function displays if a dog is present or not in the input image
    
    Args:
        img_path: Image path
    
    Returns:
        Str: Print if its an image of a dog or not 
    """        
    
    img_display(img_path)    
    
    if dog_detector(img_path):
        print("Yes, It's a dog")
        
    elif face_detector(img_path):
        print("It's a human")
        
    else:
        return print("Error Message - neither a dog nor human")
        
        
for file in np.hstack((train_files[2], human_files[2])):
    predict_detected_breed(file)
				
			

Step 7: Test Your Algorithm

Display Classified Humans
Display Classified Dogs

Conclusion

What other options do you think are suitable?

Leave a Reply

Your email address will not be published. Required fields are marked *