MSDS458 Research Assignment 02 - Part 1¶

More Technical: Throughout the notebook. This types of boxes provide more technical details and extra references about what you are seeing. They contain helpful tips, but you can safely skip them the first time you run through the code.

The CIFAR-10 dataset (Canadian Institute For Advanced Research) is a collection of images that are commonly used to train machine learning and computer vision algorithms. It is one of the most widely used datasets for machine learning research. The CIFAR-10 dataset contains 60,000 32x32 color images in 10 different classes. The 10 different classes represent airplanes, cars, birds, cats, deer, dogs, frogs, horses, ships, and trucks. There are 6,000 images of each class.

The CIFAR-10 dataset
https://www.cs.toronto.edu/~kriz/cifar.html

Imports¶

In [41]:
import numpy as np
import pandas as pd
from packaging import version

from sklearn.metrics import confusion_matrix, classification_report
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_squared_error as MSE
from sklearn.model_selection import train_test_split

import matplotlib.pyplot as plt
import seaborn as sns

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import models, layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPool2D, BatchNormalization, Dropout, Flatten, Dense
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from tensorflow.keras.preprocessing import image
from tensorflow.keras.utils import to_categorical
In [42]:
%matplotlib inline
np.set_printoptions(precision=3, suppress=True)

Verify TensorFlow Version and Keras Version¶

In [43]:
print("This notebook requires TensorFlow 2.0 or above")
print("TensorFlow version: ", tf.__version__)
assert version.parse(tf.__version__).release[0] >=2
This notebook requires TensorFlow 2.0 or above
TensorFlow version:  2.10.0
In [44]:
print("Keras version: ", keras.__version__)
Keras version:  2.10.0

Mount Google Drive to Colab Environment¶

In [45]:
# from google.colab import drive
# drive.mount('/content/gdrive')

EDA Functions¶

In [46]:
def get_three_classes(x, y):
    def indices_of(class_id):
        indices, _ = np.where(y == float(class_id))
        return indices

    indices = np.concatenate([indices_of(0), indices_of(1), indices_of(2)], axis=0)
    
    x = x[indices]
    y = y[indices]
    
    count = x.shape[0]
    indices = np.random.choice(range(count), count, replace=False)
    
    x = x[indices]
    y = y[indices]
    
    y = tf.keras.utils.to_categorical(y)
    
    return x, y
In [47]:
def show_random_examples(x, y, p):
    indices = np.random.choice(range(x.shape[0]), 10, replace=False)
    
    x = x[indices]
    y = y[indices]
    p = p[indices]
    
    plt.figure(figsize=(10, 5))
    for i in range(10):
        plt.subplot(2, 5, i + 1)
        plt.imshow(x[i])
        plt.xticks([])
        plt.yticks([])
        col = 'green' if np.argmax(y[i]) == np.argmax(p[i]) else 'red'
        plt.xlabel(class_names_preview[np.argmax(p[i])], color=col)
    plt.show()

Research Assignment Reporting Functions¶

In [48]:
def plot_history(history):
  losses = history.history['loss']
  accs = history.history['accuracy']
  val_losses = history.history['val_loss']
  val_accs = history.history['val_accuracy']
  epochs = len(losses)

  plt.figure(figsize=(16, 4))
  for i, metrics in enumerate(zip([losses, accs], [val_losses, val_accs], ['Loss', 'Accuracy'])):
    plt.subplot(1, 2, i + 1)
    plt.plot(range(epochs), metrics[0], label='Training {}'.format(metrics[2]))
    plt.plot(range(epochs), metrics[1], label='Validation {}'.format(metrics[2]))
    plt.legend()
  plt.show()
In [49]:
def print_validation_report(y_test, predictions):
    print("Classification Report")
    print(classification_report(y_test, predictions))
    print('Accuracy Score: {}'.format(accuracy_score(y_test, predictions)))
    print('Root Mean Square Error: {}'.format(np.sqrt(MSE(y_test, predictions)))) 
In [50]:
def plot_confusion_matrix(y_true, y_pred):
    mtx = confusion_matrix(y_true, y_pred)
    fig, ax = plt.subplots(figsize=(8,8))
    sns.heatmap(mtx, annot=True, fmt='d', linewidths=.75,  cbar=False, ax=ax,cmap='Blues',linecolor='white')
    #  square=True,
    plt.ylabel('true label')
    plt.xlabel('predicted label')

Loading cifar10 Dataset¶

The CIFAR-10 dataset consists of 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images.

