Image Classification

In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded. You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers. At the end, you'll get to see your neural network's predictions on the sample images.

Get the Data

Run the following cell to download the CIFAR-10 dataset for python.


In [2]:
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile

cifar10_dataset_folder_path = 'cifar-10-batches-py'

class DLProgress(tqdm):
    last_block = 0

    def hook(self, block_num=1, block_size=1, total_size=None):
        self.total = total_size
        self.update((block_num - self.last_block) * block_size)
        self.last_block = block_num

if not isfile('cifar-10-python.tar.gz'):
    with DLProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar:
        urlretrieve(
            'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz',
            'cifar-10-python.tar.gz',
            pbar.hook)

if not isdir(cifar10_dataset_folder_path):
    with tarfile.open('cifar-10-python.tar.gz') as tar:
        tar.extractall()
        tar.close()


tests.test_folder_path(cifar10_dataset_folder_path)


CIFAR-10 Dataset: 171MB [01:35, 1.79MB/s]                                      
All files found!

Explore the Data

The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following:

  • airplane
  • automobile
  • bird
  • cat
  • deer
  • dog
  • frog
  • horse
  • ship
  • truck

Understanding a dataset is part of making predictions on the data. Play around with the code cell below by changing the batch_id and sample_id. The batch_id is the id for a batch (1-5). The sample_id is the id for a image and label pair in the batch.

Ask yourself "What are all possible labels?", "What is the range of values for the image data?", "Are the labels in order or random?". Answers to questions like these will help you preprocess the data and end up with better predictions.


In [4]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import helper
import numpy as np
import matplotlib.pyplot as plt

# Explore the dataset
batch_id = 1
sample_id = 5
helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id)


Stats of batch 1:
Samples: 10000
Label Counts: {0: 1005, 1: 974, 2: 1032, 3: 1016, 4: 999, 5: 937, 6: 1030, 7: 1001, 8: 1025, 9: 981}
First 20 Labels: [6, 9, 9, 4, 1, 1, 2, 7, 8, 3, 4, 7, 7, 2, 9, 9, 9, 3, 2, 6]

Example of Image 5:
Image - Min Value: 0 Max Value: 252
Image - Shape: (32, 32, 3)
Label - Label Id: 1 Name: automobile

In [5]:
#histogram of labels in batch
features, labels = helper.load_cfar10_batch(cifar10_dataset_folder_path, batch_id)
plt.hist(labels)
plt.show()
#labels seem to be evenly distributed and not in order. The shape of the images is 32x32x3


Implement Preprocess Functions

Normalize

In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x.


In [7]:
def normalize(x):
    """
    Normalize a list of sample image data in the range of 0 to 1
    : x: List of image data.  The image shape is (32, 32, 3)
    : return: Numpy array of normalize data
    """
    # TODO: Implement Function
    return (x-x.min())/(x.max()-x.min())


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_normalize(normalize)


Tests Passed

One-hot encode

Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to one_hot_encode. Make sure to save the map of encodings outside the function.

Hint: Don't reinvent the wheel.


In [8]:
n_labels = 10
encoding_map = np.eye(n_labels)
def one_hot_encode(x):
    """
    One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
    : x: List of sample Labels
    : return: Numpy array of one-hot encoded labels
    """
    # TODO: Implement Function
    return np.array([encoding_map[label] for label in x])


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_one_hot_encode(one_hot_encode)


Tests Passed

Randomize Data

As you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset.

Preprocess all the data and save it

Running the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation.


In [9]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
# Preprocess Training, Validation, and Testing Data
helper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode)

Check Point

This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.


In [10]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import pickle
import problem_unittests as tests
import helper

# Load the Preprocessed Validation data
valid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb'))

Build the network

For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project.

Note: If you're finding it hard to dedicate enough time for this course each week, we've provided a small shortcut to this part of the project. In the next couple of problems, you'll have the option to use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages to build each layer, except the layers you build in the "Convolutional and Max Pooling Layer" section. TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup.

However, if you would like to get the most out of this course, try to solve all the problems without using anything from the TF Layers packages. You can still use classes from other packages that happen to have the same name as ones you find in TF Layers! For example, instead of using the TF Layers version of the conv2d class, tf.layers.conv2d, you would want to use the TF Neural Network version of conv2d, tf.nn.conv2d.

Let's begin!

Input

The neural network needs to read the image data, one-hot encoded labels, and dropout keep probability. Implement the following functions

  • Implement neural_net_image_input
    • Return a TF Placeholder
    • Set the shape using image_shape with batch size set to None.
    • Name the TensorFlow placeholder "x" using the TensorFlow name parameter in the TF Placeholder.
  • Implement neural_net_label_input
    • Return a TF Placeholder
    • Set the shape using n_classes with batch size set to None.
    • Name the TensorFlow placeholder "y" using the TensorFlow name parameter in the TF Placeholder.
  • Implement neural_net_keep_prob_input
    • Return a TF Placeholder for dropout keep probability.
    • Name the TensorFlow placeholder "keep_prob" using the TensorFlow name parameter in the TF Placeholder.

These names will be used at the end of the project to load your saved model.

Note: None for shapes in TensorFlow allow for a dynamic size.


In [18]:
import tensorflow as tf

