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'

# Use Floyd's cifar-10 dataset if present
floyd_cifar10_location = '/input/cifar-10/python.tar.gz'
if isfile(floyd_cifar10_location):
    tar_gz_path = floyd_cifar10_location
else:
    tar_gz_path = 'cifar-10-python.tar.gz'

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(tar_gz_path):
    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',
            tar_gz_path,
            pbar.hook)

if not isdir(cifar10_dataset_folder_path):
    with tarfile.open(tar_gz_path) 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 [3]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import helper
import numpy as np

# Explore the dataset
batch_id = 2
sample_id = 6
helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id)


Stats of batch 2:
Samples: 10000
Label Counts: {0: 984, 1: 1007, 2: 1010, 3: 995, 4: 1010, 5: 988, 6: 1008, 7: 1026, 8: 987, 9: 985}
First 20 Labels: [1, 6, 6, 8, 8, 3, 4, 6, 0, 6, 0, 3, 6, 6, 5, 4, 8, 3, 2, 6]

Example of Image 6:
Image - Min Value: 0 Max Value: 235
Image - Shape: (32, 32, 3)
Label - Label Id: 4 Name: deer

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 [4]:
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/255


"""
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 [5]:
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
    """
    for i,label in enumerate(x):
        A=np.zeros(10)
        A[label]=1
        if(i==0):
            oneHotEncode=A
        else:
            oneHotEncode=np.vstack([oneHotEncode,A])
    return oneHotEncode