The dataset is divided into five training batches and one test batch, each with 10000 images. The test batch contains exactly 1000 randomly-selected images from each class. The training batches contain the remaining images in random order, but some training batches may contain more images from one class than another. Between them, the training batches contain exactly 5000 images from each class.

In [51]:
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
  • Tuple of Numpy arrays: (x_train, y_train), (x_test, y_test).
  • x_train, x_test: uint8 arrays of color image data with shapes (num_samples, 32, 32).
  • y_train, y_test: uint8 arrays of digit labels (integers in range 0-9)

EDA Training and Test Datasets¶

  • Imported 50000 examples for training and 10000 examples for test
  • Imported 50000 labels for training and 10000 labels for test
In [52]:
print('train_images:\t{}'.format(x_train.shape))
print('train_labels:\t{}'.format(y_train.shape))
print('test_images:\t\t{}'.format(x_test.shape))
print('test_labels:\t\t{}'.format(y_test.shape))
train_images:	(50000, 32, 32, 3)
train_labels:	(50000, 1)
test_images:		(10000, 32, 32, 3)
test_labels:		(10000, 1)

Review Labels¶

In [53]:
print("First ten labels training dataset:\n {}\n".format(y_train[0:10]))
print("This output the numeric label, need to convert to item description")
First ten labels training dataset:
 [[6]
 [9]
 [9]
 [4]
 [1]
 [1]
 [2]
 [7]
 [8]
 [3]]

This output the numeric label, need to convert to item description

Plot Subset of Examples¶

In [54]:
(train_images, train_labels),(test_images, test_labels)= tf.keras.datasets.cifar10.load_data()
In [55]:
x_preview, y_preview = get_three_classes(train_images, train_labels)
x_preview, y_preview = get_three_classes(test_images, test_labels)
In [56]:
class_names_preview = ['aeroplane', 'car', 'bird']

show_random_examples(x_preview, y_preview, y_preview)

Preprocessing Data for Model Development¶

The labels are an array of integers, ranging from 0 to 9. These correspond to the class of clothing the image represents:

Label Class_
0 airplane
1 automobile
2 bird
3 cat
4 deer
5 dog
6 frog
7 horse
8 ship
9 truck
In [57]:
class_names = ['airplane'
,'automobile'
,'bird'
,'cat'
,'deer'
,'dog'
,'frog' 
,'horse'
,'ship'
,'truck']

Create Validation Data Set¶

In [58]:
x_train_split, x_valid_split, y_train_split, y_valid_split = train_test_split(x_train
                                                                              ,y_train
                                                                              ,test_size=.1
                                                                              ,random_state=42
                                                                              ,shuffle=True)

Confirm Datasets {Train, Validation, Test}¶

In [59]:
print(x_train_split.shape, x_valid_split.shape, x_test.shape)
(45000, 32, 32, 3) (5000, 32, 32, 3) (10000, 32, 32, 3)

Rescale Examples {Train, Validation, Test}¶

The images are 28x28 NumPy arrays, with pixel values ranging from 0 to 255

  1. Each element in each example is a pixel value
  2. Pixel values range from 0 to 255
  3. 0 = black
  4. 255 = white
In [60]:
x_train_norm = x_train_split/255
x_valid_norm = x_valid_split/255
x_test_norm = x_test/255

Create the Model¶

Build DNN Model¶

We use a Sequential class defined in Keras to create our model. The last layer is for classification to each of the 10 images.

In [61]:
model = Sequential([
  Flatten(input_shape=x_train_norm.shape[1:]),
  Dense(units=2000,activation=tf.nn.softmax),
  Dropout(0.3),
  Dense(units=2000,activation=tf.nn.softmax),
  Dropout(0.3),
  Dense(units=2000,activation=tf.nn.softmax),
  Dropout(0.3),
  Dense(units=10, activation=tf.nn.softmax)       
])
In [62]:
model.summary()
Model: "sequential_2"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 flatten_2 (Flatten)         (None, 3072)              0         
                                                                 
 dense_8 (Dense)             (None, 2000)              6146000   
                                                                 
 dropout (Dropout)           (None, 2000)              0         
                                                                 
 dense_9 (Dense)             (None, 2000)              4002000   
                                                                 
 dropout_1 (Dropout)         (None, 2000)              0         
                                                                 
 dense_10 (Dense)            (None, 2000)              4002000   
                                                                 
 dropout_2 (Dropout)         (None, 2000)              0         
                                                                 
 dense_11 (Dense)            (None, 10)                20010     
                                                                 