def neural_net_image_input(image_shape):
    """
    Return a Tensor for a batch of image input
    : image_shape: Shape of the images
    : return: Tensor for image input.
    """
    # TODO: Implement Function
    with tf.name_scope('inputs'):
        return tf.placeholder(tf.float32, [None, image_shape[0], image_shape[1], image_shape[2]], name='x')


def neural_net_label_input(n_classes):
    """
    Return a Tensor for a batch of label input
    : n_classes: Number of classes
    : return: Tensor for label input.
    """
    # TODO: Implement Function
    with tf.name_scope('targets'):
        return tf.placeholder(tf.float32, [None, n_classes], name='y')


def neural_net_keep_prob_input():
    """
    Return a Tensor for keep probability
    : return: Tensor for keep probability.
    """
    # TODO: Implement Function
    with tf.name_scope('keep_prob'):
        return tf.placeholder(tf.float32, name='keep_prob')

Convolution and Max Pooling Layer

Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling:

  • Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor.
  • Apply a convolution to x_tensor using weight and conv_strides.
    • We recommend you use same padding, but you're welcome to use any padding.
  • Add bias
  • Add a nonlinear activation to the convolution.
  • Apply Max Pooling using pool_ksize and pool_strides.
    • We recommend you use same padding, but you're welcome to use any padding.

Note: You can't use TensorFlow Layers or TensorFlow Layers (contrib) for this layer, but you can still use TensorFlow's Neural Network package. You may still use the shortcut option for all the other layers.


In [19]:
def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):
    """
    Apply convolution then max pooling to x_tensor
    :param x_tensor: TensorFlow Tensor
    :param conv_num_outputs: Number of outputs for the convolutional layer
    :param conv_ksize: kernel size 2-D Tuple for the convolutional layer
    :param conv_strides: Stride 2-D Tuple for convolution
    :param pool_ksize: kernel size 2-D Tuple for pool
    :param pool_strides: Stride 2-D Tuple for pool
    : return: A tensor that represents convolution and max pooling of x_tensor
    """
    # TODO: Implement Function
    with tf.name_scope('conv2d_maxpool'):
        kernel = tf.Variable(tf.truncated_normal([conv_ksize[0], conv_ksize[1], int(x_tensor.shape[3]), conv_num_outputs], mean=0.0, stddev=0.1), name='filters')
        bias = tf.Variable(tf.truncated_normal([conv_num_outputs], mean=0.0, stddev=0.1), name='bias')
        conv = tf.nn.conv2d(x_tensor, kernel, [1, conv_strides[0], conv_strides[1], 1], 'SAME')
        conv = tf.nn.bias_add(conv, bias)
        conv = tf.nn.relu(conv)
        pool = tf.nn.max_pool(conv, [1, pool_ksize[0], pool_ksize[1], 1], [1, pool_strides[0], pool_strides[1], 1], 'SAME')
        
        tf.summary.histogram('conv2d_filter', kernel)
        tf.summary.histogram('conv2d_b', bias)
        
        return pool

Flatten Layer

Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.


In [20]:
def flatten(x_tensor):
    """
    Flatten x_tensor to (Batch Size, Flattened Image Size)
    : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions.
    : return: A tensor of size (Batch Size, Flattened Image Size).
    """
    # TODO: Implement Function
    dimensions = x_tensor.get_shape().as_list()
    return tf.reshape(x_tensor, [-1, dimensions[1]*dimensions[2]*dimensions[3]])

Fully-Connected Layer

Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.


In [21]:
def fully_conn(x_tensor, num_outputs):
    """
    Apply a fully connected layer to x_tensor using weight and bias
    : x_tensor: A 2-D tensor where the first dimension is batch size.
    : num_outputs: The number of output that the new tensor should be.
    : return: A 2-D tensor where the second dimension is num_outputs.
    """
    # TODO: Implement Function
    with tf.name_scope('fc'):
        dims = x_tensor.get_shape().as_list()
        weights = tf.Variable(tf.truncated_normal([dims[1], num_outputs], mean=0.0, stddev=0.1), name='weights')
        bias = tf.Variable(tf.truncated_normal([num_outputs], mean=0.0, stddev=0.1), name='bias')
        layer = tf.add(tf.matmul(x_tensor, weights), bias)
        layer = tf.nn.relu(layer)
        
        tf.summary.histogram('fc_w', weights)
        tf.summary.histogram('fc_b', bias)
        
        return layer

Output Layer

Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.

Note: Activation, softmax, or cross entropy should not be applied to this.


In [22]:
def output(x_tensor, num_outputs):
    """
    Apply a output layer to x_tensor using weight and bias
    : x_tensor: A 2-D tensor where the first dimension is batch size.
    : num_outputs: The number of output that the new tensor should be.
    : return: A 2-D tensor where the second dimension is num_outputs.
    """
    # TODO: Implement Function
    with tf.name_scope('output_fc'):
        dims = x_tensor.get_shape().as_list()
        weights = tf.Variable(tf.truncated_normal([dims[1], num_outputs], mean=0.0, stddev=0.1), name='weights')
        bias = tf.Variable(tf.truncated_normal([num_outputs], mean=0.0, stddev=0.1), name='bias')
        layer = tf.add(tf.matmul(x_tensor, weights), bias)
        
        tf.summary.histogram('output_w', weights)
        tf.summary.histogram('output_b', bias)
        
        return layer

