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 [1]:
"""
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)


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 [2]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import helper
import numpy as np

# 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

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 [3]:
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
    ret=x/(x.max()-x.min())

    return ret


"""
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 [4]:
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    
    n_labels = len(x)
    n_unique_labels = 10
    one_hot_encode = np.zeros((n_labels,n_unique_labels))
    for itme in range(n_labels):
        one_hot_encode[itme, x[itme]] = 1
    print(x[0])
    print(one_hot_encode[0])
    print('----------')
    return one_hot_encode


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


3
[ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]
----------
7
[ 0.  0.  0.  0.  0.  0.  0.  1.  0.  0.]
----------
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 [5]:
"""
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)


6
[ 0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]
----------
1
[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
----------
8
[ 0.  0.  0.  0.  0.  0.  0.  0.  1.  0.]
----------
0
[ 1.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
----------
1
[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
----------
4
[ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]
----------
3
[ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]
----------

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 [1]:
"""
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.

If you're finding it hard to dedicate enough time for this course a 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 TensorFlow Layers or TensorFlow Layers (contrib) to build each layer, except "Convolutional & Max Pooling" layer. TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup.

If you would like to get the most of this course, try to solve all the problems without TF Layers. 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 [2]:
import tensorflow as tf

def neural_net_image_input(image_shape):
    """
    Return a Tensor for a bach of image input
    : image_shape: Shape of the images
    : return: Tensor for image input.
    """
    # TODO: Implement Function
    #print(image_shape)
    x = tf.placeholder("float", shape=[None, image_shape[0], image_shape[1], image_shape[2]], name='x')
    #print(x.name)
    return 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
    #print(n_classes)
    x = tf.placeholder("float", shape=[None, n_classes],name='y')
    return x


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


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tf.reset_default_graph()
tests.test_nn_image_inputs(neural_net_image_input)
tests.test_nn_label_inputs(neural_net_label_input)
tests.test_nn_keep_prob_inputs(neural_net_keep_prob_input)


Image Input Tests Passed.
Label Input Tests Passed.
Keep Prob Tests Passed.

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. You're free to use any TensorFlow package for all the other layers.


In [3]:
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_strides: Stride 2-D Tuple for convolution
    :param pool_ksize: kernal 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
    #print(x_tensor.shape)
    x, x_h, x_w, x_depth = x_tensor.shape
    #print(conv_num_outputs)
    #print(conv_ksize)
    conv_h,conv_w = conv_ksize
    #print(conv_strides)
    s_h,s_w = conv_strides
    #print(pool_ksize)
    pool_h, pool_w = pool_ksize
    #print(pool_strides)
    pool_h_s,pool_w_s = pool_strides

    #weights
    
    fw = tf.Variable(tf.truncated_normal(shape=(int(conv_h), int(conv_w), int(x_depth), int(conv_num_outputs)),stddev=0.01, mean = 0))
    #bias                             
    fb = tf.Variable(tf.zeros(conv_num_outputs))                             
    padding = 'VALID'
    conv = tf.nn.conv2d(x_tensor, fw, strides=[1, int(s_h), int(s_w), 1], padding=padding) + fb
    conv = tf.nn.relu(conv)
    conv = tf.nn.max_pool(conv, ksize=[1, int(pool_h), int(pool_w), 1],strides=[1, int(pool_h_s), int(pool_w_s), 1],padding=padding)
    conv.get_shape().as_list()
    return conv


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


Tests Passed

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). You can use TensorFlow Layers or TensorFlow Layers (contrib) for this layer.


In [4]:
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
    #print(x_tensor.shape)
    x, x_h, x_w, x_depth = x_tensor.shape
    return tf.reshape(x_tensor, [-1, int(x_h)*int(x_w)*int(x_depth)])


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


Tests Passed

Fully-Connected Layer

Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). You can use TensorFlow Layers or TensorFlow Layers (contrib) for this layer.


In [5]:
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
    #print(x_tensor.shape)
    #print(num_outputs)
    w = tf.Variable(tf.truncated_normal(shape=(int(x_tensor.shape[1]), int(num_outputs)),stddev=0.1, mean = 0))
    b = tf.Variable(tf.zeros([num_outputs]))
    y = tf.nn.relu(tf.add(tf.matmul(x_tensor, w), b))
    return y


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


Tests Passed

Output Layer

Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). You can use TensorFlow Layers or TensorFlow Layers (contrib) for this layer.

Note: Activation, softmax, or cross entropy shouldn't be applied to this.


In [6]:
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
    #print(x_tensor.shape)
    #print(num_outputs)
    w = tf.Variable(tf.truncated_normal((int(x_tensor.shape[1]), int(num_outputs)),stddev=0.1, mean = 0))
    b = tf.Variable(tf.zeros([num_outputs]))
    y = tf.add(tf.matmul(x_tensor, w), b)
    return y


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