=================================================================
Total params: 14,170,010
Trainable params: 14,170,010
Non-trainable params: 0
_________________________________________________________________
In [63]:
keras.utils.plot_model(model, "CIFAR10.png", show_shapes=True) 
You must install pydot (`pip install pydot`) and install graphviz (see instructions at https://graphviz.gitlab.io/download/) for plot_model to work.

Compiling the model¶

In addition to setting up our model architecture, we also need to define which algorithm should the model use in order to optimize the weights and biases as per the given data. We will use stochastic gradient descent.

We also need to define a loss function. Think of this function as the difference between the predicted outputs and the actual outputs given in the dataset. This loss needs to be minimised in order to have a higher model accuracy. That's what the optimization algorithm essentially does - it minimises the loss during model training. For our multi-class classification problem, categorical cross entropy is commonly used.

Finally, we will use the accuracy during training as a metric to keep track of as the model trains.

tf.keras.losses.SparseCategoricalCrossentropy
https://www.tensorflow.org/api_docs/python/tf/keras/losses/SparseCategoricalCrossentropy
In [64]:
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['accuracy'])

Training the model¶

Module: tf.keras.callbacks
tf.keras.callbacks.EarlyStopping
https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/EarlyStopping
tf.keras.callbacks.ModelCheckpoint
https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint
In [65]:
history = model.fit(x_train_norm
                    ,y_train_split
                    ,epochs=200
                    ,batch_size=64
                    ,validation_data=(x_valid_norm, y_valid_split)
                    ,callbacks=[
                     tf.keras.callbacks.ModelCheckpoint("CNN_model.h5",save_best_only=True,save_weights_only=False) 
                     ,tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=3),
                    ]                                                                                                           
                   )
Epoch 1/200
704/704 [==============================] - 200s 269ms/step - loss: 2.3028 - accuracy: 0.0980 - val_loss: 2.3026 - val_accuracy: 0.1006
Epoch 2/200
704/704 [==============================] - 178s 253ms/step - loss: 2.3028 - accuracy: 0.1000 - val_loss: 2.3025 - val_accuracy: 0.1000
Epoch 3/200
704/704 [==============================] - 154s 219ms/step - loss: 2.3028 - accuracy: 0.0982 - val_loss: 2.3027 - val_accuracy: 0.1018
Epoch 4/200
704/704 [==============================] - 122s 174ms/step - loss: 2.3028 - accuracy: 0.0975 - val_loss: 2.3026 - val_accuracy: 0.0974
Epoch 6/200
704/704 [==============================] - 125s 178ms/step - loss: 2.3028 - accuracy: 0.0998 - val_loss: 2.3031 - val_accuracy: 0.0970

Evaluate the model¶

In order to ensure that this is not a simple "memorization" by the machine, we should evaluate the performance on the test set. This is easy to do, we simply use the evaluate method on our model.

In [66]:
model = tf.keras.models.load_model("CNN_model.h5")
print(f"Test acc: {model.evaluate(x_test_norm, y_test)[1]:.3f}")
313/313 [==============================] - 7s 19ms/step - loss: 1.9890 - accuracy: 0.2390
Test acc: 0.239

Predictions¶

In [ ]:
preds = model.predict(x_test_norm)
print('shape of preds: ', preds.shape)
247/313 [======================>.......] - ETA: 1s

Plotting Performance Metrics¶

We use Matplotlib to create 2 plots--displaying the training and validation loss (resp. accuracy) for each (training) epoch side by side.

In [ ]:
history_dict = history.history
history_dict.keys()
In [ ]:
history_df=pd.DataFrame(history_dict)
history_df.tail().round(3)

Plot Training Metrics (Loss and Accuracy)¶

In [ ]:
plot_history(history)

Confusion matrices¶

Using both sklearn.metrics. Then we visualize the confusion matrix and see what that tells us.

In [ ]:
pred1= model.predict(x_test_norm)
pred1=np.argmax(pred1, axis=1)
In [ ]:
print_validation_report(y_test, pred1)
In [ ]:
plot_confusion_matrix(y_test,pred1)

Load HDF5 Model Format¶

tf.keras.models.load_model
https://www.tensorflow.org/api_docs/python/tf/keras/models/load_model
In [ ]:
model = tf.keras.models.load_model('CNN_model.h5')
In [ ]:
preds = model.predict(x_test_norm)
In [ ]:
preds.shape

Predictions¶

In [ ]:
cm = sns.light_palette((260, 75, 60), input="husl", as_cmap=True)
In [ ]:
df = pd.DataFrame(preds[0:20], columns = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'])
df.style.format("{:.2%}").background_gradient(cmap=cm)