Create Convolutional Model

Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model:

  • Apply 1, 2, or 3 Convolution and Max Pool layers
  • Apply a Flatten Layer
  • Apply 1, 2, or 3 Fully Connected Layers
  • Apply an Output Layer
  • Return the output
  • Apply TensorFlow's Dropout to one or more layers in the model using keep_prob.

In [24]:
def conv_net(x, keep_prob):
    """
    Create a convolutional neural network model
    : x: Placeholder tensor that holds image data.
    : keep_prob: Placeholder tensor that hold dropout keep probability.
    : return: Tensor that represents logits
    """
    # TODO: Apply 1, 2, or 3 Convolution and Max Pool layers
    #    Play around with different number of outputs, kernel size and stride
    # Function Definition from Above:
    #    conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides)
    
    conv = conv2d_maxpool(x, 64, [4,4], [2,2], [4,4], [2,2])
    conv = conv2d_maxpool(conv, 128, [4,4], [2,2], [4,4], [2,2])
    conv = conv2d_maxpool(conv, 254, [4,4], [2,2], [4,4], [2,2])
    

    # TODO: Apply a Flatten Layer
    # Function Definition from Above:
    #   flatten(x_tensor)
    flattened_x = flatten(conv)
    

    # TODO: Apply 1, 2, or 3 Fully Connected Layers
    #    Play around with different number of outputs
    # Function Definition from Above:
    #   fully_conn(x_tensor, num_outputs)
    full_layer = fully_conn(flattened_x, 2048)
    full_layer = tf.nn.dropout(full_layer, keep_prob)
    full_layer = fully_conn(full_layer, 2048)
    full_layer = tf.nn.dropout(full_layer, keep_prob)
    
    
    # TODO: Apply an Output Layer
    #    Set this to the number of classes
    # Function Definition from Above:
    #   output(x_tensor, num_outputs)
    output_layer = output(full_layer, 10)
    
    
    # TODO: return output
    return output_layer


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""

##############################
## Build the Neural Network ##
##############################

# Remove previous weights, bias, inputs, etc..
tf.reset_default_graph()

# Inputs
x = neural_net_image_input((32, 32, 3))
y = neural_net_label_input(10)
keep_prob = neural_net_keep_prob_input()

# Model
with tf.name_scope("logits"):
    logits = conv_net(x, keep_prob)

# Name logits Tensor, so that is can be loaded from disk after training
logits = tf.identity(logits, name='logits')

# Loss and Optimizer
with tf.name_scope("xentropy"):
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
    tf.summary.scalar('cost', cost)
    
with tf.name_scope("cost"):
    optimizer = tf.train.AdamOptimizer().minimize(cost)

# Accuracy
with tf.name_scope("accuracy"):
    correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy')
    tf.summary.scalar('accuracy', accuracy)
    
merged = tf.summary.merge_all()

Train the Neural Network

Single Optimization

Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following:

  • x for image input
  • y for labels
  • keep_prob for keep probability for dropout

This function will be called for each batch, so tf.global_variables_initializer() has already been called.

Note: Nothing needs to be returned. This function is only optimizing the neural network.


In [26]:
def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch):
    """
    Optimize the session on a batch of images and labels
    : session: Current TensorFlow session
    : optimizer: TensorFlow optimizer function
    : keep_probability: keep probability
    : feature_batch: Batch of Numpy image data
    : label_batch: Batch of Numpy label data
    """
    # TODO: Implement Function
    session.run(optimizer, feed_dict = {x: feature_batch, y: label_batch, keep_prob: keep_probability})

Show Stats

Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy.


In [27]:
def print_stats(session, feature_batch, label_batch, cost, accuracy):
    """
    Print information about loss and validation accuracy
    : session: Current TensorFlow session
    : feature_batch: Batch of Numpy image data
    : label_batch: Batch of Numpy label data
    : cost: TensorFlow cost function
    : accuracy: TensorFlow accuracy function
    """
    # TODO: Implement Function
    print(session.run(cost, feed_dict = {x: feature_batch, y: label_batch, keep_prob: 1.0}))
    print(session.run(accuracy, feed_dict = {x: valid_features, y: valid_labels, keep_prob: 1.0}))

Hyperparameters

Tune the following parameters:

  • Set epochs to the number of iterations until the network stops learning or start overfitting
  • Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory:
    • 64
    • 128
    • 256
    • ...
  • Set keep_probability to the probability of keeping a node using dropout

In [28]:
# TODO: Tune Parameters
epochs = 50
batch_size = 512
keep_probability = 0.5

Train on a Single CIFAR-10 Batch

Instead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section.


In [32]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
print('Checking the Training on a Single Batch...')
with tf.Session() as sess:
    # Initializing the variables
    sess.run(tf.global_variables_initializer())
    file_writer = tf.summary.FileWriter('./logs/graph', sess.graph)
    
    # Training cycle
    for epoch in range(epochs):
        batch_i = 1
        for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):
            train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)
        print('Epoch {:>2}, CIFAR-10 Batch {}:  '.format(epoch + 1, batch_i), end='')
        print_stats(sess, batch_features, batch_labels, cost, accuracy)