Tests Passed

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 [7]:
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=x
    """
    conv = conv2d_maxpool(conv,
                          conv_num_outputs=50,
                          conv_ksize=(3,3),
                          conv_strides=(1,1),
                          pool_ksize=(3,3),
                          pool_strides=(2,2))
    #"""
    #"""
    conv = conv2d_maxpool(conv,
                          conv_num_outputs=25,
                          conv_ksize=(3,3),
                          conv_strides=(1,1),
                          pool_ksize=(3,3),
                          pool_strides=(2,2))
    #"""
    
    """
    conv = conv2d_maxpool(conv,
                          conv_num_outputs=10,
                          conv_ksize=(3,3),
                          conv_strides=(1,1),
                          pool_ksize=(3,3),
                          pool_strides=(2,2))
    #"""
    
    

    # TODO: Apply a Flatten Layer
    # Function Definition from Above:
    #   flatten(x_tensor)
    flat_layer = 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)
    fc = flat_layer
    
    #"""
    fc = fully_conn(fc, 120)
    fc = tf.nn.dropout(fc, keep_prob)
    #"""
    #"""
    fc = fully_conn(fc, 60)
    fc = tf.nn.dropout(fc, 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(fc, 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
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
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
optimizer = tf.train.AdamOptimizer().minimize(cost)

# 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')

tests.test_conv_net(conv_net)


Neural Network Built!

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 [8]:
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})


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


Tests Passed

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 [9]:
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
    loss = session.run(cost, feed_dict={
                x: feature_batch,
                y: label_batch,
                keep_prob: 1.})
    
    accuracy = session.run(accuracy, feed_dict={
                x: valid_features,
                y: valid_labels,
                keep_prob: 1.})
    print('Loss: {:.4f} Accuracy: {:.2f}%'.format(loss, accuracy*100))

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 [10]:
# TODO: Tune Parameters
epochs = 50
batch_size = 2048
keep_probability = 0.9

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 [11]:
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import datetime
print('Checking the Training on a Single Batch...')
with tf.Session() as sess:
    # Initializing the variables
    sess.run(tf.global_variables_initializer())
    
    # Training cycle
    for epoch in range(epochs):
        batch_i = 1
        start = datetime.datetime.now()
        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)
        end = datetime.datetime.now()
        print (end-start)


Checking the Training on a Single Batch...
Epoch  1, CIFAR-10 Batch 1:  Loss: 2.2673 Accuracy: 12.26%
0:00:03.002504
Epoch  2, CIFAR-10 Batch 1:  Loss: 2.1810 Accuracy: 18.62%
0:00:00.984789
Epoch  3, CIFAR-10 Batch 1:  Loss: 2.0854 Accuracy: 26.02%
0:00:00.988144
Epoch  4, CIFAR-10 Batch 1:  Loss: 2.0318 Accuracy: 26.78%
0:00:00.984472
Epoch  5, CIFAR-10 Batch 1:  Loss: 2.0031 Accuracy: 28.86%
0:00:00.988987
Epoch  6, CIFAR-10 Batch 1:  Loss: 1.9708 Accuracy: 29.52%
0:00:00.984124
Epoch  7, CIFAR-10 Batch 1:  Loss: 1.9429 Accuracy: 30.28%
0:00:00.988282
Epoch  8, CIFAR-10 Batch 1:  Loss: 1.9101 Accuracy: 31.44%
0:00:00.984609
Epoch  9, CIFAR-10 Batch 1:  Loss: 1.8758 Accuracy: 32.96%
0:00:00.987525
Epoch 10, CIFAR-10 Batch 1:  Loss: 1.8363 Accuracy: 33.78%
0:00:00.983768
Epoch 11, CIFAR-10 Batch 1:  Loss: 1.7950 Accuracy: 35.62%
0:00:00.989679
Epoch 12, CIFAR-10 Batch 1:  Loss: 1.7537 Accuracy: 36.80%
0:00:00.984851
Epoch 13, CIFAR-10 Batch 1:  Loss: 1.7157 Accuracy: 38.46%
0:00:00.988012
Epoch 14, CIFAR-10 Batch 1:  Loss: 1.6851 Accuracy: 38.44%
0:00:00.984270
Epoch 15, CIFAR-10 Batch 1:  Loss: 1.6428 Accuracy: 40.52%
0:00:00.991375
Epoch 16, CIFAR-10 Batch 1:  Loss: 1.6076 Accuracy: 40.94%
0:00:00.984840
Epoch 17, CIFAR-10 Batch 1:  Loss: 1.5745 Accuracy: 41.42%
0:00:00.988724
Epoch 18, CIFAR-10 Batch 1:  Loss: 1.5385 Accuracy: 42.48%
0:00:00.984018
Epoch 19, CIFAR-10 Batch 1:  Loss: 1.5122 Accuracy: 43.12%
0:00:00.989492
Epoch 20, CIFAR-10 Batch 1:  Loss: 1.4824 Accuracy: 43.50%
0:00:00.983467
Epoch 21, CIFAR-10 Batch 1:  Loss: 1.4562 Accuracy: 44.02%
0:00:00.989025
Epoch 22, CIFAR-10 Batch 1:  Loss: 1.4279 Accuracy: 44.90%
0:00:00.984773
Epoch 23, CIFAR-10 Batch 1:  Loss: 1.4163 Accuracy: 44.66%
0:00:00.989468
Epoch 24, CIFAR-10 Batch 1:  Loss: 1.3828 Accuracy: 45.54%
0:00:00.986624
Epoch 25, CIFAR-10 Batch 1:  Loss: 1.3596 Accuracy: 46.06%
0:00:00.989381
Epoch 26, CIFAR-10 Batch 1:  Loss: 1.3402 Accuracy: 47.10%
0:00:00.984284
Epoch 27, CIFAR-10 Batch 1:  Loss: 1.3283 Accuracy: 46.82%
0:00:00.988340
Epoch 28, CIFAR-10 Batch 1:  Loss: 1.2968 Accuracy: 47.06%
0:00:00.984099
Epoch 29, CIFAR-10 Batch 1:  Loss: 1.2799 Accuracy: 47.74%
0:00:00.988975
Epoch 30, CIFAR-10 Batch 1:  Loss: 1.2699 Accuracy: 47.78%
0:00:00.984685
Epoch 31, CIFAR-10 Batch 1:  Loss: 1.2505 Accuracy: 48.14%
0:00:00.987716
Epoch 32, CIFAR-10 Batch 1:  Loss: 1.2303 Accuracy: 48.40%
0:00:00.987175
Epoch 33, CIFAR-10 Batch 1:  Loss: 1.2094 Accuracy: 48.88%
0:00:00.992859
Epoch 34, CIFAR-10 Batch 1:  Loss: 1.1954 Accuracy: 49.24%
0:00:00.985751
Epoch 35, CIFAR-10 Batch 1:  Loss: 1.1726 Accuracy: 49.90%
0:00:00.986502
Epoch 36, CIFAR-10 Batch 1:  Loss: 1.1566 Accuracy: 49.86%
0:00:00.986121
Epoch 37, CIFAR-10 Batch 1:  Loss: 1.1400 Accuracy: 50.30%
0:00:00.987854
Epoch 38, CIFAR-10 Batch 1:  Loss: 1.1321 Accuracy: 50.14%
0:00:00.984950
Epoch 39, CIFAR-10 Batch 1:  Loss: 1.1080 Accuracy: 50.40%
0:00:00.988645
Epoch 40, CIFAR-10 Batch 1:  Loss: 1.1073 Accuracy: 50.62%
0:00:00.986274
Epoch 41, CIFAR-10 Batch 1:  Loss: 1.0795 Accuracy: 51.76%
0:00:00.988196
Epoch 42, CIFAR-10 Batch 1:  Loss: 1.0683 Accuracy: 51.02%
0:00:00.984926
Epoch 43, CIFAR-10 Batch 1:  Loss: 1.0530 Accuracy: 51.28%
0:00:00.986699
Epoch 44, CIFAR-10 Batch 1:  Loss: 1.0542 Accuracy: 51.10%
0:00:00.984901
Epoch 45, CIFAR-10 Batch 1:  Loss: 1.0465 Accuracy: 51.14%
0:00:00.987596
Epoch 46, CIFAR-10 Batch 1:  Loss: 1.0284 Accuracy: 51.44%
0:00:00.984020
Epoch 47, CIFAR-10 Batch 1:  Loss: 1.0055 Accuracy: 52.06%
0:00:00.987646
Epoch 48, CIFAR-10 Batch 1:  Loss: 0.9912 Accuracy: 51.98%
0:00:00.982973
Epoch 49, CIFAR-10 Batch 1:  Loss: 0.9770 Accuracy: 52.00%
0:00:00.988259
Epoch 50, CIFAR-10 Batch 1:  Loss: 0.9639 Accuracy: 52.42%
0:00:00.984635