"""
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 [6]:
"""
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 [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'))
(valid_labels.shape
)


Out[1]:
(5000, 10)

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 [2]:
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
    return tf.placeholder(tf.float32,shape=(None,*image_shape),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
    return tf.placeholder(tf.float32,shape=(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
    return tf.placeholder(tf.float32,name='keep_prob')


"""
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, but you can still use TensorFlow's Neural Network package. You may still use the shortcut option for all the other layers.


In [3]:
MEAN_INIT = 0.001
STDDEV_INIT = 0.05
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: kernal size 2-D Tuple 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
    """
    
    
    weights=tf.Variable(tf.truncated_normal(mean=MEAN_INIT, stddev=STDDEV_INIT, shape=[*conv_ksize,int(x_tensor.shape[3]),conv_num_outputs]))
    #bias=tf.Variable(tf.zeros(conv_num_outputs))
    bias = tf.Variable(tf.truncated_normal(mean=MEAN_INIT, stddev=STDDEV_INIT, shape=[conv_num_outputs]))
    x= tf.nn.conv2d(x_tensor,weights,[1,*conv_strides,1],padding='SAME')
    x=tf.nn.bias_add(x,bias)
    x=tf.nn.relu(x)
    x=tf.nn.max_pool(x,[1,*pool_ksize,1],[1,*pool_strides,1], padding='SAME')
    # TODO: Implement Function
    
    return x


"""
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). 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 [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).
    """
   
    image_size=int(x_tensor.shape[1]*x_tensor.shape[2]*x_tensor.shape[3])
    return tf.reshape(x_tensor,[-1,image_size])


"""
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). 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 [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
    
    W=tf.Variable(tf.truncated_normal(mean=MEAN_INIT, stddev=STDDEV_INIT, shape=[x_tensor.shape[1].value, num_outputs]))
    bias=tf.Variable(tf.truncated_normal(mean=MEAN_INIT, stddev=STDDEV_INIT, shape=[num_outputs]))
    x=tf.add(tf.matmul(x_tensor,W),bias)
    return tf.nn.relu(x)


"""
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). 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 [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
    W=tf.Variable(tf.truncated_normal([x_tensor.shape[1].value,num_outputs]))
    bias=tf.Variable(tf.zeros(num_outputs))
    x=tf.add(tf.matmul(x_tensor,W),bias)
    return x


"""
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
    """
    conv_num_outputs=[]
    # 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:
    x = conv2d_maxpool(x, 16, (5, 5), (1, 1), (2, 2), (2, 2))
    x = conv2d_maxpool(x, 32, (5, 5), (1, 1), (2, 2), (2, 2))
    x = conv2d_maxpool(x, 64, (5, 5), (1, 1), (2, 2), (2, 2))
    # TODO: Apply a Flatten Layer
    # Function Definition from Above:
    x=flatten(x)

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


"""
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
    """
    feed_dict = {'keep_prob:0': keep_probability, 'x:0': feature_batch, 'y:0': label_batch}
    session.run(optimizer, feed_dict=feed_dict)


"""
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
    """
    feed_cost = {'keep_prob:0': keep_probability, 'x:0': feature_batch, 'y:0': label_batch}
    cost=session.run(cost, feed_dict=feed_cost)
    feed_accuracy = {'keep_prob:0': keep_probability, 'x:0': valid_features, 'y:0': valid_labels}
    accuracy=session.run(accuracy,feed_dict=feed_accuracy)
    print("cost: {}, accuracy: {}".format(cost, accuracy))
    # TODO: Implement Function
    pass

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 = 128
keep_probability = 0.8

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 [17]:
"""
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())
    
    # 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:  cost: 2.2427592277526855, accuracy: 0.23539999127388
Epoch  2, CIFAR-10 Batch 1:  cost: 2.0407938957214355, accuracy: 0.31859999895095825
Epoch  3, CIFAR-10 Batch 1:  cost: 1.7320318222045898, accuracy: 0.3959999680519104
Epoch  4, CIFAR-10 Batch 1:  cost: 1.5132397413253784, accuracy: 0.44019997119903564
Epoch  5, CIFAR-10 Batch 1:  cost: 1.2091209888458252, accuracy: 0.4731999337673187
Epoch  6, CIFAR-10 Batch 1:  cost: 0.814053475856781, accuracy: 0.49699991941452026
Epoch  7, CIFAR-10 Batch 1:  cost: 0.7808919548988342, accuracy: 0.5031999349594116
Epoch  8, CIFAR-10 Batch 1:  cost: 0.6286003589630127, accuracy: 0.5001999139785767
Epoch  9, CIFAR-10 Batch 1:  cost: 0.4314364790916443, accuracy: 0.5175999402999878
Epoch 10, CIFAR-10 Batch 1:  cost: 0.3238156735897064, accuracy: 0.500999927520752
Epoch 11, CIFAR-10 Batch 1:  cost: 0.2920665442943573, accuracy: 0.507599949836731
Epoch 12, CIFAR-10 Batch 1:  cost: 0.2655963897705078, accuracy: 0.4771999716758728
Epoch 13, CIFAR-10 Batch 1:  cost: 0.2560829818248749, accuracy: 0.4771999716758728
Epoch 14, CIFAR-10 Batch 1:  cost: 0.16447794437408447, accuracy: 0.4899999797344208
Epoch 15, CIFAR-10 Batch 1:  cost: 0.0881958082318306, accuracy: 0.5097999572753906
Epoch 16, CIFAR-10 Batch 1:  cost: 0.10259144008159637, accuracy: 0.4949999451637268
Epoch 17, CIFAR-10 Batch 1:  cost: 0.06719682365655899, accuracy: 0.478799968957901
Epoch 18, CIFAR-10 Batch 1:  cost: 0.09344163537025452, accuracy: 0.4797999858856201
Epoch 19, CIFAR-10 Batch 1:  cost: 0.05060189589858055, accuracy: 0.4779999554157257
Epoch 20, CIFAR-10 Batch 1:  cost: 0.049525581300258636, accuracy: 0.4869999289512634
Epoch 21, CIFAR-10 Batch 1:  cost: 0.09222665429115295, accuracy: 0.45879995822906494
Epoch 22, CIFAR-10 Batch 1:  cost: 0.026742542162537575, accuracy: 0.5145999789237976
Epoch 23, CIFAR-10 Batch 1:  cost: 0.020737260580062866, accuracy: 0.4997999370098114
Epoch 24, CIFAR-10 Batch 1:  cost: 0.02879699505865574, accuracy: 0.5079999566078186
Epoch 25, CIFAR-10 Batch 1:  cost: 0.015805725008249283, accuracy: 0.5087999701499939
Epoch 26, CIFAR-10 Batch 1:  cost: 0.006757225841283798, accuracy: 0.5077999830245972
Epoch 27, CIFAR-10 Batch 1:  cost: 0.004478118382394314, accuracy: 0.5043999552726746
Epoch 28, CIFAR-10 Batch 1:  cost: 0.010608717799186707, accuracy: 0.4909999966621399
Epoch 29, CIFAR-10 Batch 1:  cost: 0.009836665354669094, accuracy: 0.5007999539375305
Epoch 30, CIFAR-10 Batch 1:  cost: 0.007746041752398014, accuracy: 0.5097999572753906
Epoch 31, CIFAR-10 Batch 1:  cost: 0.005519259721040726, accuracy: 0.5187999606132507
Epoch 32, CIFAR-10 Batch 1:  cost: 0.0025247205048799515, accuracy: 0.5265999436378479
Epoch 33, CIFAR-10 Batch 1:  cost: 0.001740502193570137, accuracy: 0.5101999640464783
Epoch 34, CIFAR-10 Batch 1:  cost: 0.0037106648087501526, accuracy: 0.5165999531745911
Epoch 35, CIFAR-10 Batch 1:  cost: 0.0038676345720887184, accuracy: 0.5179999470710754
Epoch 36, CIFAR-10 Batch 1:  cost: 0.0016435581492260098, accuracy: 0.5255999565124512
Epoch 37, CIFAR-10 Batch 1:  cost: 0.007996256463229656, accuracy: 0.517799973487854
Epoch 38, CIFAR-10 Batch 1:  cost: 0.0004892045981250703, accuracy: 0.512999951839447
Epoch 39, CIFAR-10 Batch 1:  cost: 0.003954113461077213, accuracy: 0.4919999837875366
Epoch 40, CIFAR-10 Batch 1:  cost: 0.0011836240300908685, accuracy: 0.5035999417304993
Epoch 41, CIFAR-10 Batch 1:  cost: 0.006655373610556126, accuracy: 0.509399950504303
Epoch 42, CIFAR-10 Batch 1:  cost: 0.0043088817037642, accuracy: 0.48579996824264526
Epoch 43, CIFAR-10 Batch 1:  cost: 0.00033569149672985077, accuracy: 0.49299997091293335
Epoch 44, CIFAR-10 Batch 1:  cost: 0.00035326191573403776, accuracy: 0.5163999795913696
Epoch 45, CIFAR-10 Batch 1:  cost: 0.0010419973405078053, accuracy: 0.5163999795913696
Epoch 46, CIFAR-10 Batch 1:  cost: 0.01871386356651783, accuracy: 0.5085999965667725
Epoch 47, CIFAR-10 Batch 1:  cost: 0.00498999934643507, accuracy: 0.5087999701499939
Epoch 48, CIFAR-10 Batch 1:  cost: 0.0007008588290773332, accuracy: 0.5023999810218811
Epoch 49, CIFAR-10 Batch 1:  cost: 0.0008769748383201659, accuracy: 0.5079998970031738
Epoch 50, CIFAR-10 Batch 1:  cost: 0.005240697413682938, accuracy: 0.5125999450683594

Fully Train the Model

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


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


Training...
Epoch  1, CIFAR-10 Batch 1:  cost: 2.1577045917510986, accuracy: 0.22699998319149017
Epoch  1, CIFAR-10 Batch 2:  cost: 1.8553059101104736, accuracy: 0.3667999804019928
Epoch  1, CIFAR-10 Batch 3:  cost: 1.185328722000122, accuracy: 0.4309999942779541
Epoch  1, CIFAR-10 Batch 4:  cost: 1.335034728050232, accuracy: 0.46599993109703064
Epoch  1, CIFAR-10 Batch 5:  cost: 1.5152300596237183, accuracy: 0.5008000135421753
Epoch  2, CIFAR-10 Batch 1:  cost: 1.5361875295639038, accuracy: 0.493399977684021
Epoch  2, CIFAR-10 Batch 2:  cost: 1.4216092824935913, accuracy: 0.49959999322891235
Epoch  2, CIFAR-10 Batch 3:  cost: 0.9435378313064575, accuracy: 0.5075998902320862
Epoch  2, CIFAR-10 Batch 4:  cost: 1.1588923931121826, accuracy: 0.5443999171257019
Epoch  2, CIFAR-10 Batch 5:  cost: 1.210066556930542, accuracy: 0.5591999292373657
Epoch  3, CIFAR-10 Batch 1:  cost: 1.2266242504119873, accuracy: 0.558199942111969
Epoch  3, CIFAR-10 Batch 2:  cost: 1.1010558605194092, accuracy: 0.5751999020576477
Epoch  3, CIFAR-10 Batch 3:  cost: 0.8246574401855469, accuracy: 0.5669999122619629
Epoch  3, CIFAR-10 Batch 4:  cost: 0.8768447637557983, accuracy: 0.5703999400138855
Epoch  3, CIFAR-10 Batch 5:  cost: 0.8577079772949219, accuracy: 0.5909999012947083
Epoch  4, CIFAR-10 Batch 1:  cost: 1.0247564315795898, accuracy: 0.5805999040603638
Epoch  4, CIFAR-10 Batch 2:  cost: 0.7762237787246704, accuracy: 0.590999960899353
Epoch  4, CIFAR-10 Batch 3:  cost: 0.6411420106887817, accuracy: 0.5787999033927917
Epoch  4, CIFAR-10 Batch 4:  cost: 0.6041019558906555, accuracy: 0.5917999148368835
Epoch  4, CIFAR-10 Batch 5:  cost: 0.5832586288452148, accuracy: 0.5751999020576477
Epoch  5, CIFAR-10 Batch 1:  cost: 0.7672988176345825, accuracy: 0.5899998545646667
Epoch  5, CIFAR-10 Batch 2:  cost: 0.5648606419563293, accuracy: 0.6103999614715576
Epoch  5, CIFAR-10 Batch 3:  cost: 0.4327095150947571, accuracy: 0.6253998875617981
Epoch  5, CIFAR-10 Batch 4:  cost: 0.4364103078842163, accuracy: 0.6013998985290527
Epoch  5, CIFAR-10 Batch 5:  cost: 0.41688111424446106, accuracy: 0.6065999269485474
Epoch  6, CIFAR-10 Batch 1:  cost: 0.5694918036460876, accuracy: 0.6115999221801758
Epoch  6, CIFAR-10 Batch 2:  cost: 0.41016045212745667, accuracy: 0.626599907875061
Epoch  6, CIFAR-10 Batch 3:  cost: 0.3373982608318329, accuracy: 0.6355998516082764
Epoch  6, CIFAR-10 Batch 4:  cost: 0.28107208013534546, accuracy: 0.6031998991966248
Epoch  6, CIFAR-10 Batch 5:  cost: 0.30643385648727417, accuracy: 0.6191998720169067
Epoch  7, CIFAR-10 Batch 1:  cost: 0.46811312437057495, accuracy: 0.6289999485015869
Epoch  7, CIFAR-10 Batch 2:  cost: 0.2759336531162262, accuracy: 0.6277998685836792
Epoch  7, CIFAR-10 Batch 3:  cost: 0.22321978211402893, accuracy: 0.6285998821258545
Epoch  7, CIFAR-10 Batch 4:  cost: 0.24690061807632446, accuracy: 0.6079999804496765
Epoch  7, CIFAR-10 Batch 5:  cost: 0.24275049567222595, accuracy: 0.6159999370574951
Epoch  8, CIFAR-10 Batch 1:  cost: 0.3672572672367096, accuracy: 0.6339998841285706
Epoch  8, CIFAR-10 Batch 2:  cost: 0.2716188430786133, accuracy: 0.6073999404907227
Epoch  8, CIFAR-10 Batch 3:  cost: 0.20684117078781128, accuracy: 0.6183998584747314
Epoch  8, CIFAR-10 Batch 4:  cost: 0.2469176948070526, accuracy: 0.624799907207489
Epoch  8, CIFAR-10 Batch 5:  cost: 0.1939978301525116, accuracy: 0.6043999195098877
Epoch  9, CIFAR-10 Batch 1:  cost: 0.308403342962265, accuracy: 0.6287998557090759
Epoch  9, CIFAR-10 Batch 2:  cost: 0.2030859738588333, accuracy: 0.6097999215126038
Epoch  9, CIFAR-10 Batch 3:  cost: 0.13345780968666077, accuracy: 0.6283998489379883
Epoch  9, CIFAR-10 Batch 4:  cost: 0.13862597942352295, accuracy: 0.6109999418258667
Epoch  9, CIFAR-10 Batch 5:  cost: 0.1095576360821724, accuracy: 0.6155998706817627
Epoch 10, CIFAR-10 Batch 1:  cost: 0.1539323329925537, accuracy: 0.6019999384880066
Epoch 10, CIFAR-10 Batch 2:  cost: 0.08014201372861862, accuracy: 0.601599931716919
Epoch 10, CIFAR-10 Batch 3:  cost: 0.11036597192287445, accuracy: 0.6041999459266663
Epoch 10, CIFAR-10 Batch 4:  cost: 0.08395636826753616, accuracy: 0.6101998686790466
Epoch 10, CIFAR-10 Batch 5:  cost: 0.06872741878032684, accuracy: 0.6073999404907227
Epoch 11, CIFAR-10 Batch 1:  cost: 0.09611861407756805, accuracy: 0.5955999493598938
Epoch 11, CIFAR-10 Batch 2:  cost: 0.07377795875072479, accuracy: 0.6135998964309692
Epoch 11, CIFAR-10 Batch 3:  cost: 0.044348377734422684, accuracy: 0.5999999046325684
Epoch 11, CIFAR-10 Batch 4:  cost: 0.08301176130771637, accuracy: 0.5997999310493469
Epoch 11, CIFAR-10 Batch 5:  cost: 0.0652611181139946, accuracy: 0.6183998584747314
Epoch 12, CIFAR-10 Batch 1:  cost: 0.13970255851745605, accuracy: 0.6137999296188354
Epoch 12, CIFAR-10 Batch 2:  cost: 0.05172976106405258, accuracy: 0.6009998917579651
Epoch 12, CIFAR-10 Batch 3:  cost: 0.060343027114868164, accuracy: 0.6119999289512634
Epoch 12, CIFAR-10 Batch 4:  cost: 0.07945269346237183, accuracy: 0.5989998579025269
Epoch 12, CIFAR-10 Batch 5:  cost: 0.04601128399372101, accuracy: 0.6191998720169067
Epoch 13, CIFAR-10 Batch 1:  cost: 0.055043287575244904, accuracy: 0.5935999155044556
Epoch 13, CIFAR-10 Batch 2:  cost: 0.042677875608205795, accuracy: 0.6077998876571655
Epoch 13, CIFAR-10 Batch 3:  cost: 0.07563374936580658, accuracy: 0.6073998808860779
Epoch 13, CIFAR-10 Batch 4:  cost: 0.033998191356658936, accuracy: 0.6073998808860779
Epoch 13, CIFAR-10 Batch 5:  cost: 0.04316549748182297, accuracy: 0.6261999011039734
Epoch 14, CIFAR-10 Batch 1:  cost: 0.04169583320617676, accuracy: 0.6133999228477478
Epoch 14, CIFAR-10 Batch 2:  cost: 0.03492669761180878, accuracy: 0.5945999026298523
Epoch 14, CIFAR-10 Batch 3:  cost: 0.025766003876924515, accuracy: 0.6067999601364136
Epoch 14, CIFAR-10 Batch 4:  cost: 0.01797674596309662, accuracy: 0.6157999038696289
Epoch 14, CIFAR-10 Batch 5:  cost: 0.03157922998070717, accuracy: 0.6123999357223511
Epoch 15, CIFAR-10 Batch 1:  cost: 0.058042000979185104, accuracy: 0.6147998571395874
Epoch 15, CIFAR-10 Batch 2:  cost: 0.04449928551912308, accuracy: 0.5893999338150024
Epoch 15, CIFAR-10 Batch 3:  cost: 0.019897522404789925, accuracy: 0.6063998937606812
Epoch 15, CIFAR-10 Batch 4:  cost: 0.04164574295282364, accuracy: 0.6121999025344849
Epoch 15, CIFAR-10 Batch 5:  cost: 0.013174875639379025, accuracy: 0.5909999012947083
Epoch 16, CIFAR-10 Batch 1:  cost: 0.05823980271816254, accuracy: 0.6017999649047852
Epoch 16, CIFAR-10 Batch 2:  cost: 0.030421216040849686, accuracy: 0.6069998741149902
Epoch 16, CIFAR-10 Batch 3:  cost: 0.015573360025882721, accuracy: 0.6115999221801758
Epoch 16, CIFAR-10 Batch 4:  cost: 0.007036426104605198, accuracy: 0.6237998604774475
Epoch 16, CIFAR-10 Batch 5:  cost: 0.022990519180893898, accuracy: 0.5883999466896057
Epoch 17, CIFAR-10 Batch 1:  cost: 0.07887937873601913, accuracy: 0.5779998898506165
Epoch 17, CIFAR-10 Batch 2:  cost: 0.05404641851782799, accuracy: 0.603399932384491
Epoch 17, CIFAR-10 Batch 3:  cost: 0.028374873101711273, accuracy: 0.6101999282836914
Epoch 17, CIFAR-10 Batch 4:  cost: 0.011594258248806, accuracy: 0.6175999045372009
Epoch 17, CIFAR-10 Batch 5:  cost: 0.05802008509635925, accuracy: 0.6317999362945557
Epoch 18, CIFAR-10 Batch 1:  cost: 0.06145978718996048, accuracy: 0.5909999012947083
Epoch 18, CIFAR-10 Batch 2:  cost: 0.010538389906287193, accuracy: 0.6167998313903809
Epoch 18, CIFAR-10 Batch 3:  cost: 0.004478453658521175, accuracy: 0.6193999648094177
Epoch 18, CIFAR-10 Batch 4:  cost: 0.03380636125802994, accuracy: 0.6173998713493347
Epoch 18, CIFAR-10 Batch 5:  cost: 0.03804902359843254, accuracy: 0.6157999038696289
Epoch 19, CIFAR-10 Batch 1:  cost: 0.051036983728408813, accuracy: 0.5927999019622803
Epoch 19, CIFAR-10 Batch 2:  cost: 0.0369950570166111, accuracy: 0.6011999249458313
Epoch 19, CIFAR-10 Batch 3:  cost: 0.0069273123517632484, accuracy: 0.6105998754501343
Epoch 19, CIFAR-10 Batch 4:  cost: 0.025020696222782135, accuracy: 0.6165999174118042
Epoch 19, CIFAR-10 Batch 5:  cost: 0.07283265143632889, accuracy: 0.5995998978614807
Epoch 20, CIFAR-10 Batch 1:  cost: 0.04530908912420273, accuracy: 0.5829999446868896
Epoch 20, CIFAR-10 Batch 2:  cost: 0.03978182002902031, accuracy: 0.5941998958587646
Epoch 20, CIFAR-10 Batch 3:  cost: 0.009484771639108658, accuracy: 0.6047998666763306
Epoch 20, CIFAR-10 Batch 4:  cost: 0.01113959215581417, accuracy: 0.6175999045372009
Epoch 20, CIFAR-10 Batch 5:  cost: 0.023597102612257004, accuracy: 0.6165999174118042
Epoch 21, CIFAR-10 Batch 1:  cost: 0.009411031380295753, accuracy: 0.5945999622344971
Epoch 21, CIFAR-10 Batch 2:  cost: 0.007450041826814413, accuracy: 0.5969999432563782
Epoch 21, CIFAR-10 Batch 3:  cost: 0.0335564911365509, accuracy: 0.621799886226654
Epoch 21, CIFAR-10 Batch 4:  cost: 0.020731991156935692, accuracy: 0.6179998517036438
Epoch 21, CIFAR-10 Batch 5:  cost: 0.005426616873592138, accuracy: 0.6171998977661133
Epoch 22, CIFAR-10 Batch 1:  cost: 0.023351941257715225, accuracy: 0.5781999826431274
Epoch 22, CIFAR-10 Batch 2:  cost: 0.005327652674168348, accuracy: 0.6091998815536499
Epoch 22, CIFAR-10 Batch 3:  cost: 0.005238404963165522, accuracy: 0.6239998936653137
Epoch 22, CIFAR-10 Batch 4:  cost: 0.02566584013402462, accuracy: 0.6203998327255249
Epoch 22, CIFAR-10 Batch 5:  cost: 0.008056036196649075, accuracy: 0.6151999235153198
Epoch 23, CIFAR-10 Batch 1:  cost: 0.008755801245570183, accuracy: 0.6035999059677124
Epoch 23, CIFAR-10 Batch 2:  cost: 0.004617597907781601, accuracy: 0.6119998693466187
Epoch 23, CIFAR-10 Batch 3:  cost: 0.0007012057467363775, accuracy: 0.629599928855896
Epoch 23, CIFAR-10 Batch 4:  cost: 0.009575764648616314, accuracy: 0.6089999675750732
Epoch 23, CIFAR-10 Batch 5:  cost: 0.006068243645131588, accuracy: 0.6141998767852783
Epoch 24, CIFAR-10 Batch 1:  cost: 0.005394535604864359, accuracy: 0.6263998746871948
Epoch 24, CIFAR-10 Batch 2:  cost: 0.009217049926519394, accuracy: 0.5989999771118164
Epoch 24, CIFAR-10 Batch 3:  cost: 0.03163521736860275, accuracy: 0.6165999174118042
Epoch 24, CIFAR-10 Batch 4:  cost: 0.005483903922140598, accuracy: 0.6059999465942383
Epoch 24, CIFAR-10 Batch 5:  cost: 0.004287637770175934, accuracy: 0.6177999377250671
Epoch 25, CIFAR-10 Batch 1:  cost: 0.0045296321623027325, accuracy: 0.6295998692512512
Epoch 25, CIFAR-10 Batch 2:  cost: 0.016914652660489082, accuracy: 0.6061998605728149
Epoch 25, CIFAR-10 Batch 3:  cost: 0.0038647018373012543, accuracy: 0.6207998991012573
Epoch 25, CIFAR-10 Batch 4:  cost: 0.01164703443646431, accuracy: 0.6203999519348145
Epoch 25, CIFAR-10 Batch 5:  cost: 0.006585775874555111, accuracy: 0.6233999133110046
Epoch 26, CIFAR-10 Batch 1:  cost: 0.0053392332047224045, accuracy: 0.6247999668121338
Epoch 26, CIFAR-10 Batch 2:  cost: 0.004564761649817228, accuracy: 0.6291999220848083
Epoch 26, CIFAR-10 Batch 3:  cost: 0.012729483656585217, accuracy: 0.6131998896598816
Epoch 26, CIFAR-10 Batch 4:  cost: 0.0033941688016057014, accuracy: 0.6129999160766602
Epoch 26, CIFAR-10 Batch 5:  cost: 0.0028707985766232014, accuracy: 0.6223999261856079
Epoch 27, CIFAR-10 Batch 1:  cost: 0.004663518629968166, accuracy: 0.6287997961044312
Epoch 27, CIFAR-10 Batch 2:  cost: 0.008320910856127739, accuracy: 0.6119998693466187
Epoch 27, CIFAR-10 Batch 3:  cost: 0.008085372857749462, accuracy: 0.6079999208450317
Epoch 27, CIFAR-10 Batch 4:  cost: 0.010323526337742805, accuracy: 0.6085999011993408
Epoch 27, CIFAR-10 Batch 5:  cost: 0.008647486567497253, accuracy: 0.6143999099731445
Epoch 28, CIFAR-10 Batch 1:  cost: 0.0052285268902778625, accuracy: 0.6249998807907104
Epoch 28, CIFAR-10 Batch 2:  cost: 0.016595037654042244, accuracy: 0.6107999682426453
Epoch 28, CIFAR-10 Batch 3:  cost: 0.039928581565618515, accuracy: 0.5947999358177185
Epoch 28, CIFAR-10 Batch 4:  cost: 0.0012717923382297158, accuracy: 0.6175999045372009
Epoch 28, CIFAR-10 Batch 5:  cost: 0.005400177091360092, accuracy: 0.60999995470047
Epoch 29, CIFAR-10 Batch 1:  cost: 0.007300837431102991, accuracy: 0.6223998665809631
Epoch 29, CIFAR-10 Batch 2:  cost: 0.0045577166602015495, accuracy: 0.6179999113082886
Epoch 29, CIFAR-10 Batch 3:  cost: 0.00017351508722640574, accuracy: 0.6183998584747314
Epoch 29, CIFAR-10 Batch 4:  cost: 0.0010406167712062597, accuracy: 0.6239999532699585
Epoch 29, CIFAR-10 Batch 5:  cost: 0.0012982290936633945, accuracy: 0.6249998807907104
Epoch 30, CIFAR-10 Batch 1:  cost: 0.007698424160480499, accuracy: 0.6285998821258545
Epoch 30, CIFAR-10 Batch 2:  cost: 0.013423893600702286, accuracy: 0.624799907207489
Epoch 30, CIFAR-10 Batch 3:  cost: 0.002527210395783186, accuracy: 0.6291998624801636
Epoch 30, CIFAR-10 Batch 4:  cost: 0.001594155328348279, accuracy: 0.6201999187469482
Epoch 30, CIFAR-10 Batch 5:  cost: 0.011002629064023495, accuracy: 0.6223998665809631
Epoch 31, CIFAR-10 Batch 1:  cost: 0.030007289722561836, accuracy: 0.6349998712539673
Epoch 31, CIFAR-10 Batch 2:  cost: 0.0041837915778160095, accuracy: 0.6289998888969421
Epoch 31, CIFAR-10 Batch 3:  cost: 0.0004901114152744412, accuracy: 0.6247998476028442
Epoch 31, CIFAR-10 Batch 4:  cost: 0.00381995877251029, accuracy: 0.6105998754501343
Epoch 31, CIFAR-10 Batch 5:  cost: 0.0621110200881958, accuracy: 0.629599928855896
Epoch 32, CIFAR-10 Batch 1:  cost: 0.009790724143385887, accuracy: 0.6197999715805054
Epoch 32, CIFAR-10 Batch 2:  cost: 0.0044875675812363625, accuracy: 0.6251999139785767
Epoch 32, CIFAR-10 Batch 3:  cost: 0.006956341210752726, accuracy: 0.6229998469352722
Epoch 32, CIFAR-10 Batch 4:  cost: 0.003582073375582695, accuracy: 0.6303999423980713
Epoch 32, CIFAR-10 Batch 5:  cost: 0.02179224230349064, accuracy: 0.6257999539375305
Epoch 33, CIFAR-10 Batch 1:  cost: 0.014364932663738728, accuracy: 0.627799928188324
Epoch 33, CIFAR-10 Batch 2:  cost: 0.0017498971428722143, accuracy: 0.6323999166488647
Epoch 33, CIFAR-10 Batch 3:  cost: 0.007830418646335602, accuracy: 0.6307998895645142
Epoch 33, CIFAR-10 Batch 4:  cost: 0.0008229986415244639, accuracy: 0.6257998943328857
Epoch 33, CIFAR-10 Batch 5:  cost: 0.0020233772229403257, accuracy: 0.6243998408317566
Epoch 34, CIFAR-10 Batch 1:  cost: 0.03129936754703522, accuracy: 0.6229999661445618
Epoch 34, CIFAR-10 Batch 2:  cost: 0.0009398132096976042, accuracy: 0.6273998618125916
Epoch 34, CIFAR-10 Batch 3:  cost: 0.0012669020798057318, accuracy: 0.6353998780250549
Epoch 34, CIFAR-10 Batch 4:  cost: 0.007432004902511835, accuracy: 0.6101999282836914
Epoch 34, CIFAR-10 Batch 5:  cost: 0.004531616345047951, accuracy: 0.6255999207496643
Epoch 35, CIFAR-10 Batch 1:  cost: 0.004230921156704426, accuracy: 0.6221998929977417
Epoch 35, CIFAR-10 Batch 2:  cost: 0.07397548109292984, accuracy: 0.6347998380661011
Epoch 35, CIFAR-10 Batch 3:  cost: 6.503323675133288e-05, accuracy: 0.624799907207489
Epoch 35, CIFAR-10 Batch 4:  cost: 0.013590904884040356, accuracy: 0.6139999032020569
Epoch 35, CIFAR-10 Batch 5:  cost: 0.00022839893063064665, accuracy: 0.6311999559402466
Epoch 36, CIFAR-10 Batch 1:  cost: 0.005046069156378508, accuracy: 0.631399929523468
Epoch 36, CIFAR-10 Batch 2:  cost: 0.01990058831870556, accuracy: 0.6231999397277832
Epoch 36, CIFAR-10 Batch 3:  cost: 4.195887959212996e-05, accuracy: 0.6207998991012573
Epoch 36, CIFAR-10 Batch 4:  cost: 0.0034273010678589344, accuracy: 0.6131998896598816
Epoch 36, CIFAR-10 Batch 5:  cost: 0.0021924497559666634, accuracy: 0.6285998821258545
Epoch 37, CIFAR-10 Batch 1:  cost: 0.002531130099669099, accuracy: 0.6263998746871948
Epoch 37, CIFAR-10 Batch 2:  cost: 0.0013037073658779263, accuracy: 0.6147998571395874
Epoch 37, CIFAR-10 Batch 3:  cost: 0.004399850964546204, accuracy: 0.6231999397277832
Epoch 37, CIFAR-10 Batch 4:  cost: 0.0020314238499850035, accuracy: 0.6079999804496765
Epoch 37, CIFAR-10 Batch 5:  cost: 0.009232969954609871, accuracy: 0.6175999045372009
Epoch 38, CIFAR-10 Batch 1:  cost: 0.0390099436044693, accuracy: 0.6233999133110046
Epoch 38, CIFAR-10 Batch 2:  cost: 0.026461567729711533, accuracy: 0.6061999201774597
Epoch 38, CIFAR-10 Batch 3:  cost: 0.0018046260811388493, accuracy: 0.6293998956680298
Epoch 38, CIFAR-10 Batch 4:  cost: 0.006921513006091118, accuracy: 0.6123999357223511
Epoch 38, CIFAR-10 Batch 5:  cost: 0.008765838108956814, accuracy: 0.6223998665809631
Epoch 39, CIFAR-10 Batch 1:  cost: 0.002604335779324174, accuracy: 0.6209998726844788
Epoch 39, CIFAR-10 Batch 2:  cost: 0.002801703754812479, accuracy: 0.6175999045372009
Epoch 39, CIFAR-10 Batch 3:  cost: 0.02952498383820057, accuracy: 0.6237998604774475
Epoch 39, CIFAR-10 Batch 4:  cost: 0.0029084132984280586, accuracy: 0.6227998733520508
Epoch 39, CIFAR-10 Batch 5:  cost: 0.00497039407491684, accuracy: 0.6259998679161072
Epoch 40, CIFAR-10 Batch 1:  cost: 0.013556763529777527, accuracy: 0.621199905872345
Epoch 40, CIFAR-10 Batch 2:  cost: 0.0005938446847721934, accuracy: 0.6129999160766602
Epoch 40, CIFAR-10 Batch 3:  cost: 0.000713881105184555, accuracy: 0.6159999966621399
Epoch 40, CIFAR-10 Batch 4:  cost: 0.010947632603347301, accuracy: 0.6163999438285828
Epoch 40, CIFAR-10 Batch 5:  cost: 0.0013138926587998867, accuracy: 0.6245998740196228
Epoch 41, CIFAR-10 Batch 1:  cost: 0.04483472555875778, accuracy: 0.6223999261856079
Epoch 41, CIFAR-10 Batch 2:  cost: 0.010956625454127789, accuracy: 0.6131998896598816
Epoch 41, CIFAR-10 Batch 3:  cost: 0.047943878918886185, accuracy: 0.6319999694824219
Epoch 41, CIFAR-10 Batch 4:  cost: 0.015929359942674637, accuracy: 0.6237999200820923
Epoch 41, CIFAR-10 Batch 5:  cost: 0.0029012730810791254, accuracy: 0.6239999532699585
Epoch 42, CIFAR-10 Batch 1:  cost: 6.019869397277944e-05, accuracy: 0.6269998550415039
Epoch 42, CIFAR-10 Batch 2:  cost: 0.0006532745901495218, accuracy: 0.6175998449325562
Epoch 42, CIFAR-10 Batch 3:  cost: 0.0016391578828915954, accuracy: 0.6353999376296997
Epoch 42, CIFAR-10 Batch 4:  cost: 0.00023581204004585743, accuracy: 0.6269998550415039
Epoch 42, CIFAR-10 Batch 5:  cost: 0.0003260978264734149, accuracy: 0.6305999159812927
Epoch 43, CIFAR-10 Batch 1:  cost: 0.00016996855265460908, accuracy: 0.6207998991012573
Epoch 43, CIFAR-10 Batch 2:  cost: 0.0003297037328593433, accuracy: 0.6101998686790466
Epoch 43, CIFAR-10 Batch 3:  cost: 0.001004625461064279, accuracy: 0.6373999118804932
Epoch 43, CIFAR-10 Batch 4:  cost: 0.03314555063843727, accuracy: 0.6281999349594116
Epoch 43, CIFAR-10 Batch 5:  cost: 0.019687896594405174, accuracy: 0.6221998929977417
Epoch 44, CIFAR-10 Batch 1:  cost: 0.0012551104882732034, accuracy: 0.624799907207489
Epoch 44, CIFAR-10 Batch 2:  cost: 0.06026959791779518, accuracy: 0.6191999912261963
Epoch 44, CIFAR-10 Batch 3:  cost: 0.00031173499883152544, accuracy: 0.6233999729156494
Epoch 44, CIFAR-10 Batch 4:  cost: 0.017508598044514656, accuracy: 0.6185998916625977
Epoch 44, CIFAR-10 Batch 5:  cost: 0.0002475846849847585, accuracy: 0.6401998996734619
Epoch 45, CIFAR-10 Batch 1:  cost: 0.002673554001376033, accuracy: 0.6287999153137207
Epoch 45, CIFAR-10 Batch 2:  cost: 0.008774878457188606, accuracy: 0.622999906539917
Epoch 45, CIFAR-10 Batch 3:  cost: 0.005959466099739075, accuracy: 0.6227999329566956
Epoch 45, CIFAR-10 Batch 4:  cost: 0.00014540020492859185, accuracy: 0.6245999336242676
Epoch 45, CIFAR-10 Batch 5:  cost: 0.003991786856204271, accuracy: 0.614599883556366
Epoch 46, CIFAR-10 Batch 1:  cost: 0.0051707131788134575, accuracy: 0.6281998753547668
Epoch 46, CIFAR-10 Batch 2:  cost: 0.0027993780095130205, accuracy: 0.6287999153137207
Epoch 46, CIFAR-10 Batch 3:  cost: 0.0028154635801911354, accuracy: 0.6179999113082886
Epoch 46, CIFAR-10 Batch 4:  cost: 0.0020988336764276028, accuracy: 0.6151999235153198
Epoch 46, CIFAR-10 Batch 5:  cost: 0.010349283926188946, accuracy: 0.6157999038696289
Epoch 47, CIFAR-10 Batch 1:  cost: 8.92731113708578e-05, accuracy: 0.6231999397277832
Epoch 47, CIFAR-10 Batch 2:  cost: 0.0043086581863462925, accuracy: 0.624799907207489
Epoch 47, CIFAR-10 Batch 3:  cost: 0.00033191434340551496, accuracy: 0.6177999377250671
Epoch 47, CIFAR-10 Batch 4:  cost: 0.038149818778038025, accuracy: 0.6209998726844788
Epoch 47, CIFAR-10 Batch 5:  cost: 0.02329256199300289, accuracy: 0.6165999174118042
Epoch 48, CIFAR-10 Batch 1:  cost: 0.00041117967339232564, accuracy: 0.6261999011039734
Epoch 48, CIFAR-10 Batch 2:  cost: 0.015473942272365093, accuracy: 0.6173999309539795
Epoch 48, CIFAR-10 Batch 3:  cost: 0.0019547813571989536, accuracy: 0.619999885559082
Epoch 48, CIFAR-10 Batch 4:  cost: 0.001372717902995646, accuracy: 0.6287999153137207
Epoch 48, CIFAR-10 Batch 5:  cost: 0.0007431823178194463, accuracy: 0.6341999173164368
Epoch 49, CIFAR-10 Batch 1:  cost: 0.0014950222102925181, accuracy: 0.6223999261856079
Epoch 49, CIFAR-10 Batch 2:  cost: 0.010539512149989605, accuracy: 0.629599928855896
Epoch 49, CIFAR-10 Batch 3:  cost: 0.009301828220486641, accuracy: 0.6209999322891235
Epoch 49, CIFAR-10 Batch 4:  cost: 0.018536709249019623, accuracy: 0.6293998956680298
Epoch 49, CIFAR-10 Batch 5:  cost: 0.039297107607126236, accuracy: 0.6283999085426331
Epoch 50, CIFAR-10 Batch 1:  cost: 3.9261918573174626e-05, accuracy: 0.621199905872345
Epoch 50, CIFAR-10 Batch 2:  cost: 0.0018018262926489115, accuracy: 0.6271998882293701
Epoch 50, CIFAR-10 Batch 3:  cost: 0.00013064692029729486, accuracy: 0.6213999390602112
Epoch 50, CIFAR-10 Batch 4:  cost: 0.0022040128242224455, accuracy: 0.6367999315261841
Epoch 50, CIFAR-10 Batch 5:  cost: 0.0012439591810107231, accuracy: 0.6197998523712158

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 [12]:
"""
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_test.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 test_feature_batch, test_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: test_feature_batch, loaded_y: test_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.6222310126582279

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.