Checking the Training on a Single Batch...
Epoch  1, CIFAR-10 Batch 1:  2.20093
0.1924
Epoch  2, CIFAR-10 Batch 1:  2.00707
0.2648
Epoch  3, CIFAR-10 Batch 1:  1.8771
0.3122
Epoch  4, CIFAR-10 Batch 1:  1.78155
0.3372
Epoch  5, CIFAR-10 Batch 1:  1.71091
0.3688
Epoch  6, CIFAR-10 Batch 1:  1.62703
0.3954
Epoch  7, CIFAR-10 Batch 1:  1.52914
0.4174
Epoch  8, CIFAR-10 Batch 1:  1.44032
0.4386
Epoch  9, CIFAR-10 Batch 1:  1.38966
0.4436
Epoch 10, CIFAR-10 Batch 1:  1.32031
0.4518
Epoch 11, CIFAR-10 Batch 1:  1.24645
0.4564
Epoch 12, CIFAR-10 Batch 1:  1.2092
0.4766
Epoch 13, CIFAR-10 Batch 1:  1.14844
0.4768
Epoch 14, CIFAR-10 Batch 1:  1.08187
0.4906
Epoch 15, CIFAR-10 Batch 1:  1.02775
0.4872
Epoch 16, CIFAR-10 Batch 1:  0.992103
0.4958
Epoch 17, CIFAR-10 Batch 1:  0.91765
0.4966
Epoch 18, CIFAR-10 Batch 1:  0.841063
0.512
Epoch 19, CIFAR-10 Batch 1:  0.804693
0.5058
Epoch 20, CIFAR-10 Batch 1:  0.742184
0.5082
Epoch 21, CIFAR-10 Batch 1:  0.69569
0.527
Epoch 22, CIFAR-10 Batch 1:  0.707289
0.5146
Epoch 23, CIFAR-10 Batch 1:  0.639696
0.515
Epoch 24, CIFAR-10 Batch 1:  0.565117
0.5312
Epoch 25, CIFAR-10 Batch 1:  0.578429
0.5156
Epoch 26, CIFAR-10 Batch 1:  0.576429
0.5098
Epoch 27, CIFAR-10 Batch 1:  0.619233
0.4904
Epoch 28, CIFAR-10 Batch 1:  0.606591
0.5036
Epoch 29, CIFAR-10 Batch 1:  0.532125
0.5344
Epoch 30, CIFAR-10 Batch 1:  0.487689
0.5362
Epoch 31, CIFAR-10 Batch 1:  0.40859
0.543
Epoch 32, CIFAR-10 Batch 1:  0.404214
0.5402
Epoch 33, CIFAR-10 Batch 1:  0.390754
0.5336
Epoch 34, CIFAR-10 Batch 1:  0.399445
0.5302
Epoch 35, CIFAR-10 Batch 1:  0.422257
0.5312
Epoch 36, CIFAR-10 Batch 1:  0.402931
0.5152
Epoch 37, CIFAR-10 Batch 1:  0.324644
0.532
Epoch 38, CIFAR-10 Batch 1:  0.296996
0.536
Epoch 39, CIFAR-10 Batch 1:  0.26698
0.5404
Epoch 40, CIFAR-10 Batch 1:  0.267918
0.5234
Epoch 41, CIFAR-10 Batch 1:  0.221539
0.5406
Epoch 42, CIFAR-10 Batch 1:  0.198304
0.5344
Epoch 43, CIFAR-10 Batch 1:  0.245861
0.5158
Epoch 44, CIFAR-10 Batch 1:  0.314241
0.4976
Epoch 45, CIFAR-10 Batch 1:  0.264067
0.5208
Epoch 46, CIFAR-10 Batch 1:  0.229622
0.53
Epoch 47, CIFAR-10 Batch 1:  0.199081
0.5428
Epoch 48, CIFAR-10 Batch 1:  0.193035
0.5336
Epoch 49, CIFAR-10 Batch 1:  0.264052
0.5094
Epoch 50, CIFAR-10 Batch 1:  0.136181
0.5276

Fully Train the Model

Now that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches.


In [32]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
save_model_path = './image_classification'

print('Training...')
with tf.Session() as sess:
    # Initializing the variables
    sess.run(tf.global_variables_initializer())
    
    # Training cycle
    for epoch in range(epochs):
        # Loop over all batches
        n_batches = 5
        for batch_i in range(1, n_batches + 1):
            for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):
                train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)
            print('Epoch {:>2}, CIFAR-10 Batch {}:  '.format(epoch + 1, batch_i), end='')
            print_stats(sess, batch_features, batch_labels, cost, accuracy)
        if epoch%5 == 0:
            s = sess.run(merged, feed_dict={x: batch_features, y: batch_labels, keep_prob: keep_probability})
            file_writer.add_summary(s, epoch)
            
    # Save Model
    saver = tf.train.Saver()
    save_path = saver.save(sess, save_model_path)