Fully Train the Model

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


In [12]:
"""
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
        start = datetime.datetime.now()
        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)
        end = datetime.datetime.now()
        print (end-start)    
    # Save Model
    saver = tf.train.Saver()
    save_path = saver.save(sess, save_model_path)


Training...
Epoch  1, CIFAR-10 Batch 1:  Loss: 2.2700 Accuracy: 10.30%
Epoch  1, CIFAR-10 Batch 2:  Loss: 2.1900 Accuracy: 20.28%
Epoch  1, CIFAR-10 Batch 3:  Loss: 2.0909 Accuracy: 21.46%
Epoch  1, CIFAR-10 Batch 4:  Loss: 2.0036 Accuracy: 26.82%
Epoch  1, CIFAR-10 Batch 5:  Loss: 1.9719 Accuracy: 25.34%
0:00:04.956487
Epoch  2, CIFAR-10 Batch 1:  Loss: 2.0004 Accuracy: 29.32%
Epoch  2, CIFAR-10 Batch 2:  Loss: 1.9449 Accuracy: 30.56%
Epoch  2, CIFAR-10 Batch 3:  Loss: 1.8817 Accuracy: 30.08%
Epoch  2, CIFAR-10 Batch 4:  Loss: 1.8582 Accuracy: 32.02%
Epoch  2, CIFAR-10 Batch 5:  Loss: 1.8639 Accuracy: 31.34%
0:00:04.927664
Epoch  3, CIFAR-10 Batch 1:  Loss: 1.8579 Accuracy: 34.88%
Epoch  3, CIFAR-10 Batch 2:  Loss: 1.8034 Accuracy: 35.64%
Epoch  3, CIFAR-10 Batch 3:  Loss: 1.7369 Accuracy: 35.86%
Epoch  3, CIFAR-10 Batch 4:  Loss: 1.7325 Accuracy: 37.30%
Epoch  3, CIFAR-10 Batch 5:  Loss: 1.7283 Accuracy: 37.42%
0:00:04.928022
Epoch  4, CIFAR-10 Batch 1:  Loss: 1.7215 Accuracy: 38.88%
Epoch  4, CIFAR-10 Batch 2:  Loss: 1.6963 Accuracy: 38.82%
Epoch  4, CIFAR-10 Batch 3:  Loss: 1.6081 Accuracy: 40.20%
Epoch  4, CIFAR-10 Batch 4:  Loss: 1.6168 Accuracy: 41.06%
Epoch  4, CIFAR-10 Batch 5:  Loss: 1.6337 Accuracy: 41.60%
0:00:04.930733
Epoch  5, CIFAR-10 Batch 1:  Loss: 1.6141 Accuracy: 41.86%
Epoch  5, CIFAR-10 Batch 2:  Loss: 1.5784 Accuracy: 42.60%
Epoch  5, CIFAR-10 Batch 3:  Loss: 1.5290 Accuracy: 42.76%
Epoch  5, CIFAR-10 Batch 4:  Loss: 1.5322 Accuracy: 43.12%
Epoch  5, CIFAR-10 Batch 5:  Loss: 1.5624 Accuracy: 43.56%
0:00:04.929986
Epoch  6, CIFAR-10 Batch 1:  Loss: 1.5339 Accuracy: 43.54%
Epoch  6, CIFAR-10 Batch 2:  Loss: 1.5062 Accuracy: 44.66%
Epoch  6, CIFAR-10 Batch 3:  Loss: 1.4731 Accuracy: 44.42%
Epoch  6, CIFAR-10 Batch 4:  Loss: 1.4649 Accuracy: 45.04%
Epoch  6, CIFAR-10 Batch 5:  Loss: 1.5061 Accuracy: 44.96%
0:00:04.935557
Epoch  7, CIFAR-10 Batch 1:  Loss: 1.4635 Accuracy: 45.64%
Epoch  7, CIFAR-10 Batch 2:  Loss: 1.4528 Accuracy: 45.96%
Epoch  7, CIFAR-10 Batch 3:  Loss: 1.4123 Accuracy: 46.36%
Epoch  7, CIFAR-10 Batch 4:  Loss: 1.4125 Accuracy: 46.60%
Epoch  7, CIFAR-10 Batch 5:  Loss: 1.4513 Accuracy: 47.10%
0:00:04.929438
Epoch  8, CIFAR-10 Batch 1:  Loss: 1.4155 Accuracy: 47.62%
Epoch  8, CIFAR-10 Batch 2:  Loss: 1.4171 Accuracy: 47.78%
Epoch  8, CIFAR-10 Batch 3:  Loss: 1.3572 Accuracy: 48.24%
Epoch  8, CIFAR-10 Batch 4:  Loss: 1.3748 Accuracy: 48.48%
Epoch  8, CIFAR-10 Batch 5:  Loss: 1.4041 Accuracy: 48.80%
0:00:04.933527
Epoch  9, CIFAR-10 Batch 1:  Loss: 1.3680 Accuracy: 49.14%
Epoch  9, CIFAR-10 Batch 2:  Loss: 1.3798 Accuracy: 48.98%
Epoch  9, CIFAR-10 Batch 3:  Loss: 1.3230 Accuracy: 49.80%
Epoch  9, CIFAR-10 Batch 4:  Loss: 1.3254 Accuracy: 50.40%
Epoch  9, CIFAR-10 Batch 5:  Loss: 1.3575 Accuracy: 49.96%
0:00:04.942886
Epoch 10, CIFAR-10 Batch 1:  Loss: 1.3351 Accuracy: 50.82%
Epoch 10, CIFAR-10 Batch 2:  Loss: 1.3272 Accuracy: 51.46%
Epoch 10, CIFAR-10 Batch 3:  Loss: 1.2818 Accuracy: 51.38%
Epoch 10, CIFAR-10 Batch 4:  Loss: 1.2850 Accuracy: 51.04%
Epoch 10, CIFAR-10 Batch 5:  Loss: 1.3199 Accuracy: 51.60%
0:00:04.928450
Epoch 11, CIFAR-10 Batch 1:  Loss: 1.2995 Accuracy: 51.50%
Epoch 11, CIFAR-10 Batch 2:  Loss: 1.2966 Accuracy: 52.26%
Epoch 11, CIFAR-10 Batch 3:  Loss: 1.2535 Accuracy: 51.72%
Epoch 11, CIFAR-10 Batch 4:  Loss: 1.2613 Accuracy: 51.96%
Epoch 11, CIFAR-10 Batch 5:  Loss: 1.2882 Accuracy: 52.50%
0:00:04.932409
Epoch 12, CIFAR-10 Batch 1:  Loss: 1.2746 Accuracy: 53.00%
Epoch 12, CIFAR-10 Batch 2:  Loss: 1.2791 Accuracy: 52.54%
Epoch 12, CIFAR-10 Batch 3:  Loss: 1.2306 Accuracy: 52.56%
Epoch 12, CIFAR-10 Batch 4:  Loss: 1.2411 Accuracy: 52.68%
Epoch 12, CIFAR-10 Batch 5:  Loss: 1.2630 Accuracy: 52.90%
0:00:04.928463
Epoch 13, CIFAR-10 Batch 1:  Loss: 1.2431 Accuracy: 53.74%
Epoch 13, CIFAR-10 Batch 2:  Loss: 1.2404 Accuracy: 53.96%
Epoch 13, CIFAR-10 Batch 3:  Loss: 1.1866 Accuracy: 53.76%
Epoch 13, CIFAR-10 Batch 4:  Loss: 1.2041 Accuracy: 53.68%
Epoch 13, CIFAR-10 Batch 5:  Loss: 1.2216 Accuracy: 53.78%
0:00:04.929582
Epoch 14, CIFAR-10 Batch 1:  Loss: 1.2112 Accuracy: 54.48%
Epoch 14, CIFAR-10 Batch 2:  Loss: 1.2104 Accuracy: 54.60%
Epoch 14, CIFAR-10 Batch 3:  Loss: 1.1528 Accuracy: 54.80%
Epoch 14, CIFAR-10 Batch 4:  Loss: 1.1736 Accuracy: 55.30%
Epoch 14, CIFAR-10 Batch 5:  Loss: 1.1905 Accuracy: 53.94%
0:00:04.923190
Epoch 15, CIFAR-10 Batch 1:  Loss: 1.1873 Accuracy: 54.86%
Epoch 15, CIFAR-10 Batch 2:  Loss: 1.1874 Accuracy: 54.72%
Epoch 15, CIFAR-10 Batch 3:  Loss: 1.1309 Accuracy: 55.52%
Epoch 15, CIFAR-10 Batch 4:  Loss: 1.1504 Accuracy: 55.82%
Epoch 15, CIFAR-10 Batch 5:  Loss: 1.1566 Accuracy: 54.62%
0:00:04.924015
Epoch 16, CIFAR-10 Batch 1:  Loss: 1.1623 Accuracy: 55.64%
Epoch 16, CIFAR-10 Batch 2:  Loss: 1.1599 Accuracy: 55.58%
Epoch 16, CIFAR-10 Batch 3:  Loss: 1.1064 Accuracy: 56.00%
Epoch 16, CIFAR-10 Batch 4:  Loss: 1.1298 Accuracy: 55.72%
Epoch 16, CIFAR-10 Batch 5:  Loss: 1.1283 Accuracy: 55.56%
0:00:04.931368
Epoch 17, CIFAR-10 Batch 1:  Loss: 1.1399 Accuracy: 56.46%
Epoch 17, CIFAR-10 Batch 2:  Loss: 1.1342 Accuracy: 56.52%
Epoch 17, CIFAR-10 Batch 3:  Loss: 1.0855 Accuracy: 56.12%
Epoch 17, CIFAR-10 Batch 4:  Loss: 1.1056 Accuracy: 56.24%
Epoch 17, CIFAR-10 Batch 5:  Loss: 1.1068 Accuracy: 55.68%
0:00:04.932911
Epoch 18, CIFAR-10 Batch 1:  Loss: 1.1194 Accuracy: 56.46%
Epoch 18, CIFAR-10 Batch 2:  Loss: 1.1119 Accuracy: 57.10%
Epoch 18, CIFAR-10 Batch 3:  Loss: 1.0531 Accuracy: 56.84%
Epoch 18, CIFAR-10 Batch 4:  Loss: 1.0791 Accuracy: 56.76%
Epoch 18, CIFAR-10 Batch 5:  Loss: 1.0754 Accuracy: 57.16%
0:00:04.930202
Epoch 19, CIFAR-10 Batch 1:  Loss: 1.1056 Accuracy: 56.46%
Epoch 19, CIFAR-10 Batch 2:  Loss: 1.0912 Accuracy: 57.62%
Epoch 19, CIFAR-10 Batch 3:  Loss: 1.0384 Accuracy: 57.32%
Epoch 19, CIFAR-10 Batch 4:  Loss: 1.0580 Accuracy: 58.00%
Epoch 19, CIFAR-10 Batch 5:  Loss: 1.0539 Accuracy: 57.02%
0:00:04.928543
Epoch 20, CIFAR-10 Batch 1:  Loss: 1.0746 Accuracy: 57.24%
Epoch 20, CIFAR-10 Batch 2:  Loss: 1.0647 Accuracy: 58.00%
Epoch 20, CIFAR-10 Batch 3:  Loss: 1.0169 Accuracy: 57.88%
Epoch 20, CIFAR-10 Batch 4:  Loss: 1.0422 Accuracy: 58.16%
Epoch 20, CIFAR-10 Batch 5:  Loss: 1.0288 Accuracy: 57.50%
0:00:04.925957
Epoch 21, CIFAR-10 Batch 1:  Loss: 1.0599 Accuracy: 57.22%
Epoch 21, CIFAR-10 Batch 2:  Loss: 1.0400 Accuracy: 58.48%
Epoch 21, CIFAR-10 Batch 3:  Loss: 0.9903 Accuracy: 58.48%
Epoch 21, CIFAR-10 Batch 4:  Loss: 1.0234 Accuracy: 58.06%
Epoch 21, CIFAR-10 Batch 5:  Loss: 1.0070 Accuracy: 57.80%
0:00:04.930473
Epoch 22, CIFAR-10 Batch 1:  Loss: 1.0370 Accuracy: 57.72%
Epoch 22, CIFAR-10 Batch 2:  Loss: 1.0180 Accuracy: 58.82%
Epoch 22, CIFAR-10 Batch 3:  Loss: 0.9670 Accuracy: 58.72%
Epoch 22, CIFAR-10 Batch 4:  Loss: 0.9944 Accuracy: 58.90%
Epoch 22, CIFAR-10 Batch 5:  Loss: 0.9814 Accuracy: 58.56%
0:00:04.924053
Epoch 23, CIFAR-10 Batch 1:  Loss: 1.0102 Accuracy: 58.76%
Epoch 23, CIFAR-10 Batch 2:  Loss: 1.0032 Accuracy: 59.32%
Epoch 23, CIFAR-10 Batch 3:  Loss: 0.9475 Accuracy: 59.50%
Epoch 23, CIFAR-10 Batch 4:  Loss: 0.9823 Accuracy: 59.02%
Epoch 23, CIFAR-10 Batch 5:  Loss: 0.9664 Accuracy: 58.56%
0:00:04.927015
Epoch 24, CIFAR-10 Batch 1:  Loss: 0.9953 Accuracy: 58.88%
Epoch 24, CIFAR-10 Batch 2:  Loss: 0.9858 Accuracy: 59.72%
Epoch 24, CIFAR-10 Batch 3:  Loss: 0.9284 Accuracy: 59.24%
Epoch 24, CIFAR-10 Batch 4:  Loss: 0.9522 Accuracy: 59.62%
Epoch 24, CIFAR-10 Batch 5:  Loss: 0.9437 Accuracy: 58.98%
0:00:04.924196
Epoch 25, CIFAR-10 Batch 1:  Loss: 0.9723 Accuracy: 59.12%
Epoch 25, CIFAR-10 Batch 2:  Loss: 0.9648 Accuracy: 60.04%
Epoch 25, CIFAR-10 Batch 3:  Loss: 0.9161 Accuracy: 59.82%
Epoch 25, CIFAR-10 Batch 4:  Loss: 0.9334 Accuracy: 59.84%
Epoch 25, CIFAR-10 Batch 5:  Loss: 0.9204 Accuracy: 59.12%
0:00:04.935484
Epoch 26, CIFAR-10 Batch 1:  Loss: 0.9511 Accuracy: 59.80%
Epoch 26, CIFAR-10 Batch 2:  Loss: 0.9412 Accuracy: 60.10%
Epoch 26, CIFAR-10 Batch 3:  Loss: 0.8949 Accuracy: 59.72%
Epoch 26, CIFAR-10 Batch 4:  Loss: 0.9145 Accuracy: 60.46%
Epoch 26, CIFAR-10 Batch 5:  Loss: 0.9014 Accuracy: 59.62%
0:00:04.930973
Epoch 27, CIFAR-10 Batch 1:  Loss: 0.9378 Accuracy: 59.96%
Epoch 27, CIFAR-10 Batch 2:  Loss: 0.9204 Accuracy: 60.08%
Epoch 27, CIFAR-10 Batch 3:  Loss: 0.8693 Accuracy: 60.26%
Epoch 27, CIFAR-10 Batch 4:  Loss: 0.8957 Accuracy: 60.64%
Epoch 27, CIFAR-10 Batch 5:  Loss: 0.8829 Accuracy: 59.72%
0:00:04.926800
Epoch 28, CIFAR-10 Batch 1:  Loss: 0.9170 Accuracy: 60.60%
Epoch 28, CIFAR-10 Batch 2:  Loss: 0.8988 Accuracy: 60.22%
Epoch 28, CIFAR-10 Batch 3:  Loss: 0.8543 Accuracy: 60.74%
Epoch 28, CIFAR-10 Batch 4:  Loss: 0.8820 Accuracy: 60.90%
Epoch 28, CIFAR-10 Batch 5:  Loss: 0.8640 Accuracy: 59.84%
0:00:04.939775
Epoch 29, CIFAR-10 Batch 1:  Loss: 0.9033 Accuracy: 60.94%
Epoch 29, CIFAR-10 Batch 2:  Loss: 0.8848 Accuracy: 60.66%
Epoch 29, CIFAR-10 Batch 3:  Loss: 0.8371 Accuracy: 60.92%
Epoch 29, CIFAR-10 Batch 4:  Loss: 0.8640 Accuracy: 61.30%
Epoch 29, CIFAR-10 Batch 5:  Loss: 0.8521 Accuracy: 59.98%
0:00:04.930995
Epoch 30, CIFAR-10 Batch 1:  Loss: 0.8852 Accuracy: 60.84%
Epoch 30, CIFAR-10 Batch 2:  Loss: 0.8701 Accuracy: 61.10%
Epoch 30, CIFAR-10 Batch 3:  Loss: 0.8225 Accuracy: 61.48%
Epoch 30, CIFAR-10 Batch 4:  Loss: 0.8407 Accuracy: 61.08%
Epoch 30, CIFAR-10 Batch 5:  Loss: 0.8314 Accuracy: 60.44%
0:00:04.934094
Epoch 31, CIFAR-10 Batch 1:  Loss: 0.8771 Accuracy: 61.16%
Epoch 31, CIFAR-10 Batch 2:  Loss: 0.8521 Accuracy: 61.62%
Epoch 31, CIFAR-10 Batch 3:  Loss: 0.8023 Accuracy: 61.66%
Epoch 31, CIFAR-10 Batch 4:  Loss: 0.8223 Accuracy: 61.80%
Epoch 31, CIFAR-10 Batch 5:  Loss: 0.8121 Accuracy: 60.76%
0:00:04.932134
Epoch 32, CIFAR-10 Batch 1:  Loss: 0.8470 Accuracy: 61.28%
Epoch 32, CIFAR-10 Batch 2:  Loss: 0.8343 Accuracy: 61.46%
Epoch 32, CIFAR-10 Batch 3:  Loss: 0.7896 Accuracy: 61.88%
Epoch 32, CIFAR-10 Batch 4:  Loss: 0.8094 Accuracy: 62.20%
Epoch 32, CIFAR-10 Batch 5:  Loss: 0.7969 Accuracy: 60.60%
0:00:04.929217
Epoch 33, CIFAR-10 Batch 1:  Loss: 0.8467 Accuracy: 61.28%
Epoch 33, CIFAR-10 Batch 2:  Loss: 0.8183 Accuracy: 61.72%
Epoch 33, CIFAR-10 Batch 3:  Loss: 0.7793 Accuracy: 61.92%
Epoch 33, CIFAR-10 Batch 4:  Loss: 0.7947 Accuracy: 62.10%
Epoch 33, CIFAR-10 Batch 5:  Loss: 0.7844 Accuracy: 61.04%
0:00:04.929258
Epoch 34, CIFAR-10 Batch 1:  Loss: 0.8289 Accuracy: 61.70%
Epoch 34, CIFAR-10 Batch 2:  Loss: 0.7976 Accuracy: 61.90%
Epoch 34, CIFAR-10 Batch 3:  Loss: 0.7678 Accuracy: 62.32%
Epoch 34, CIFAR-10 Batch 4:  Loss: 0.7974 Accuracy: 61.08%
Epoch 34, CIFAR-10 Batch 5:  Loss: 0.7800 Accuracy: 61.02%
0:00:04.929841
Epoch 35, CIFAR-10 Batch 1:  Loss: 0.8174 Accuracy: 61.96%
Epoch 35, CIFAR-10 Batch 2:  Loss: 0.7818 Accuracy: 62.18%
Epoch 35, CIFAR-10 Batch 3:  Loss: 0.7507 Accuracy: 62.34%
Epoch 35, CIFAR-10 Batch 4:  Loss: 0.7710 Accuracy: 61.96%
Epoch 35, CIFAR-10 Batch 5:  Loss: 0.7440 Accuracy: 61.42%
0:00:04.926040
Epoch 36, CIFAR-10 Batch 1:  Loss: 0.7937 Accuracy: 62.26%
Epoch 36, CIFAR-10 Batch 2:  Loss: 0.7742 Accuracy: 62.32%
Epoch 36, CIFAR-10 Batch 3:  Loss: 0.7393 Accuracy: 62.66%
Epoch 36, CIFAR-10 Batch 4:  Loss: 0.7532 Accuracy: 62.10%
Epoch 36, CIFAR-10 Batch 5:  Loss: 0.7231 Accuracy: 61.86%
0:00:04.930741
Epoch 37, CIFAR-10 Batch 1:  Loss: 0.7743 Accuracy: 62.58%
Epoch 37, CIFAR-10 Batch 2:  Loss: 0.7513 Accuracy: 62.54%
Epoch 37, CIFAR-10 Batch 3:  Loss: 0.7297 Accuracy: 62.76%
Epoch 37, CIFAR-10 Batch 4:  Loss: 0.7383 Accuracy: 61.82%
Epoch 37, CIFAR-10 Batch 5:  Loss: 0.7204 Accuracy: 61.76%
0:00:04.934630
Epoch 38, CIFAR-10 Batch 1:  Loss: 0.7585 Accuracy: 62.74%
Epoch 38, CIFAR-10 Batch 2:  Loss: 0.7380 Accuracy: 62.72%
Epoch 38, CIFAR-10 Batch 3:  Loss: 0.7239 Accuracy: 61.98%
Epoch 38, CIFAR-10 Batch 4:  Loss: 0.7345 Accuracy: 62.44%
Epoch 38, CIFAR-10 Batch 5:  Loss: 0.7178 Accuracy: 61.30%
0:00:04.931434
Epoch 39, CIFAR-10 Batch 1:  Loss: 0.7635 Accuracy: 62.28%
Epoch 39, CIFAR-10 Batch 2:  Loss: 0.7272 Accuracy: 62.80%
Epoch 39, CIFAR-10 Batch 3:  Loss: 0.6998 Accuracy: 63.24%
Epoch 39, CIFAR-10 Batch 4:  Loss: 0.7032 Accuracy: 62.84%
Epoch 39, CIFAR-10 Batch 5:  Loss: 0.6843 Accuracy: 62.70%
0:00:04.928999
Epoch 40, CIFAR-10 Batch 1:  Loss: 0.7317 Accuracy: 62.88%
Epoch 40, CIFAR-10 Batch 2:  Loss: 0.7208 Accuracy: 62.56%
Epoch 40, CIFAR-10 Batch 3:  Loss: 0.6941 Accuracy: 62.66%
Epoch 40, CIFAR-10 Batch 4:  Loss: 0.6961 Accuracy: 62.42%
Epoch 40, CIFAR-10 Batch 5:  Loss: 0.6776 Accuracy: 62.32%
0:00:04.929664
Epoch 41, CIFAR-10 Batch 1:  Loss: 0.7401 Accuracy: 63.04%
Epoch 41, CIFAR-10 Batch 2:  Loss: 0.6925 Accuracy: 63.12%
Epoch 41, CIFAR-10 Batch 3:  Loss: 0.6779 Accuracy: 62.84%
Epoch 41, CIFAR-10 Batch 4:  Loss: 0.6852 Accuracy: 62.68%
Epoch 41, CIFAR-10 Batch 5:  Loss: 0.6538 Accuracy: 62.52%
0:00:04.931775
Epoch 42, CIFAR-10 Batch 1:  Loss: 0.7204 Accuracy: 63.12%
Epoch 42, CIFAR-10 Batch 2:  Loss: 0.6866 Accuracy: 62.92%
Epoch 42, CIFAR-10 Batch 3:  Loss: 0.6715 Accuracy: 63.20%
Epoch 42, CIFAR-10 Batch 4:  Loss: 0.6585 Accuracy: 63.52%
Epoch 42, CIFAR-10 Batch 5:  Loss: 0.6325 Accuracy: 63.30%
0:00:04.932150
Epoch 43, CIFAR-10 Batch 1:  Loss: 0.6975 Accuracy: 63.12%
Epoch 43, CIFAR-10 Batch 2:  Loss: 0.6677 Accuracy: 63.58%
Epoch 43, CIFAR-10 Batch 3:  Loss: 0.6535 Accuracy: 63.80%
Epoch 43, CIFAR-10 Batch 4:  Loss: 0.6445 Accuracy: 64.06%
Epoch 43, CIFAR-10 Batch 5:  Loss: 0.6135 Accuracy: 63.52%
0:00:04.940867
Epoch 44, CIFAR-10 Batch 1:  Loss: 0.6827 Accuracy: 63.96%
Epoch 44, CIFAR-10 Batch 2:  Loss: 0.6557 Accuracy: 63.98%
Epoch 44, CIFAR-10 Batch 3:  Loss: 0.6448 Accuracy: 63.96%
Epoch 44, CIFAR-10 Batch 4:  Loss: 0.6282 Accuracy: 63.88%
Epoch 44, CIFAR-10 Batch 5:  Loss: 0.6030 Accuracy: 63.66%
0:00:04.930792
Epoch 45, CIFAR-10 Batch 1:  Loss: 0.6736 Accuracy: 63.36%
Epoch 45, CIFAR-10 Batch 2:  Loss: 0.6404 Accuracy: 63.92%
Epoch 45, CIFAR-10 Batch 3:  Loss: 0.6252 Accuracy: 63.70%
Epoch 45, CIFAR-10 Batch 4:  Loss: 0.6190 Accuracy: 63.84%
Epoch 45, CIFAR-10 Batch 5:  Loss: 0.5899 Accuracy: 64.06%
0:00:04.929864
Epoch 46, CIFAR-10 Batch 1:  Loss: 0.6480 Accuracy: 63.58%
Epoch 46, CIFAR-10 Batch 2:  Loss: 0.6358 Accuracy: 64.04%
Epoch 46, CIFAR-10 Batch 3:  Loss: 0.6206 Accuracy: 63.72%
Epoch 46, CIFAR-10 Batch 4:  Loss: 0.5974 Accuracy: 64.40%
Epoch 46, CIFAR-10 Batch 5:  Loss: 0.5782 Accuracy: 63.72%
0:00:04.928365
Epoch 47, CIFAR-10 Batch 1:  Loss: 0.6408 Accuracy: 63.84%
Epoch 47, CIFAR-10 Batch 2:  Loss: 0.6136 Accuracy: 63.96%
Epoch 47, CIFAR-10 Batch 3:  Loss: 0.6038 Accuracy: 64.12%
Epoch 47, CIFAR-10 Batch 4:  Loss: 0.5812 Accuracy: 64.64%
Epoch 47, CIFAR-10 Batch 5:  Loss: 0.5663 Accuracy: 64.14%
0:00:04.939497
Epoch 48, CIFAR-10 Batch 1:  Loss: 0.6358 Accuracy: 63.96%
Epoch 48, CIFAR-10 Batch 2:  Loss: 0.6056 Accuracy: 64.30%
Epoch 48, CIFAR-10 Batch 3:  Loss: 0.5892 Accuracy: 64.18%
Epoch 48, CIFAR-10 Batch 4:  Loss: 0.5760 Accuracy: 64.20%
Epoch 48, CIFAR-10 Batch 5:  Loss: 0.5643 Accuracy: 63.84%
0:00:04.932745
Epoch 49, CIFAR-10 Batch 1:  Loss: 0.6126 Accuracy: 64.46%
Epoch 49, CIFAR-10 Batch 2:  Loss: 0.5884 Accuracy: 64.78%
Epoch 49, CIFAR-10 Batch 3:  Loss: 0.5867 Accuracy: 64.30%
Epoch 49, CIFAR-10 Batch 4:  Loss: 0.5655 Accuracy: 64.60%
Epoch 49, CIFAR-10 Batch 5:  Loss: 0.5470 Accuracy: 64.34%
0:00:04.928066
Epoch 50, CIFAR-10 Batch 1:  Loss: 0.6250 Accuracy: 64.00%
Epoch 50, CIFAR-10 Batch 2:  Loss: 0.5883 Accuracy: 64.64%
Epoch 50, CIFAR-10 Batch 3:  Loss: 0.5824 Accuracy: 63.62%
Epoch 50, CIFAR-10 Batch 4:  Loss: 0.5570 Accuracy: 64.64%
Epoch 50, CIFAR-10 Batch 5:  Loss: 0.5444 Accuracy: 64.10%
0:00:04.927868

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 [13]:
"""
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()


Testing Accuracy: 0.6375786423683166

Why 50-70% 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 70%. 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.