Training...
Epoch  1, CIFAR-10 Batch 1:  2.21166
0.1694
Epoch  1, CIFAR-10 Batch 2:  2.03599
0.2516
Epoch  1, CIFAR-10 Batch 3:  1.83643
0.3016
Epoch  1, CIFAR-10 Batch 4:  1.78109
0.341
Epoch  1, CIFAR-10 Batch 5:  1.75212
0.3634
Epoch  2, CIFAR-10 Batch 1:  1.71461
0.4034
Epoch  2, CIFAR-10 Batch 2:  1.56744
0.411
Epoch  2, CIFAR-10 Batch 3:  1.46489
0.4356
Epoch  2, CIFAR-10 Batch 4:  1.45554
0.4502
Epoch  2, CIFAR-10 Batch 5:  1.47331
0.4548
Epoch  3, CIFAR-10 Batch 1:  1.49503
0.4682
Epoch  3, CIFAR-10 Batch 2:  1.43782
0.4596
Epoch  3, CIFAR-10 Batch 3:  1.27255
0.4842
Epoch  3, CIFAR-10 Batch 4:  1.28458
0.4916
Epoch  3, CIFAR-10 Batch 5:  1.31808
0.5004
Epoch  4, CIFAR-10 Batch 1:  1.42062
0.498
Epoch  4, CIFAR-10 Batch 2:  1.29777
0.4916
Epoch  4, CIFAR-10 Batch 3:  1.17718
0.5142
Epoch  4, CIFAR-10 Batch 4:  1.1387
0.5272
Epoch  4, CIFAR-10 Batch 5:  1.23141
0.5196
Epoch  5, CIFAR-10 Batch 1:  1.31253
0.518
Epoch  5, CIFAR-10 Batch 2:  1.22153
0.5132
Epoch  5, CIFAR-10 Batch 3:  1.0833
0.5496
Epoch  5, CIFAR-10 Batch 4:  1.03245
0.5566
Epoch  5, CIFAR-10 Batch 5:  1.14208
0.5576
Epoch  6, CIFAR-10 Batch 1:  1.19814
0.5458
Epoch  6, CIFAR-10 Batch 2:  1.10953
0.5638
Epoch  6, CIFAR-10 Batch 3:  1.00602
0.5732
Epoch  6, CIFAR-10 Batch 4:  0.959498
0.5702
Epoch  6, CIFAR-10 Batch 5:  1.06073
0.5794
Epoch  7, CIFAR-10 Batch 1:  1.10558
0.5664
Epoch  7, CIFAR-10 Batch 2:  1.03807
0.5612
Epoch  7, CIFAR-10 Batch 3:  0.983123
0.5614
Epoch  7, CIFAR-10 Batch 4:  0.918247
0.5678
Epoch  7, CIFAR-10 Batch 5:  0.971192
0.5884
Epoch  8, CIFAR-10 Batch 1:  1.03601
0.584
Epoch  8, CIFAR-10 Batch 2:  0.945407
0.5912
Epoch  8, CIFAR-10 Batch 3:  0.896254
0.575
Epoch  8, CIFAR-10 Batch 4:  0.858217
0.5938
Epoch  8, CIFAR-10 Batch 5:  0.888576
0.5934
Epoch  9, CIFAR-10 Batch 1:  0.998879
0.579
Epoch  9, CIFAR-10 Batch 2:  0.912348
0.5832
Epoch  9, CIFAR-10 Batch 3:  0.83638
0.5924
Epoch  9, CIFAR-10 Batch 4:  0.814459
0.5988
Epoch  9, CIFAR-10 Batch 5:  0.835596
0.5978
Epoch 10, CIFAR-10 Batch 1:  0.911179
0.597
Epoch 10, CIFAR-10 Batch 2:  0.912045
0.5926
Epoch 10, CIFAR-10 Batch 3:  0.796436
0.5998
Epoch 10, CIFAR-10 Batch 4:  0.765681
0.6124
Epoch 10, CIFAR-10 Batch 5:  0.799696
0.6032
Epoch 11, CIFAR-10 Batch 1:  0.860294
0.6148
Epoch 11, CIFAR-10 Batch 2:  0.835695
0.6126
Epoch 11, CIFAR-10 Batch 3:  0.736097
0.6084
Epoch 11, CIFAR-10 Batch 4:  0.735222
0.6184
Epoch 11, CIFAR-10 Batch 5:  0.764893
0.6106
Epoch 12, CIFAR-10 Batch 1:  0.78106
0.6238
Epoch 12, CIFAR-10 Batch 2:  0.75622
0.6248
Epoch 12, CIFAR-10 Batch 3:  0.684035
0.6136
Epoch 12, CIFAR-10 Batch 4:  0.674342
0.6256
Epoch 12, CIFAR-10 Batch 5:  0.729028
0.609
Epoch 13, CIFAR-10 Batch 1:  0.742485
0.627
Epoch 13, CIFAR-10 Batch 2:  0.721683
0.6318
Epoch 13, CIFAR-10 Batch 3:  0.643152
0.6248
Epoch 13, CIFAR-10 Batch 4:  0.638513
0.6246
Epoch 13, CIFAR-10 Batch 5:  0.693441
0.6258
Epoch 14, CIFAR-10 Batch 1:  0.722186
0.631
Epoch 14, CIFAR-10 Batch 2:  0.695712
0.6262
Epoch 14, CIFAR-10 Batch 3:  0.607011
0.6292
Epoch 14, CIFAR-10 Batch 4:  0.611253
0.633
Epoch 14, CIFAR-10 Batch 5:  0.6254
0.6344
Epoch 15, CIFAR-10 Batch 1:  0.688828
0.6264
Epoch 15, CIFAR-10 Batch 2:  0.645024
0.6292
Epoch 15, CIFAR-10 Batch 3:  0.602919
0.6112
Epoch 15, CIFAR-10 Batch 4:  0.619652
0.632
Epoch 15, CIFAR-10 Batch 5:  0.616448
0.6318
Epoch 16, CIFAR-10 Batch 1:  0.652184
0.6328
Epoch 16, CIFAR-10 Batch 2:  0.6878
0.6028
Epoch 16, CIFAR-10 Batch 3:  0.560646
0.6324
Epoch 16, CIFAR-10 Batch 4:  0.552743
0.6436
Epoch 16, CIFAR-10 Batch 5:  0.549728
0.6418
Epoch 17, CIFAR-10 Batch 1:  0.647533
0.6306
Epoch 17, CIFAR-10 Batch 2:  0.630639
0.6116
Epoch 17, CIFAR-10 Batch 3:  0.54351
0.635
Epoch 17, CIFAR-10 Batch 4:  0.527081
0.6354
Epoch 17, CIFAR-10 Batch 5:  0.531667
0.6342
Epoch 18, CIFAR-10 Batch 1:  0.631967
0.627
Epoch 18, CIFAR-10 Batch 2:  0.607153
0.623
Epoch 18, CIFAR-10 Batch 3:  0.494467
0.6344
Epoch 18, CIFAR-10 Batch 4:  0.49717
0.6326
Epoch 18, CIFAR-10 Batch 5:  0.508731
0.636
Epoch 19, CIFAR-10 Batch 1:  0.628106
0.6206
Epoch 19, CIFAR-10 Batch 2:  0.612371
0.625
Epoch 19, CIFAR-10 Batch 3:  0.489262
0.6378
Epoch 19, CIFAR-10 Batch 4:  0.489266
0.6414
Epoch 19, CIFAR-10 Batch 5:  0.46507
0.648
Epoch 20, CIFAR-10 Batch 1:  0.579142
0.6382
Epoch 20, CIFAR-10 Batch 2:  0.651365
0.6022
Epoch 20, CIFAR-10 Batch 3:  0.480609
0.6352
Epoch 20, CIFAR-10 Batch 4:  0.475071
0.6488
Epoch 20, CIFAR-10 Batch 5:  0.442564
0.649
Epoch 21, CIFAR-10 Batch 1:  0.553833
0.6366
Epoch 21, CIFAR-10 Batch 2:  0.52145
0.6386
Epoch 21, CIFAR-10 Batch 3:  0.466578
0.6292
Epoch 21, CIFAR-10 Batch 4:  0.473846
0.644
Epoch 21, CIFAR-10 Batch 5:  0.440345
0.6444
Epoch 22, CIFAR-10 Batch 1:  0.539763
0.6318
Epoch 22, CIFAR-10 Batch 2:  0.514574
0.636
Epoch 22, CIFAR-10 Batch 3:  0.383784
0.6502
Epoch 22, CIFAR-10 Batch 4:  0.442958
0.646
Epoch 22, CIFAR-10 Batch 5:  0.411912
0.6454
Epoch 23, CIFAR-10 Batch 1:  0.538303
0.6316
Epoch 23, CIFAR-10 Batch 2:  0.538711
0.6166
Epoch 23, CIFAR-10 Batch 3:  0.430896
0.64
Epoch 23, CIFAR-10 Batch 4:  0.438802
0.6422
Epoch 23, CIFAR-10 Batch 5:  0.372153
0.6564
Epoch 24, CIFAR-10 Batch 1:  0.497475
0.6354
Epoch 24, CIFAR-10 Batch 2:  0.512941
0.6204
Epoch 24, CIFAR-10 Batch 3:  0.426734
0.6456
Epoch 24, CIFAR-10 Batch 4:  0.433099
0.6396
Epoch 24, CIFAR-10 Batch 5:  0.343954
0.6564
Epoch 25, CIFAR-10 Batch 1:  0.506423
0.6308
Epoch 25, CIFAR-10 Batch 2:  0.547314
0.6154
Epoch 25, CIFAR-10 Batch 3:  0.390964
0.6504
Epoch 25, CIFAR-10 Batch 4:  0.394586
0.6468
Epoch 25, CIFAR-10 Batch 5:  0.373944
0.6452
Epoch 26, CIFAR-10 Batch 1:  0.451963
0.6396
Epoch 26, CIFAR-10 Batch 2:  0.54239
0.5954
Epoch 26, CIFAR-10 Batch 3:  0.409652
0.6398
Epoch 26, CIFAR-10 Batch 4:  0.391186
0.6502
Epoch 26, CIFAR-10 Batch 5:  0.379658
0.641
Epoch 27, CIFAR-10 Batch 1:  0.48864
0.633
Epoch 27, CIFAR-10 Batch 2:  0.434445
0.6398
Epoch 27, CIFAR-10 Batch 3:  0.362788
0.6422
Epoch 27, CIFAR-10 Batch 4:  0.344335
0.6506
Epoch 27, CIFAR-10 Batch 5:  0.377403
0.6296
Epoch 28, CIFAR-10 Batch 1:  0.454554
0.6224
Epoch 28, CIFAR-10 Batch 2:  0.528867
0.5894
Epoch 28, CIFAR-10 Batch 3:  0.362514
0.6506
Epoch 28, CIFAR-10 Batch 4:  0.345418
0.643
Epoch 28, CIFAR-10 Batch 5:  0.324779
0.6334
Epoch 29, CIFAR-10 Batch 1:  0.479743
0.6224
Epoch 29, CIFAR-10 Batch 2:  0.398171
0.6334
Epoch 29, CIFAR-10 Batch 3:  0.311307
0.655
Epoch 29, CIFAR-10 Batch 4:  0.303088
0.6412
Epoch 29, CIFAR-10 Batch 5:  0.315004
0.6242
Epoch 30, CIFAR-10 Batch 1:  0.450083
0.6202
Epoch 30, CIFAR-10 Batch 2:  0.421208
0.634
Epoch 30, CIFAR-10 Batch 3:  0.292127
0.6648
Epoch 30, CIFAR-10 Batch 4:  0.262542
0.6472
Epoch 30, CIFAR-10 Batch 5:  0.267565
0.6396
Epoch 31, CIFAR-10 Batch 1:  0.465795
0.6286
Epoch 31, CIFAR-10 Batch 2:  0.356959
0.6428
Epoch 31, CIFAR-10 Batch 3:  0.286614
0.6562
Epoch 31, CIFAR-10 Batch 4:  0.266602
0.6462
Epoch 31, CIFAR-10 Batch 5:  0.258577
0.642
Epoch 32, CIFAR-10 Batch 1:  0.443721
0.6088
Epoch 32, CIFAR-10 Batch 2:  0.403832
0.6212
Epoch 32, CIFAR-10 Batch 3:  0.306881
0.6514
Epoch 32, CIFAR-10 Batch 4:  0.263008
0.6348
Epoch 32, CIFAR-10 Batch 5:  0.309552
0.6196
Epoch 33, CIFAR-10 Batch 1:  0.430391
0.6366
Epoch 33, CIFAR-10 Batch 2:  0.356947
0.6434
Epoch 33, CIFAR-10 Batch 3:  0.328087
0.653
Epoch 33, CIFAR-10 Batch 4:  0.244335
0.6394
Epoch 33, CIFAR-10 Batch 5:  0.233653
0.6414
Epoch 34, CIFAR-10 Batch 1:  0.400426
0.6296
Epoch 34, CIFAR-10 Batch 2:  0.360119
0.6306
Epoch 34, CIFAR-10 Batch 3:  0.291159
0.6448
Epoch 34, CIFAR-10 Batch 4:  0.222827
0.6288
Epoch 34, CIFAR-10 Batch 5:  0.227793
0.647
Epoch 35, CIFAR-10 Batch 1:  0.37495
0.6414
Epoch 35, CIFAR-10 Batch 2:  0.351839
0.628
Epoch 35, CIFAR-10 Batch 3:  0.252433
0.6448
Epoch 35, CIFAR-10 Batch 4:  0.178488
0.6408
Epoch 35, CIFAR-10 Batch 5:  0.249252
0.6416
Epoch 36, CIFAR-10 Batch 1:  0.315388
0.6496
Epoch 36, CIFAR-10 Batch 2:  0.29642
0.639
Epoch 36, CIFAR-10 Batch 3:  0.226822
0.6456
Epoch 36, CIFAR-10 Batch 4:  0.178589
0.6484
Epoch 36, CIFAR-10 Batch 5:  0.227971
0.646
Epoch 37, CIFAR-10 Batch 1:  0.325463
0.641
Epoch 37, CIFAR-10 Batch 2:  0.254299
0.642
Epoch 37, CIFAR-10 Batch 3:  0.201551
0.6568
Epoch 37, CIFAR-10 Batch 4:  0.138769
0.6484
Epoch 37, CIFAR-10 Batch 5:  0.239369
0.6406
Epoch 38, CIFAR-10 Batch 1:  0.298077
0.6496
Epoch 38, CIFAR-10 Batch 2:  0.221598
0.6474
Epoch 38, CIFAR-10 Batch 3:  0.181704
0.654
Epoch 38, CIFAR-10 Batch 4:  0.154869
0.6384
Epoch 38, CIFAR-10 Batch 5:  0.209193
0.643
Epoch 39, CIFAR-10 Batch 1:  0.296748
0.6392
Epoch 39, CIFAR-10 Batch 2:  0.205484
0.652
Epoch 39, CIFAR-10 Batch 3:  0.208748
0.6352
Epoch 39, CIFAR-10 Batch 4:  0.148808
0.65
Epoch 39, CIFAR-10 Batch 5:  0.224276
0.6366
Epoch 40, CIFAR-10 Batch 1:  0.303394
0.6188
Epoch 40, CIFAR-10 Batch 2:  0.229561
0.6418
Epoch 40, CIFAR-10 Batch 3:  0.186894
0.6408
Epoch 40, CIFAR-10 Batch 4:  0.178251
0.639
Epoch 40, CIFAR-10 Batch 5:  0.21695
0.6286
Epoch 41, CIFAR-10 Batch 1:  0.224128
0.6414
Epoch 41, CIFAR-10 Batch 2:  0.231522
0.6468
Epoch 41, CIFAR-10 Batch 3:  0.162511
0.6414
Epoch 41, CIFAR-10 Batch 4:  0.1982
0.6246
Epoch 41, CIFAR-10 Batch 5:  0.232851
0.6084
Epoch 42, CIFAR-10 Batch 1:  0.291507
0.6282
Epoch 42, CIFAR-10 Batch 2:  0.262628
0.6376
Epoch 42, CIFAR-10 Batch 3:  0.188962
0.6324
Epoch 42, CIFAR-10 Batch 4:  0.179589
0.6242
Epoch 42, CIFAR-10 Batch 5:  0.219896
0.609
Epoch 43, CIFAR-10 Batch 1:  0.267048
0.6304
Epoch 43, CIFAR-10 Batch 2:  0.244949
0.6276
Epoch 43, CIFAR-10 Batch 3:  0.171634
0.6372
Epoch 43, CIFAR-10 Batch 4:  0.187338
0.6364
Epoch 43, CIFAR-10 Batch 5:  0.157789
0.638
Epoch 44, CIFAR-10 Batch 1:  0.238637
0.6404
Epoch 44, CIFAR-10 Batch 2:  0.230277
0.6378
Epoch 44, CIFAR-10 Batch 3:  0.185545
0.6274
Epoch 44, CIFAR-10 Batch 4:  0.177404
0.6458
Epoch 44, CIFAR-10 Batch 5:  0.160448
0.6372
Epoch 45, CIFAR-10 Batch 1:  0.194527
0.6462
Epoch 45, CIFAR-10 Batch 2:  0.241609
0.625
Epoch 45, CIFAR-10 Batch 3:  0.190016
0.6376
Epoch 45, CIFAR-10 Batch 4:  0.172933
0.6374
Epoch 45, CIFAR-10 Batch 5:  0.176167
0.6312
Epoch 46, CIFAR-10 Batch 1:  0.177713
0.6552
Epoch 46, CIFAR-10 Batch 2:  0.258762
0.6232
Epoch 46, CIFAR-10 Batch 3:  0.169085
0.6424
Epoch 46, CIFAR-10 Batch 4:  0.184824
0.6212
Epoch 46, CIFAR-10 Batch 5:  0.178952
0.6368
Epoch 47, CIFAR-10 Batch 1:  0.195318
0.6472
Epoch 47, CIFAR-10 Batch 2:  0.233487
0.6212
Epoch 47, CIFAR-10 Batch 3:  0.192884
0.6526
Epoch 47, CIFAR-10 Batch 4:  0.1381
0.635
Epoch 47, CIFAR-10 Batch 5:  0.173517
0.632
Epoch 48, CIFAR-10 Batch 1:  0.173927
0.6514
Epoch 48, CIFAR-10 Batch 2:  0.191218
0.6402
Epoch 48, CIFAR-10 Batch 3:  0.134857
0.648
Epoch 48, CIFAR-10 Batch 4:  0.146444
0.632
Epoch 48, CIFAR-10 Batch 5:  0.202592
0.6166
Epoch 49, CIFAR-10 Batch 1:  0.180857
0.6524
Epoch 49, CIFAR-10 Batch 2:  0.201355
0.631
Epoch 49, CIFAR-10 Batch 3:  0.132283
0.6416
Epoch 49, CIFAR-10 Batch 4:  0.140292
0.6344
Epoch 49, CIFAR-10 Batch 5:  0.147614
0.6392
Epoch 50, CIFAR-10 Batch 1:  0.195321
0.639
Epoch 50, CIFAR-10 Batch 2:  0.161661
0.6344
Epoch 50, CIFAR-10 Batch 3:  0.0898699
0.6542
Epoch 50, CIFAR-10 Batch 4:  0.140169
0.624
Epoch 50, CIFAR-10 Batch 5:  0.150952
0.6352

Checkpoint

The model has been saved to disk.

Test Model

Test your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters.


In [34]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import tensorflow as tf
import pickle
import helper
import random

# Set batch size if not already set
try:
    if batch_size:
        pass
except NameError:
    batch_size = 64

save_model_path = './image_classification'
n_samples = 4
top_n_predictions = 3

def test_model():
    """
    Test the saved model against the test dataset
    """

    test_features, test_labels = pickle.load(open('preprocess_training.p', mode='rb'))
    loaded_graph = tf.Graph()

    with tf.Session(graph=loaded_graph) as sess:
        # Load model
        loader = tf.train.import_meta_graph(save_model_path + '.meta')
        loader.restore(sess, save_model_path)

        # Get Tensors from loaded model
        loaded_x = loaded_graph.get_tensor_by_name('x:0')
        loaded_y = loaded_graph.get_tensor_by_name('y:0')
        loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')
        loaded_logits = loaded_graph.get_tensor_by_name('logits:0')
        loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0')
        
        # Get accuracy in batches for memory limitations
        test_batch_acc_total = 0
        test_batch_count = 0
        
        for train_feature_batch, train_label_batch in helper.batch_features_labels(test_features, test_labels, batch_size):
            test_batch_acc_total += sess.run(
                loaded_acc,
                feed_dict={loaded_x: train_feature_batch, loaded_y: train_label_batch, loaded_keep_prob: 1.0})
            test_batch_count += 1

        print('Testing Accuracy: {}\n'.format(test_batch_acc_total/test_batch_count))

        # Print Random Samples
        random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples)))
        random_test_predictions = sess.run(
            tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions),
            feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0})
        helper.display_image_predictions(random_test_features, random_test_labels, random_test_predictions)


test_model()


INFO:tensorflow:Restoring parameters from ./image_classification
Testing Accuracy: 0.6345530778169632

Why 50-80% Accuracy?

You might be wondering why you can't get an accuracy any higher. First things first, 50% isn't bad for a simple CNN. Pure guessing would get you 10% accuracy. However, you might notice people are getting scores well above 80%. That's because we haven't taught you all there is to know about neural networks. We still need to cover a few more techniques.

Submitting This Project

When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_image_classification.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.