Deep Learning

Practice Projects

P2: Multi-Label Classification

Step 0. Style and Libraries

Let's choose a style of the Jupyter notebook and import the software libraries. The command hide_code will hide the code cells.

In [4]:
%%html
<style>
@import url('https://fonts.googleapis.com/css?family=Orbitron|Roboto');
body {background-color: aliceblue;} 
a {color: #4876ff; font-family: 'Roboto';} 
h1 {color: #348ABD; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #ccc;} 
h2, h3 {color: slategray; font-family: 'Roboto'; text-shadow: 4px 4px 4px #ccc;}
h4 {color: #348ABD; font-family: 'Orbitron';}
span {text-shadow: 4px 4px 4px #ccc;}
div.output_prompt, div.output_area pre {color: slategray;}
div.input_prompt, div.output_subarea {color: #4876ff;}      
div.output_stderr pre {background-color: aliceblue;}  
div.output_stderr {background-color: slategrey;}                        
</style>
<script>
code_show = true; 
function code_display() {
    if (code_show) {
        $('div.input').each(function(id) {
            if (id == 0 || $(this).html().indexOf('hide_code') > -1) {$(this).hide();}
        });
        $('div.output_prompt').css('opacity', 0);
    } else {
        $('div.input').each(function(id) {$(this).show();});
        $('div.output_prompt').css('opacity', 1);
    };
    code_show = !code_show;
} 
$(document).ready(code_display);
</script>
<form action="javascript: code_display()">
<input style="color: #348ABD; background: aliceblue; opacity: 0.8;" \ 
type="submit" value="Click to display or hide code cells">
</form>                  
In [36]:
hide_code = ''
import numpy as np 
import pandas as pd
import tensorflow as tf

from PIL import ImageFile
from tqdm import tqdm
import h5py
import cv2

import matplotlib.pylab as plt
from matplotlib import cm
%matplotlib inline

import warnings
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore",category=DeprecationWarning)

from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier

from keras.utils import to_categorical
from keras.preprocessing import image as keras_image
from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau
from keras.preprocessing.image import ImageDataGenerator

from keras.models import Sequential, load_model, Model
from keras.layers import Input, BatchNormalization
from keras.layers import Dense, LSTM, GlobalAveragePooling1D, GlobalAveragePooling2D
from keras.layers import Activation, Flatten, Dropout, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D, GlobalMaxPooling2D
from keras.layers.advanced_activations import PReLU, LeakyReLU

from keras.applications.vgg16 import VGG16, preprocess_input
import scipy
from scipy import misc
In [2]:
hide_code
# Plot the neural network fitting history
def history_plot(fit_history, n):
    plt.figure(figsize=(18, 12))
    
    plt.subplot(211)
    plt.plot(fit_history.history['loss'][n:], color='slategray', label = 'train')
    plt.plot(fit_history.history['val_loss'][n:], color='#4876ff', label = 'valid')
    plt.xlabel("Epochs")
    plt.ylabel("Loss")
    plt.legend()
    plt.title('Loss Function');  
    
    plt.subplot(212)
    plt.plot(fit_history.history['acc'][n:], color='slategray', label = 'train')
    plt.plot(fit_history.history['val_acc'][n:], color='#4876ff', label = 'valid')
    plt.xlabel("Epochs")
    plt.ylabel("Accuracy")    
    plt.legend()
    plt.title('Accuracy');

Step 1. Load and Explore the Data

For this project, I have created two datasets of color images (32x32x3) with 33 handwritten letters.

Run the following cells to download the data.

In [3]:
hide_code
# Function for processing an image
def image_to_tensor(img_path, folder_path):
    img = keras_image.load_img(folder_path + img_path, target_size=(32, 32))
    x = keras_image.img_to_array(img)
    return np.expand_dims(x, axis=0)
# Function for creating the data tensor
def data_to_tensor(img_paths, folder_path):
    list_of_tensors = [image_to_tensor(img_path, folder_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)
ImageFile.LOAD_TRUNCATED_IMAGES = True 
In [4]:
hide_code
# Load the dataset #1
data = pd.read_csv("data/letters.csv")
files = data['file']
letters = data['letter']
backgrounds = data['background'].values
targets = data['label'].values
tensors = data_to_tensor(files, "data/");
100%|██████████| 1650/1650 [00:30<00:00, 54.82it/s]
In [5]:
hide_code
# Load the dataset #2
data2 = pd.read_csv("data2/letters2.csv")
files2 = data2['file']
letters2 = data2['letter']
backgrounds2 = data2['background'].values
targets2 = data2['label'].values
tensors2 = data_to_tensor(files2, "data2/");
100%|██████████| 5940/5940 [02:14<00:00, 44.20it/s]
In [6]:
hide_code
# Load the dataset #3
data3 = pd.read_csv("data3/letters3.csv")
files3 = data3['file']
letters3 = data3['letter']
backgrounds3 = data3['background'].values
targets3 = data3['label'].values
tensors3 = data_to_tensor(files3, "data3/");
100%|██████████| 6600/6600 [02:36<00:00, 42.14it/s]
In [7]:
hide_code
# Print the shape 
print ('Tensor #1 shape:', tensors.shape)
print ('Target #1 shape', targets.shape)
print ('Tensor #2 shape:', tensors2.shape)
print ('Target #2 shape', targets2.shape)
print ('Tensor #3 shape:', tensors3.shape)
print ('Target #3 shape', targets3.shape)
Tensor #1 shape: (1650, 32, 32, 3)
Target #1 shape (1650,)
Tensor #2 shape: (5940, 32, 32, 3)
Target #2 shape (5940,)
Tensor #3 shape: (6600, 32, 32, 3)
Target #3 shape (6600,)
In [8]:
hide_code
# Concatenate arrays
tensors = np.concatenate((tensors, tensors2), axis=0)
targets = np.concatenate((targets, targets2), axis=0)
backgrounds = np.concatenate((backgrounds, backgrounds2), axis=0)
print ('Tensor shape:', tensors.shape)
print ('Target shape', targets.shape)
print ('Background shape:', backgrounds.shape)
Tensor shape: (7590, 32, 32, 3)
Target shape (7590,)
Background shape: (7590,)
In [9]:
hide_code
# Concatenate arrays
tensors = np.concatenate((tensors, tensors3), axis=0)
targets = np.concatenate((targets, targets3), axis=0)
backgrounds = np.concatenate((backgrounds, backgrounds3), axis=0)
print ('Tensor shape:', tensors.shape)
print ('Target shape', targets.shape)
print ('Background shape:', backgrounds.shape)
Tensor shape: (14190, 32, 32, 3)
Target shape (14190,)
Background shape: (14190,)
In [10]:
hide_code
# Concatenate series
letters = pd.concat((letters, letters2), axis=0, ignore_index=True)
letters = pd.concat((letters, letters3), axis=0, ignore_index=True)
len(letters)
Out[10]:
14190
In [11]:
hide_code
# Read from files and display images using OpenCV
def display_images(img_path, ax):
    img = cv2.imread("data2/" + img_path)
    ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    
fig = plt.figure(figsize=(18, 6))
for i in range(12):
    ax = fig.add_subplot(2, 6, i + 1, xticks=[], yticks=[], title=letters2[i*180])
    display_images(files2[i*180], ax)
In [12]:
hide_code
# Read from files and display images using OpenCV
def display_images(img_path, ax):
    img = cv2.imread("data3/" + img_path)
    ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    
fig = plt.figure(figsize=(18, 6))
for i in range(12):
    ax = fig.add_subplot(2, 6, i + 1, xticks=[], yticks=[], title=letters3[i*200])
    display_images(files3[i*200], ax)

Step 2. Save and Load the Data

The data tensors can be saved in the appropriate format of files .h5.

In [15]:
hide_code
# Create the tensor file
with h5py.File('LetterColorImages_123.h5', 'w') as f:
    f.create_dataset('images', data = tensors)
    f.create_dataset('labels', data = targets)
    f.create_dataset('backgrounds', data = backgrounds)
    f.close()
In [16]:
hide_code
# Create the tensor file
with h5py.File('LetterColorImages3.h5', 'w') as f:
    f.create_dataset('images', data = tensors3)
    f.create_dataset('labels', data = targets3)
    f.create_dataset('backgrounds', data = backgrounds3)
    f.close()
In [17]:
hide_code
# Read the h5 file
f = h5py.File('LetterColorImages_123.h5', 'r')

# List all groups
keys = list(f.keys())
keys
Out[17]:
['backgrounds', 'images', 'labels']
In [18]:
hide_code
# Create tensors and targets
backgrounds = np.array(f[keys[0]])
tensors = np.array(f[keys[1]])
targets = np.array(f[keys[2]])
print ('Tensor shape:', tensors.shape)
print ('Target shape', targets.shape)
print ('Background shape:', backgrounds.shape)
Tensor shape: (14190, 32, 32, 3)
Target shape (14190,)
Background shape: (14190,)
In [19]:
hide_code
# Create a csv file
images_csv = tensors.reshape(-1,32*32*3)
np.savetxt("letter_images.csv", images_csv, fmt='%i', delimiter=",")
In [20]:
hide_code
# Read the pandas dataframe from csv
data_images = pd.read_csv("letter_images.csv", header=None)
data_images.iloc[:10,:10]
Out[20]:
0 1 2 3 4 5 6 7 8 9
0 196 186 203 196 188 203 194 187 202 194
1 179 173 183 181 174 186 182 175 185 179
2 179 164 164 181 168 168 182 169 168 182
3 177 161 167 175 162 167 173 160 165 176
4 154 149 156 157 151 159 157 149 157 157
5 252 242 233 252 242 233 254 244 235 255
6 176 169 179 177 170 180 177 170 180 178
7 200 197 214 201 198 217 202 199 218 202
8 252 240 233 253 242 235 253 241 234 252
9 178 170 177 178 170 176 176 169 178 179
In [22]:
hide_code
# Read image tensors from the dataframe
tensors = data_images.values
tensors = tensors.reshape(14190,32,32,3)

Step 3. Implement Preprocess Functions

Normalize and Gray Scale

In the cell below, normalize the image tensors, and return them as a normalized Numpy array.

In [13]:
hide_code
# Normalize the tensors
tensors = tensors.astype('float32')/255
In [14]:
hide_code
# Read and display a tensor using Matplotlib
print('Label: ', letters[7500])
plt.figure(figsize=(3,3))
plt.imshow(tensors[7500]);
Label:  я

Create tensors of grayscaled images and display their shape.

In [15]:
hide_code
# Grayscaled tensors
gray_tensors = np.dot(tensors[...,:3], [0.299, 0.587, 0.114])
print ('Grayscaled Tensor shape:', gray_tensors.shape)
Grayscaled Tensor shape: (14190, 32, 32)
In [16]:
hide_code
# Read and display a grayscaled tensor using Matplotlib
print('Label: ', letters[7500])
plt.figure(figsize=(3,3))
plt.imshow(gray_tensors[7500], cmap=cm.bone);
Label:  я

One-hot encode

Now we'll implement the one-hot encoding function to_categorical.

In [17]:
hide_code
# Print the target unique values
print('backgrounds:', set(backgrounds))
print('targets:', set(targets))
backgrounds: {0, 1, 2, 3}
targets: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33}
In [18]:
hide_code
# One-hot encode the background targets
backgrounds = to_categorical(backgrounds, 4)
backgrounds.shape
Out[18]:
(14190, 4)
In [19]:
hide_code
# One-hot encode the targets, started from the zero label
cat_targets = to_categorical(np.array(targets-1), 33)
cat_targets.shape
Out[19]:
(14190, 33)

Add background

In [20]:
hide_code
# Create multi-label targets
back_targets = np.concatenate((cat_targets, backgrounds), axis=1)
back_targets.shape
Out[20]:
(14190, 37)

Split

Color Images

Apply the function train_test_split and split the data into training and testing sets.

Set up the size for the test set - 10% and for the validation set - 10%.

In [21]:
hide_code
# Split the data
x_train, x_test, y_train, y_test = train_test_split(tensors, cat_targets, 
                                                    test_size = 0.2, 
                                                    random_state = 1)
n = int(len(x_test)/2)
x_valid, y_valid = x_test[:n], y_test[:n]
x_test, y_test = x_test[n:], y_test[n:]
In [22]:
hide_code
# Print the shape
x_train.shape, x_valid.shape, x_test.shape, y_train.shape, y_valid.shape, y_test.shape
Out[22]:
((11352, 32, 32, 3),
 (1419, 32, 32, 3),
 (1419, 32, 32, 3),
 (11352, 33),
 (1419, 33),
 (1419, 33))

Grayscaled Images

In [23]:
hide_code
# Split the grayscaled data
x_train2, x_test2, y_train2, y_test2 = train_test_split(gray_tensors, cat_targets, 
                                                        test_size = 0.2, 
                                                        random_state = 1)
x_valid2, y_valid2 = x_test2[:n], y_test2[:n]
x_test2, y_test2 = x_test2[n:], y_test2[n:]
In [24]:
hide_code
# Reshape the grayscaled data
x_train2, x_test2, x_valid2 = \
x_train2.reshape(-1, 32, 32, 1), x_test2.reshape(-1, 32, 32, 1), x_valid2.reshape(-1, 32, 32, 1)
In [25]:
hide_code
# Print the shape
x_train2.shape, x_valid2.shape, x_test2.shape, y_train2.shape, y_valid2.shape, y_test2.shape
Out[25]:
((11352, 32, 32, 1),
 (1419, 32, 32, 1),
 (1419, 32, 32, 1),
 (11352, 33),
 (1419, 33),
 (1419, 33))
In [26]:
hide_code
# Convert images from grayscaled to RGB
x_train2_tensor = tf.image.grayscale_to_rgb(x_train2, name=None)
x_test2_tensor = tf.image.grayscale_to_rgb(x_test2, name=None)
x_valid2_tensor = tf.image.grayscale_to_rgb(x_valid2, name=None)
# Run tensorflow session
sess = tf.Session()
with sess.as_default():
    x_train2_color = x_train2_tensor.eval()
    x_test2_color = x_test2_tensor.eval()
    x_valid2_color = x_valid2_tensor.eval()
# Check the shape    
x_train2_color.shape, x_test2_color.shape, x_valid2_color.shape
Out[26]:
((11352, 32, 32, 3), (1419, 32, 32, 3), (1419, 32, 32, 3))

Multi-label targets, color images

In [27]:
hide_code
# Split with multi-label targets
x_train3, x_test3, y_train3, y_test3 = train_test_split(tensors, back_targets, 
                                                        test_size = 0.2, 
                                                        random_state = 1)
x_valid3, y_valid3 = x_test3[:n], y_test3[:n]
x_test3, y_test3 = x_test3[n:], y_test3[n:]
In [28]:
hide_code
# Print the shape
x_train3.shape, x_valid3.shape, x_test3.shape, y_train3.shape, y_valid3.shape, y_test3.shape
Out[28]:
((11352, 32, 32, 3),
 (1419, 32, 32, 3),
 (1419, 32, 32, 3),
 (11352, 37),
 (1419, 37),
 (1419, 37))
In [29]:
hide_code
# Create a list of targets
y_train3_list = [y_train3[:, :33], y_train3[:, 33:]]
y_test3_list = [y_test3[:, :33], y_valid3[:, 33:]]
y_valid3_list = [y_valid3[:, :33], y_valid3[:, 33:]]

Multi-label targets, grayscaled images

In [30]:
hide_code
# Split the grayscaled data
x_train4, x_test4, y_train4, y_test4 = train_test_split(gray_tensors, back_targets, 
                                                        test_size = 0.2, 
                                                        random_state = 1)
x_valid4, y_valid4 = x_test4[:n], y_test4[:n]
x_test4, y_test4 = x_test4[n:], y_test4[n:]
In [31]:
hide_code
# Reshape the grayscaled data
x_train4, x_test4, x_valid4 = \
x_train4.reshape(-1, 32, 32, 1), x_test4.reshape(-1, 32, 32, 1), x_valid4.reshape(-1, 32, 32, 1)
In [32]:
hide_code
# Print the shape
x_train4.shape, x_valid4.shape, x_test4.shape, y_train4.shape, y_valid4.shape, y_test4.shape
Out[32]:
((11352, 32, 32, 1),
 (1419, 32, 32, 1),
 (1419, 32, 32, 1),
 (11352, 37),
 (1419, 37),
 (1419, 37))
In [33]:
hide_code
# Create a list of targets
y_train4_list = [y_train4[:, :33], y_train4[:, 33:]]
y_test4_list = [y_test4[:, :33], y_test4[:, 33:]]
y_valid4_list = [y_valid4[:, :33], y_valid4[:, 33:]]

Step 4. Create a One-Label Classification Model

Color Images

Define a model architecture and compile the model for color images.

In [47]:
hide_code
def model():
    model = Sequential()
    # TODO: Define a model architecture

    model.add(Conv2D(32, (5, 5), padding='same', input_shape=x_train.shape[1:]))
    model.add(LeakyReLU(alpha=0.02))
    
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))

    model.add(Conv2D(196, (5, 5)))
    model.add(LeakyReLU(alpha=0.02))
    
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))

    model.add(GlobalMaxPooling2D())
    
    model.add(Dense(1024))
    model.add(LeakyReLU(alpha=0.02))
    model.add(Dropout(0.5)) 
    
    model.add(Dense(33))
    model.add(Activation('softmax'))
    
    # TODO: Compile the model
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    
    return model

model = model()
In [48]:
hide_code
# Create callbacks
checkpointer = ModelCheckpoint(filepath='weights.best.model.hdf5', 
                               verbose=2, save_best_only=True)
lr_reduction = ReduceLROnPlateau(monitor='val_loss', 
                                 patience=5, verbose=2, factor=0.5)
In [49]:
hide_code
# Train the model
history = model.fit(x_train, y_train, 
                    epochs=100, batch_size=64, verbose=2,
                    validation_data=(x_valid, y_valid),
                    callbacks=[checkpointer, lr_reduction])
Train on 11352 samples, validate on 1419 samples
Epoch 1/100
 - 80s - loss: 3.4902 - acc: 0.0334 - val_loss: 3.4656 - val_acc: 0.0324

Epoch 00001: val_loss improved from inf to 3.46558, saving model to weights.best.model.hdf5
Epoch 2/100
 - 83s - loss: 3.3618 - acc: 0.0632 - val_loss: 3.3205 - val_acc: 0.0726

Epoch 00002: val_loss improved from 3.46558 to 3.32055, saving model to weights.best.model.hdf5
Epoch 3/100
 - 66s - loss: 3.2348 - acc: 0.0785 - val_loss: 3.1811 - val_acc: 0.0853

Epoch 00003: val_loss improved from 3.32055 to 3.18108, saving model to weights.best.model.hdf5
Epoch 4/100
 - 65s - loss: 3.1557 - acc: 0.0814 - val_loss: 3.1800 - val_acc: 0.0916

Epoch 00004: val_loss improved from 3.18108 to 3.18000, saving model to weights.best.model.hdf5
Epoch 5/100
 - 66s - loss: 3.0939 - acc: 0.0921 - val_loss: 3.0863 - val_acc: 0.0902

Epoch 00005: val_loss improved from 3.18000 to 3.08626, saving model to weights.best.model.hdf5
Epoch 6/100
 - 63s - loss: 3.0717 - acc: 0.0945 - val_loss: 3.0391 - val_acc: 0.1043

Epoch 00006: val_loss improved from 3.08626 to 3.03911, saving model to weights.best.model.hdf5
Epoch 7/100
 - 64s - loss: 3.0485 - acc: 0.1003 - val_loss: 3.0674 - val_acc: 0.1029

Epoch 00007: val_loss did not improve from 3.03911
Epoch 8/100
 - 64s - loss: 3.0210 - acc: 0.1021 - val_loss: 2.9853 - val_acc: 0.1247

Epoch 00008: val_loss improved from 3.03911 to 2.98528, saving model to weights.best.model.hdf5
Epoch 9/100
 - 63s - loss: 2.9803 - acc: 0.1079 - val_loss: 2.9893 - val_acc: 0.1240

Epoch 00009: val_loss did not improve from 2.98528
Epoch 10/100
 - 63s - loss: 2.9504 - acc: 0.1173 - val_loss: 2.9121 - val_acc: 0.1325

Epoch 00010: val_loss improved from 2.98528 to 2.91214, saving model to weights.best.model.hdf5
Epoch 11/100
 - 64s - loss: 2.8839 - acc: 0.1272 - val_loss: 2.8436 - val_acc: 0.1522

Epoch 00011: val_loss improved from 2.91214 to 2.84358, saving model to weights.best.model.hdf5
Epoch 12/100
 - 63s - loss: 2.8095 - acc: 0.1496 - val_loss: 2.7002 - val_acc: 0.1952

Epoch 00012: val_loss improved from 2.84358 to 2.70021, saving model to weights.best.model.hdf5
Epoch 13/100
 - 65s - loss: 2.6800 - acc: 0.1804 - val_loss: 2.6096 - val_acc: 0.2241

Epoch 00013: val_loss improved from 2.70021 to 2.60965, saving model to weights.best.model.hdf5
Epoch 14/100
 - 69s - loss: 2.5773 - acc: 0.2134 - val_loss: 2.4587 - val_acc: 0.2636

Epoch 00014: val_loss improved from 2.60965 to 2.45871, saving model to weights.best.model.hdf5
Epoch 15/100
 - 66s - loss: 2.4195 - acc: 0.2545 - val_loss: 2.2839 - val_acc: 0.3058

Epoch 00015: val_loss improved from 2.45871 to 2.28393, saving model to weights.best.model.hdf5
Epoch 16/100
 - 67s - loss: 2.2425 - acc: 0.3088 - val_loss: 2.0716 - val_acc: 0.3883

Epoch 00016: val_loss improved from 2.28393 to 2.07160, saving model to weights.best.model.hdf5
Epoch 17/100
 - 66s - loss: 2.0736 - acc: 0.3501 - val_loss: 1.8509 - val_acc: 0.4602

Epoch 00017: val_loss improved from 2.07160 to 1.85087, saving model to weights.best.model.hdf5
Epoch 18/100
 - 70s - loss: 1.8796 - acc: 0.4151 - val_loss: 1.6854 - val_acc: 0.5032

Epoch 00018: val_loss improved from 1.85087 to 1.68537, saving model to weights.best.model.hdf5
Epoch 19/100
 - 68s - loss: 1.7563 - acc: 0.4533 - val_loss: 1.6600 - val_acc: 0.5095

Epoch 00019: val_loss improved from 1.68537 to 1.66004, saving model to weights.best.model.hdf5
Epoch 20/100
 - 68s - loss: 1.6383 - acc: 0.4851 - val_loss: 1.4401 - val_acc: 0.5729

Epoch 00020: val_loss improved from 1.66004 to 1.44006, saving model to weights.best.model.hdf5
Epoch 21/100
 - 67s - loss: 1.5436 - acc: 0.5163 - val_loss: 1.4748 - val_acc: 0.5856

Epoch 00021: val_loss did not improve from 1.44006
Epoch 22/100
 - 66s - loss: 1.4594 - acc: 0.5425 - val_loss: 1.3825 - val_acc: 0.6124

Epoch 00022: val_loss improved from 1.44006 to 1.38253, saving model to weights.best.model.hdf5
Epoch 23/100
 - 67s - loss: 1.3981 - acc: 0.5611 - val_loss: 1.1896 - val_acc: 0.6533

Epoch 00023: val_loss improved from 1.38253 to 1.18965, saving model to weights.best.model.hdf5
Epoch 24/100
 - 67s - loss: 1.2916 - acc: 0.5999 - val_loss: 1.1947 - val_acc: 0.6589

Epoch 00024: val_loss did not improve from 1.18965
Epoch 25/100
 - 68s - loss: 1.2444 - acc: 0.6127 - val_loss: 1.0528 - val_acc: 0.7068

Epoch 00025: val_loss improved from 1.18965 to 1.05276, saving model to weights.best.model.hdf5
Epoch 26/100
 - 66s - loss: 1.2077 - acc: 0.6239 - val_loss: 1.0353 - val_acc: 0.7047

Epoch 00026: val_loss improved from 1.05276 to 1.03530, saving model to weights.best.model.hdf5
Epoch 27/100
 - 67s - loss: 1.1445 - acc: 0.6433 - val_loss: 0.9916 - val_acc: 0.7223

Epoch 00027: val_loss improved from 1.03530 to 0.99156, saving model to weights.best.model.hdf5
Epoch 28/100
 - 66s - loss: 1.0933 - acc: 0.6628 - val_loss: 0.9405 - val_acc: 0.7195

Epoch 00028: val_loss improved from 0.99156 to 0.94050, saving model to weights.best.model.hdf5
Epoch 29/100
 - 66s - loss: 1.0342 - acc: 0.6769 - val_loss: 0.8425 - val_acc: 0.7738

Epoch 00029: val_loss improved from 0.94050 to 0.84246, saving model to weights.best.model.hdf5
Epoch 30/100
 - 67s - loss: 1.0045 - acc: 0.6810 - val_loss: 0.7911 - val_acc: 0.7829

Epoch 00030: val_loss improved from 0.84246 to 0.79115, saving model to weights.best.model.hdf5
Epoch 31/100
 - 68s - loss: 0.9233 - acc: 0.7072 - val_loss: 0.8281 - val_acc: 0.7625

Epoch 00031: val_loss did not improve from 0.79115
Epoch 32/100
 - 69s - loss: 0.9123 - acc: 0.7120 - val_loss: 0.7257 - val_acc: 0.7963

Epoch 00032: val_loss improved from 0.79115 to 0.72565, saving model to weights.best.model.hdf5
Epoch 33/100
 - 71s - loss: 0.8416 - acc: 0.7334 - val_loss: 0.6956 - val_acc: 0.8090

Epoch 00033: val_loss improved from 0.72565 to 0.69559, saving model to weights.best.model.hdf5
Epoch 34/100
 - 71s - loss: 0.8376 - acc: 0.7378 - val_loss: 0.7099 - val_acc: 0.7977

Epoch 00034: val_loss did not improve from 0.69559
Epoch 35/100
 - 68s - loss: 0.8066 - acc: 0.7426 - val_loss: 0.6504 - val_acc: 0.8161

Epoch 00035: val_loss improved from 0.69559 to 0.65037, saving model to weights.best.model.hdf5
Epoch 36/100
 - 66s - loss: 0.7947 - acc: 0.7536 - val_loss: 0.6361 - val_acc: 0.8175

Epoch 00036: val_loss improved from 0.65037 to 0.63610, saving model to weights.best.model.hdf5
Epoch 37/100
 - 67s - loss: 0.7641 - acc: 0.7585 - val_loss: 0.6223 - val_acc: 0.8323

Epoch 00037: val_loss improved from 0.63610 to 0.62229, saving model to weights.best.model.hdf5
Epoch 38/100
 - 67s - loss: 0.7267 - acc: 0.7673 - val_loss: 0.5761 - val_acc: 0.8393

Epoch 00038: val_loss improved from 0.62229 to 0.57606, saving model to weights.best.model.hdf5
Epoch 39/100
 - 67s - loss: 0.7325 - acc: 0.7696 - val_loss: 0.5882 - val_acc: 0.8224

Epoch 00039: val_loss did not improve from 0.57606
Epoch 40/100
 - 66s - loss: 0.7089 - acc: 0.7766 - val_loss: 0.5530 - val_acc: 0.8569

Epoch 00040: val_loss improved from 0.57606 to 0.55295, saving model to weights.best.model.hdf5
Epoch 41/100
 - 67s - loss: 0.6767 - acc: 0.7866 - val_loss: 0.6593 - val_acc: 0.8111

Epoch 00041: val_loss did not improve from 0.55295
Epoch 42/100
 - 67s - loss: 0.6486 - acc: 0.7927 - val_loss: 0.5024 - val_acc: 0.8584

Epoch 00042: val_loss improved from 0.55295 to 0.50235, saving model to weights.best.model.hdf5
Epoch 43/100
 - 67s - loss: 0.6660 - acc: 0.7860 - val_loss: 0.5471 - val_acc: 0.8400

Epoch 00043: val_loss did not improve from 0.50235
Epoch 44/100
 - 67s - loss: 0.6210 - acc: 0.7998 - val_loss: 0.5711 - val_acc: 0.8309

Epoch 00044: val_loss did not improve from 0.50235
Epoch 45/100
 - 67s - loss: 0.6247 - acc: 0.8007 - val_loss: 0.5325 - val_acc: 0.8513

Epoch 00045: val_loss did not improve from 0.50235
Epoch 46/100
 - 66s - loss: 0.5984 - acc: 0.8089 - val_loss: 0.4669 - val_acc: 0.8732

Epoch 00046: val_loss improved from 0.50235 to 0.46689, saving model to weights.best.model.hdf5
Epoch 47/100
 - 67s - loss: 0.5624 - acc: 0.8206 - val_loss: 0.4908 - val_acc: 0.8562

Epoch 00047: val_loss did not improve from 0.46689
Epoch 48/100
 - 67s - loss: 0.5594 - acc: 0.8224 - val_loss: 0.4504 - val_acc: 0.8795

Epoch 00048: val_loss improved from 0.46689 to 0.45044, saving model to weights.best.model.hdf5
Epoch 49/100
 - 67s - loss: 0.5569 - acc: 0.8222 - val_loss: 0.4356 - val_acc: 0.8781

Epoch 00049: val_loss improved from 0.45044 to 0.43555, saving model to weights.best.model.hdf5
Epoch 50/100
 - 69s - loss: 0.5500 - acc: 0.8238 - val_loss: 0.5336 - val_acc: 0.8344

Epoch 00050: val_loss did not improve from 0.43555
Epoch 51/100
 - 80s - loss: 0.5608 - acc: 0.8221 - val_loss: 0.4352 - val_acc: 0.8739

Epoch 00051: val_loss improved from 0.43555 to 0.43516, saving model to weights.best.model.hdf5
Epoch 52/100
 - 74s - loss: 0.5192 - acc: 0.8354 - val_loss: 0.4382 - val_acc: 0.8746

Epoch 00052: val_loss did not improve from 0.43516
Epoch 53/100
 - 67s - loss: 0.5107 - acc: 0.8384 - val_loss: 0.4516 - val_acc: 0.8774

Epoch 00053: val_loss did not improve from 0.43516
Epoch 54/100
 - 68s - loss: 0.5475 - acc: 0.8239 - val_loss: 0.4734 - val_acc: 0.8584

Epoch 00054: val_loss did not improve from 0.43516
Epoch 55/100
 - 69s - loss: 0.5068 - acc: 0.8396 - val_loss: 0.4168 - val_acc: 0.8837

Epoch 00055: val_loss improved from 0.43516 to 0.41684, saving model to weights.best.model.hdf5
Epoch 56/100
 - 69s - loss: 0.4904 - acc: 0.8436 - val_loss: 0.3994 - val_acc: 0.8894

Epoch 00056: val_loss improved from 0.41684 to 0.39936, saving model to weights.best.model.hdf5
Epoch 57/100
 - 69s - loss: 0.4857 - acc: 0.8454 - val_loss: 0.4893 - val_acc: 0.8562

Epoch 00057: val_loss did not improve from 0.39936
Epoch 58/100
 - 69s - loss: 0.4707 - acc: 0.8459 - val_loss: 0.4142 - val_acc: 0.8872

Epoch 00058: val_loss did not improve from 0.39936
Epoch 59/100
 - 69s - loss: 0.4728 - acc: 0.8446 - val_loss: 0.4003 - val_acc: 0.8830

Epoch 00059: val_loss did not improve from 0.39936
Epoch 60/100
 - 72s - loss: 0.4413 - acc: 0.8553 - val_loss: 0.4014 - val_acc: 0.8774

Epoch 00060: val_loss did not improve from 0.39936
Epoch 61/100
 - 69s - loss: 0.4538 - acc: 0.8532 - val_loss: 0.3807 - val_acc: 0.8858

Epoch 00061: val_loss improved from 0.39936 to 0.38071, saving model to weights.best.model.hdf5
Epoch 62/100
 - 68s - loss: 0.4476 - acc: 0.8526 - val_loss: 0.4476 - val_acc: 0.8598

Epoch 00062: val_loss did not improve from 0.38071
Epoch 63/100
 - 69s - loss: 0.4436 - acc: 0.8569 - val_loss: 0.4360 - val_acc: 0.8612

Epoch 00063: val_loss did not improve from 0.38071
Epoch 64/100
 - 69s - loss: 0.4540 - acc: 0.8560 - val_loss: 0.4551 - val_acc: 0.8661

Epoch 00064: val_loss did not improve from 0.38071
Epoch 65/100
 - 68s - loss: 0.4256 - acc: 0.8632 - val_loss: 0.4791 - val_acc: 0.8534

Epoch 00065: val_loss did not improve from 0.38071
Epoch 66/100
 - 69s - loss: 0.4219 - acc: 0.8607 - val_loss: 0.3995 - val_acc: 0.8823

Epoch 00066: val_loss did not improve from 0.38071

Epoch 00066: ReduceLROnPlateau reducing learning rate to 0.0005000000237487257.
Epoch 67/100
 - 68s - loss: 0.3473 - acc: 0.8902 - val_loss: 0.3191 - val_acc: 0.9154

Epoch 00067: val_loss improved from 0.38071 to 0.31909, saving model to weights.best.model.hdf5
Epoch 68/100
 - 69s - loss: 0.3227 - acc: 0.8929 - val_loss: 0.3123 - val_acc: 0.9077

Epoch 00068: val_loss improved from 0.31909 to 0.31234, saving model to weights.best.model.hdf5
Epoch 69/100
 - 70s - loss: 0.3247 - acc: 0.8953 - val_loss: 0.3222 - val_acc: 0.9112

Epoch 00069: val_loss did not improve from 0.31234
Epoch 70/100
 - 69s - loss: 0.3139 - acc: 0.8984 - val_loss: 0.3251 - val_acc: 0.9070

Epoch 00070: val_loss did not improve from 0.31234
Epoch 71/100
 - 69s - loss: 0.3278 - acc: 0.8908 - val_loss: 0.3291 - val_acc: 0.9049

Epoch 00071: val_loss did not improve from 0.31234
Epoch 72/100
 - 68s - loss: 0.3217 - acc: 0.8939 - val_loss: 0.3068 - val_acc: 0.9133

Epoch 00072: val_loss improved from 0.31234 to 0.30682, saving model to weights.best.model.hdf5
Epoch 73/100
 - 70s - loss: 0.3057 - acc: 0.9017 - val_loss: 0.3516 - val_acc: 0.8922

Epoch 00073: val_loss did not improve from 0.30682
Epoch 74/100
 - 69s - loss: 0.3027 - acc: 0.9025 - val_loss: 0.3201 - val_acc: 0.8999

Epoch 00074: val_loss did not improve from 0.30682
Epoch 75/100
 - 68s - loss: 0.2925 - acc: 0.9020 - val_loss: 0.3076 - val_acc: 0.9112

Epoch 00075: val_loss did not improve from 0.30682
Epoch 76/100
 - 69s - loss: 0.3110 - acc: 0.9011 - val_loss: 0.3310 - val_acc: 0.9056

Epoch 00076: val_loss did not improve from 0.30682
Epoch 77/100
 - 70s - loss: 0.3011 - acc: 0.9002 - val_loss: 0.3136 - val_acc: 0.9105

Epoch 00077: val_loss did not improve from 0.30682

Epoch 00077: ReduceLROnPlateau reducing learning rate to 0.0002500000118743628.
Epoch 78/100
 - 70s - loss: 0.2516 - acc: 0.9175 - val_loss: 0.2972 - val_acc: 0.9161

Epoch 00078: val_loss improved from 0.30682 to 0.29717, saving model to weights.best.model.hdf5
Epoch 79/100
 - 68s - loss: 0.2475 - acc: 0.9184 - val_loss: 0.3114 - val_acc: 0.9098

Epoch 00079: val_loss did not improve from 0.29717
Epoch 80/100
 - 69s - loss: 0.2524 - acc: 0.9159 - val_loss: 0.3044 - val_acc: 0.9154

Epoch 00080: val_loss did not improve from 0.29717
Epoch 81/100
 - 69s - loss: 0.2359 - acc: 0.9204 - val_loss: 0.2969 - val_acc: 0.9168

Epoch 00081: val_loss improved from 0.29717 to 0.29688, saving model to weights.best.model.hdf5
Epoch 82/100
 - 71s - loss: 0.2409 - acc: 0.9193 - val_loss: 0.3087 - val_acc: 0.9133

Epoch 00082: val_loss did not improve from 0.29688
Epoch 83/100
 - 69s - loss: 0.2506 - acc: 0.9188 - val_loss: 0.3111 - val_acc: 0.9119

Epoch 00083: val_loss did not improve from 0.29688
Epoch 84/100
 - 69s - loss: 0.2400 - acc: 0.9210 - val_loss: 0.2957 - val_acc: 0.9154

Epoch 00084: val_loss improved from 0.29688 to 0.29573, saving model to weights.best.model.hdf5
Epoch 85/100
 - 69s - loss: 0.2441 - acc: 0.9192 - val_loss: 0.2756 - val_acc: 0.9183

Epoch 00085: val_loss improved from 0.29573 to 0.27563, saving model to weights.best.model.hdf5
Epoch 86/100
 - 71s - loss: 0.2312 - acc: 0.9243 - val_loss: 0.2814 - val_acc: 0.9175

Epoch 00086: val_loss did not improve from 0.27563
Epoch 87/100
 - 69s - loss: 0.2339 - acc: 0.9239 - val_loss: 0.2839 - val_acc: 0.9161

Epoch 00087: val_loss did not improve from 0.27563
Epoch 88/100
 - 68s - loss: 0.2353 - acc: 0.9215 - val_loss: 0.2837 - val_acc: 0.9225

Epoch 00088: val_loss did not improve from 0.27563
Epoch 89/100
 - 70s - loss: 0.2235 - acc: 0.9265 - val_loss: 0.3060 - val_acc: 0.9126

Epoch 00089: val_loss did not improve from 0.27563
Epoch 90/100
 - 70s - loss: 0.2261 - acc: 0.9278 - val_loss: 0.2838 - val_acc: 0.9204

Epoch 00090: val_loss did not improve from 0.27563

Epoch 00090: ReduceLROnPlateau reducing learning rate to 0.0001250000059371814.
Epoch 91/100
 - 69s - loss: 0.2172 - acc: 0.9292 - val_loss: 0.2825 - val_acc: 0.9253

Epoch 00091: val_loss did not improve from 0.27563
Epoch 92/100
 - 69s - loss: 0.2015 - acc: 0.9344 - val_loss: 0.2787 - val_acc: 0.9232

Epoch 00092: val_loss did not improve from 0.27563
Epoch 93/100
 - 70s - loss: 0.2086 - acc: 0.9306 - val_loss: 0.2910 - val_acc: 0.9239

Epoch 00093: val_loss did not improve from 0.27563
Epoch 94/100
 - 72s - loss: 0.2007 - acc: 0.9339 - val_loss: 0.2892 - val_acc: 0.9197

Epoch 00094: val_loss did not improve from 0.27563
Epoch 95/100
 - 71s - loss: 0.2125 - acc: 0.9294 - val_loss: 0.2807 - val_acc: 0.9204

Epoch 00095: val_loss did not improve from 0.27563

Epoch 00095: ReduceLROnPlateau reducing learning rate to 6.25000029685907e-05.
Epoch 96/100
 - 71s - loss: 0.1944 - acc: 0.9356 - val_loss: 0.2691 - val_acc: 0.9225

Epoch 00096: val_loss improved from 0.27563 to 0.26913, saving model to weights.best.model.hdf5
Epoch 97/100
 - 70s - loss: 0.1989 - acc: 0.9345 - val_loss: 0.2739 - val_acc: 0.9246

Epoch 00097: val_loss did not improve from 0.26913
Epoch 98/100
 - 69s - loss: 0.1949 - acc: 0.9366 - val_loss: 0.2715 - val_acc: 0.9218

Epoch 00098: val_loss did not improve from 0.26913
Epoch 99/100
 - 70s - loss: 0.1924 - acc: 0.9357 - val_loss: 0.2715 - val_acc: 0.9232

Epoch 00099: val_loss did not improve from 0.26913
Epoch 100/100
 - 69s - loss: 0.1867 - acc: 0.9390 - val_loss: 0.2702 - val_acc: 0.9211

Epoch 00100: val_loss did not improve from 0.26913
In [50]:
hide_code
# Plot the training history
history_plot(history, 0)

We should have an accuracy greater than 3%

In [51]:
hide_code
# Load the model with the best validation accuracy
model.load_weights('weights.best.model.hdf5')
# Calculate classification accuracy on the testing set
score = model.evaluate(x_test, y_test)
score
1419/1419 [==============================] - 3s 2ms/step
Out[51]:
[0.24738302888838315, 0.9238900634249472]

Apply the ImageDataGenerator() function.

In [52]:
hide_code
# Fit the model with ImageDataGenerator()
# TODO: Define parameters
steps, epochs = 1000, 20
data_generator = ImageDataGenerator(zoom_range=0.2, shear_range=0.2, rotation_range=20)

generator = model.fit_generator(data_generator.flow(x_train, y_train, batch_size=64),
                                steps_per_epoch = steps, epochs = epochs,
                                validation_data = (x_valid, y_valid), 
                                callbacks=[checkpointer, lr_reduction], verbose=2)
Epoch 1/20
 - 463s - loss: 0.6433 - acc: 0.8049 - val_loss: 0.3001 - val_acc: 0.9168

Epoch 00001: val_loss did not improve from 0.26913
Epoch 2/20
 - 425s - loss: 0.6010 - acc: 0.8162 - val_loss: 0.2920 - val_acc: 0.9204

Epoch 00002: val_loss did not improve from 0.26913
Epoch 3/20
 - 455s - loss: 0.5854 - acc: 0.8176 - val_loss: 0.2970 - val_acc: 0.9239

Epoch 00003: val_loss did not improve from 0.26913
Epoch 4/20
 - 465s - loss: 0.5710 - acc: 0.8226 - val_loss: 0.2865 - val_acc: 0.9197

Epoch 00004: val_loss did not improve from 0.26913
Epoch 5/20
 - 432s - loss: 0.5548 - acc: 0.8271 - val_loss: 0.2854 - val_acc: 0.9168

Epoch 00005: val_loss did not improve from 0.26913
Epoch 6/20
 - 438s - loss: 0.5510 - acc: 0.8274 - val_loss: 0.2846 - val_acc: 0.9175

Epoch 00006: val_loss did not improve from 0.26913
Epoch 7/20
 - 497s - loss: 0.5330 - acc: 0.8337 - val_loss: 0.2803 - val_acc: 0.9211

Epoch 00007: val_loss did not improve from 0.26913
Epoch 8/20
 - 408s - loss: 0.5278 - acc: 0.8348 - val_loss: 0.2819 - val_acc: 0.9154

Epoch 00008: val_loss did not improve from 0.26913
Epoch 9/20
 - 386s - loss: 0.5202 - acc: 0.8361 - val_loss: 0.2817 - val_acc: 0.9211

Epoch 00009: val_loss did not improve from 0.26913
Epoch 10/20
 - 368s - loss: 0.5206 - acc: 0.8382 - val_loss: 0.2764 - val_acc: 0.9211

Epoch 00010: val_loss did not improve from 0.26913
Epoch 11/20
 - 366s - loss: 0.5024 - acc: 0.8419 - val_loss: 0.2760 - val_acc: 0.9211

Epoch 00011: val_loss did not improve from 0.26913
Epoch 12/20
 - 419s - loss: 0.5077 - acc: 0.8386 - val_loss: 0.2759 - val_acc: 0.9183

Epoch 00012: val_loss did not improve from 0.26913
Epoch 13/20
 - 398s - loss: 0.5001 - acc: 0.8442 - val_loss: 0.2740 - val_acc: 0.9225

Epoch 00013: val_loss did not improve from 0.26913
Epoch 14/20
 - 399s - loss: 0.4937 - acc: 0.8444 - val_loss: 0.2723 - val_acc: 0.9190

Epoch 00014: val_loss did not improve from 0.26913
Epoch 15/20
 - 405s - loss: 0.4871 - acc: 0.8450 - val_loss: 0.2725 - val_acc: 0.9239

Epoch 00015: val_loss did not improve from 0.26913
Epoch 16/20
 - 403s - loss: 0.4809 - acc: 0.8483 - val_loss: 0.2740 - val_acc: 0.9183

Epoch 00016: val_loss did not improve from 0.26913
Epoch 17/20
 - 422s - loss: 0.4749 - acc: 0.8494 - val_loss: 0.2669 - val_acc: 0.9211

Epoch 00017: val_loss improved from 0.26913 to 0.26689, saving model to weights.best.model.hdf5
Epoch 18/20
 - 410s - loss: 0.4754 - acc: 0.8495 - val_loss: 0.2667 - val_acc: 0.9211

Epoch 00018: val_loss improved from 0.26689 to 0.26674, saving model to weights.best.model.hdf5
Epoch 19/20
 - 413s - loss: 0.4713 - acc: 0.8501 - val_loss: 0.2675 - val_acc: 0.9218

Epoch 00019: val_loss did not improve from 0.26674
Epoch 20/20
 - 403s - loss: 0.4623 - acc: 0.8535 - val_loss: 0.2598 - val_acc: 0.9239

Epoch 00020: val_loss improved from 0.26674 to 0.25978, saving model to weights.best.model.hdf5
In [53]:
hide_code
# Load the model with the best validation accuracy
model.load_weights('weights.best.model.hdf5')
# Calculate classification accuracy on the testing set
score = model.evaluate(x_test, y_test)
score
1419/1419 [==============================] - 10s 7ms/step
Out[53]:
[0.24499498124984556, 0.923185341789993]

Let's compare the results with classifying algorithms.

In [ ]:
hide_code
# Fit the classifier and get the accuracy score
y_train_c = np.array([np.argmax(y) for y in y_train])
y_test_c = np.array([np.argmax(y) for y in y_test])
clf = GradientBoostingClassifier().fit(x_train.reshape(-1, 32*32*3), y_train_c)
clf.score(x_test.reshape(-1, 32*32*3), y_test_c)
In [ ]:
hide_code
# Fit the classifier and get the accuracy score
clf2 = RandomForestClassifier().fit(x_train.reshape(-1, 32*32*3), y_train_c)
clf2.score(x_test.reshape(-1, 32*32*3), y_test_c)

Grayscaled Images

Define a model architecture and compile the model for grayscaled images.

In [54]:
hide_code
def gray_model():
    model = Sequential()
    
    # TODO: Define a model architecture
    model.add(Conv2D(32, (5, 5), padding='same', input_shape=x_train2.shape[1:]))
    model.add(LeakyReLU(alpha=0.02))    
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))

    model.add(Conv2D(128, (5, 5)))
    model.add(LeakyReLU(alpha=0.02))    
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    
    model.add(GlobalMaxPooling2D()) 
    
    model.add(Dense(1024))
    model.add(LeakyReLU(alpha=0.02)) 
    model.add(Dropout(0.25)) 
    
    model.add(Dense(128))
    model.add(LeakyReLU(alpha=0.02)) 
    model.add(Dropout(0.25))    

    model.add(Dense(33))
    model.add(Activation('softmax'))
    
    # TODO: Compile the model
    model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
    return model

gray_model = gray_model()
In [55]:
hide_code
# Create callbacks
gray_checkpointer = ModelCheckpoint(filepath='weights.best.gray_model.hdf5', 
                                    verbose=2, save_best_only=True)
gray_lr_reduction = ReduceLROnPlateau(monitor='val_loss', 
                                      patience=10, verbose=2, factor=0.8)
In [56]:
hide_code
# Train the model
gray_history = gray_model.fit(x_train2, y_train2, 
                              epochs=200, batch_size=64, verbose=0,
                              validation_data=(x_valid2, y_valid2),
                              callbacks=[gray_checkpointer, gray_lr_reduction])
Epoch 00001: val_loss improved from inf to 3.45369, saving model to weights.best.gray_model.hdf5

Epoch 00002: val_loss improved from 3.45369 to 3.40002, saving model to weights.best.gray_model.hdf5

Epoch 00003: val_loss improved from 3.40002 to 3.38329, saving model to weights.best.gray_model.hdf5

Epoch 00004: val_loss did not improve from 3.38329

Epoch 00005: val_loss improved from 3.38329 to 3.37040, saving model to weights.best.gray_model.hdf5

Epoch 00006: val_loss improved from 3.37040 to 2.85877, saving model to weights.best.gray_model.hdf5

Epoch 00007: val_loss improved from 2.85877 to 2.70932, saving model to weights.best.gray_model.hdf5

Epoch 00008: val_loss improved from 2.70932 to 2.15681, saving model to weights.best.gray_model.hdf5

Epoch 00009: val_loss improved from 2.15681 to 2.03639, saving model to weights.best.gray_model.hdf5

Epoch 00010: val_loss improved from 2.03639 to 2.02739, saving model to weights.best.gray_model.hdf5

Epoch 00011: val_loss improved from 2.02739 to 1.90605, saving model to weights.best.gray_model.hdf5

Epoch 00012: val_loss improved from 1.90605 to 1.57145, saving model to weights.best.gray_model.hdf5

Epoch 00013: val_loss improved from 1.57145 to 1.36344, saving model to weights.best.gray_model.hdf5

Epoch 00014: val_loss improved from 1.36344 to 1.23527, saving model to weights.best.gray_model.hdf5

Epoch 00015: val_loss improved from 1.23527 to 1.08486, saving model to weights.best.gray_model.hdf5

Epoch 00016: val_loss did not improve from 1.08486

Epoch 00017: val_loss improved from 1.08486 to 0.97010, saving model to weights.best.gray_model.hdf5

Epoch 00018: val_loss improved from 0.97010 to 0.91904, saving model to weights.best.gray_model.hdf5

Epoch 00019: val_loss did not improve from 0.91904

Epoch 00020: val_loss improved from 0.91904 to 0.78284, saving model to weights.best.gray_model.hdf5

Epoch 00021: val_loss did not improve from 0.78284

Epoch 00022: val_loss did not improve from 0.78284

Epoch 00023: val_loss did not improve from 0.78284

Epoch 00024: val_loss improved from 0.78284 to 0.72622, saving model to weights.best.gray_model.hdf5

Epoch 00025: val_loss improved from 0.72622 to 0.69710, saving model to weights.best.gray_model.hdf5

Epoch 00026: val_loss did not improve from 0.69710

Epoch 00027: val_loss did not improve from 0.69710

Epoch 00028: val_loss improved from 0.69710 to 0.57178, saving model to weights.best.gray_model.hdf5

Epoch 00029: val_loss did not improve from 0.57178

Epoch 00030: val_loss did not improve from 0.57178

Epoch 00031: val_loss did not improve from 0.57178

Epoch 00032: val_loss did not improve from 0.57178

Epoch 00033: val_loss did not improve from 0.57178

Epoch 00034: val_loss improved from 0.57178 to 0.52883, saving model to weights.best.gray_model.hdf5

Epoch 00035: val_loss did not improve from 0.52883

Epoch 00036: val_loss did not improve from 0.52883

Epoch 00037: val_loss did not improve from 0.52883

Epoch 00038: val_loss did not improve from 0.52883

Epoch 00039: val_loss did not improve from 0.52883

Epoch 00040: val_loss did not improve from 0.52883

Epoch 00041: val_loss improved from 0.52883 to 0.52257, saving model to weights.best.gray_model.hdf5

Epoch 00042: val_loss did not improve from 0.52257

Epoch 00043: val_loss improved from 0.52257 to 0.50231, saving model to weights.best.gray_model.hdf5

Epoch 00044: val_loss did not improve from 0.50231

Epoch 00045: val_loss did not improve from 0.50231

Epoch 00046: val_loss did not improve from 0.50231

Epoch 00047: val_loss did not improve from 0.50231

Epoch 00048: val_loss improved from 0.50231 to 0.44098, saving model to weights.best.gray_model.hdf5

Epoch 00049: val_loss did not improve from 0.44098

Epoch 00050: val_loss did not improve from 0.44098

Epoch 00051: val_loss improved from 0.44098 to 0.38885, saving model to weights.best.gray_model.hdf5

Epoch 00052: val_loss did not improve from 0.38885

Epoch 00053: val_loss did not improve from 0.38885

Epoch 00054: val_loss did not improve from 0.38885

Epoch 00055: val_loss did not improve from 0.38885

Epoch 00056: val_loss improved from 0.38885 to 0.36511, saving model to weights.best.gray_model.hdf5

Epoch 00057: val_loss did not improve from 0.36511

Epoch 00058: val_loss did not improve from 0.36511

Epoch 00059: val_loss did not improve from 0.36511

Epoch 00060: val_loss did not improve from 0.36511

Epoch 00061: val_loss did not improve from 0.36511

Epoch 00062: val_loss did not improve from 0.36511

Epoch 00063: val_loss did not improve from 0.36511

Epoch 00064: val_loss did not improve from 0.36511

Epoch 00065: val_loss did not improve from 0.36511

Epoch 00066: val_loss did not improve from 0.36511

Epoch 00066: ReduceLROnPlateau reducing learning rate to 0.000800000037997961.

Epoch 00067: val_loss did not improve from 0.36511

Epoch 00068: val_loss did not improve from 0.36511

Epoch 00069: val_loss did not improve from 0.36511

Epoch 00070: val_loss did not improve from 0.36511

Epoch 00071: val_loss did not improve from 0.36511

Epoch 00072: val_loss improved from 0.36511 to 0.33051, saving model to weights.best.gray_model.hdf5

Epoch 00073: val_loss did not improve from 0.33051

Epoch 00074: val_loss did not improve from 0.33051

Epoch 00075: val_loss did not improve from 0.33051

Epoch 00076: val_loss did not improve from 0.33051

Epoch 00077: val_loss did not improve from 0.33051

Epoch 00078: val_loss did not improve from 0.33051

Epoch 00079: val_loss did not improve from 0.33051

Epoch 00080: val_loss improved from 0.33051 to 0.32576, saving model to weights.best.gray_model.hdf5

Epoch 00081: val_loss did not improve from 0.32576

Epoch 00082: val_loss did not improve from 0.32576

Epoch 00083: val_loss did not improve from 0.32576

Epoch 00084: val_loss did not improve from 0.32576

Epoch 00085: val_loss did not improve from 0.32576

Epoch 00086: val_loss did not improve from 0.32576

Epoch 00087: val_loss did not improve from 0.32576

Epoch 00088: val_loss did not improve from 0.32576

Epoch 00089: val_loss did not improve from 0.32576

Epoch 00090: val_loss did not improve from 0.32576

Epoch 00090: ReduceLROnPlateau reducing learning rate to 0.0006400000303983689.

Epoch 00091: val_loss did not improve from 0.32576

Epoch 00092: val_loss did not improve from 0.32576

Epoch 00093: val_loss did not improve from 0.32576

Epoch 00094: val_loss did not improve from 0.32576

Epoch 00095: val_loss improved from 0.32576 to 0.31864, saving model to weights.best.gray_model.hdf5

Epoch 00096: val_loss improved from 0.31864 to 0.31743, saving model to weights.best.gray_model.hdf5

Epoch 00097: val_loss did not improve from 0.31743

Epoch 00098: val_loss did not improve from 0.31743

Epoch 00099: val_loss did not improve from 0.31743

Epoch 00100: val_loss did not improve from 0.31743

Epoch 00101: val_loss improved from 0.31743 to 0.30556, saving model to weights.best.gray_model.hdf5

Epoch 00102: val_loss did not improve from 0.30556

Epoch 00103: val_loss did not improve from 0.30556

Epoch 00104: val_loss did not improve from 0.30556

Epoch 00105: val_loss did not improve from 0.30556

Epoch 00106: val_loss did not improve from 0.30556

Epoch 00107: val_loss did not improve from 0.30556

Epoch 00108: val_loss did not improve from 0.30556

Epoch 00109: val_loss did not improve from 0.30556

Epoch 00110: val_loss did not improve from 0.30556

Epoch 00111: val_loss did not improve from 0.30556

Epoch 00111: ReduceLROnPlateau reducing learning rate to 0.0005120000336319208.

Epoch 00112: val_loss improved from 0.30556 to 0.30341, saving model to weights.best.gray_model.hdf5

Epoch 00113: val_loss did not improve from 0.30341

Epoch 00114: val_loss did not improve from 0.30341

Epoch 00115: val_loss did not improve from 0.30341

Epoch 00116: val_loss did not improve from 0.30341

Epoch 00117: val_loss did not improve from 0.30341

Epoch 00118: val_loss did not improve from 0.30341

Epoch 00119: val_loss did not improve from 0.30341

Epoch 00120: val_loss did not improve from 0.30341

Epoch 00121: val_loss did not improve from 0.30341

Epoch 00122: val_loss did not improve from 0.30341

Epoch 00122: ReduceLROnPlateau reducing learning rate to 0.00040960004553198815.

Epoch 00123: val_loss did not improve from 0.30341

Epoch 00124: val_loss did not improve from 0.30341

Epoch 00125: val_loss did not improve from 0.30341

Epoch 00126: val_loss did not improve from 0.30341

Epoch 00127: val_loss did not improve from 0.30341

Epoch 00128: val_loss did not improve from 0.30341

Epoch 00129: val_loss did not improve from 0.30341

Epoch 00130: val_loss did not improve from 0.30341

Epoch 00131: val_loss did not improve from 0.30341

Epoch 00132: val_loss did not improve from 0.30341

Epoch 00132: ReduceLROnPlateau reducing learning rate to 0.00032768002711236477.

Epoch 00133: val_loss did not improve from 0.30341

Epoch 00134: val_loss improved from 0.30341 to 0.29877, saving model to weights.best.gray_model.hdf5

Epoch 00135: val_loss did not improve from 0.29877

Epoch 00136: val_loss did not improve from 0.29877

Epoch 00137: val_loss improved from 0.29877 to 0.28750, saving model to weights.best.gray_model.hdf5

Epoch 00138: val_loss did not improve from 0.28750

Epoch 00139: val_loss did not improve from 0.28750

Epoch 00140: val_loss did not improve from 0.28750

Epoch 00141: val_loss did not improve from 0.28750

Epoch 00142: val_loss did not improve from 0.28750

Epoch 00143: val_loss did not improve from 0.28750

Epoch 00144: val_loss did not improve from 0.28750

Epoch 00145: val_loss did not improve from 0.28750

Epoch 00146: val_loss did not improve from 0.28750

Epoch 00147: val_loss did not improve from 0.28750

Epoch 00147: ReduceLROnPlateau reducing learning rate to 0.0002621440216898918.

Epoch 00148: val_loss did not improve from 0.28750

Epoch 00149: val_loss did not improve from 0.28750

Epoch 00150: val_loss did not improve from 0.28750

Epoch 00151: val_loss did not improve from 0.28750

Epoch 00152: val_loss did not improve from 0.28750

Epoch 00153: val_loss did not improve from 0.28750

Epoch 00154: val_loss did not improve from 0.28750

Epoch 00155: val_loss did not improve from 0.28750

Epoch 00156: val_loss did not improve from 0.28750

Epoch 00157: val_loss did not improve from 0.28750

Epoch 00157: ReduceLROnPlateau reducing learning rate to 0.00020971521735191345.

Epoch 00158: val_loss did not improve from 0.28750

Epoch 00159: val_loss did not improve from 0.28750

Epoch 00160: val_loss did not improve from 0.28750

Epoch 00161: val_loss did not improve from 0.28750

Epoch 00162: val_loss did not improve from 0.28750

Epoch 00163: val_loss did not improve from 0.28750

Epoch 00164: val_loss did not improve from 0.28750

Epoch 00165: val_loss did not improve from 0.28750

Epoch 00166: val_loss improved from 0.28750 to 0.27781, saving model to weights.best.gray_model.hdf5

Epoch 00167: val_loss did not improve from 0.27781

Epoch 00168: val_loss did not improve from 0.27781

Epoch 00169: val_loss did not improve from 0.27781

Epoch 00170: val_loss did not improve from 0.27781

Epoch 00171: val_loss did not improve from 0.27781

Epoch 00172: val_loss did not improve from 0.27781

Epoch 00173: val_loss did not improve from 0.27781

Epoch 00174: val_loss did not improve from 0.27781

Epoch 00175: val_loss did not improve from 0.27781

Epoch 00176: val_loss did not improve from 0.27781

Epoch 00176: ReduceLROnPlateau reducing learning rate to 0.00016777217388153076.

Epoch 00177: val_loss did not improve from 0.27781

Epoch 00178: val_loss did not improve from 0.27781

Epoch 00179: val_loss did not improve from 0.27781

Epoch 00180: val_loss did not improve from 0.27781

Epoch 00181: val_loss did not improve from 0.27781

Epoch 00182: val_loss did not improve from 0.27781

Epoch 00183: val_loss improved from 0.27781 to 0.27773, saving model to weights.best.gray_model.hdf5

Epoch 00184: val_loss did not improve from 0.27773

Epoch 00185: val_loss did not improve from 0.27773

Epoch 00186: val_loss did not improve from 0.27773

Epoch 00186: ReduceLROnPlateau reducing learning rate to 0.00013421773910522462.

Epoch 00187: val_loss did not improve from 0.27773

Epoch 00188: val_loss did not improve from 0.27773

Epoch 00189: val_loss did not improve from 0.27773

Epoch 00190: val_loss did not improve from 0.27773

Epoch 00191: val_loss did not improve from 0.27773

Epoch 00192: val_loss did not improve from 0.27773

Epoch 00193: val_loss did not improve from 0.27773

Epoch 00194: val_loss did not improve from 0.27773

Epoch 00195: val_loss did not improve from 0.27773

Epoch 00196: val_loss did not improve from 0.27773

Epoch 00196: ReduceLROnPlateau reducing learning rate to 0.00010737419361248613.

Epoch 00197: val_loss did not improve from 0.27773

Epoch 00198: val_loss did not improve from 0.27773

Epoch 00199: val_loss did not improve from 0.27773

Epoch 00200: val_loss did not improve from 0.27773
In [57]:
hide_code
# Plot the training history
history_plot(gray_history, 0)

Try to reach an accuracy greater than 80%

In [58]:
hide_code
# Load the model with the best validation accuracy
gray_model.load_weights('weights.best.gray_model.hdf5')
# Calculate classification accuracy on the testing set
gray_score = gray_model.evaluate(x_test2, y_test2)
gray_score
1419/1419 [==============================] - 9s 6ms/step
Out[58]:
[0.3054520464525246, 0.9295278365045807]

Apply the ImageDataGenerator() function.

In [61]:
hide_code
# Fit the model with ImageDataGenerator()
# TODO: Define parameters
steps, epochs = 1000, 20
data_generator = ImageDataGenerator(zoom_range=0.2, shear_range=0.2, rotation_range=20)

gray_generator = gray_model.fit_generator(data_generator.flow(x_train2, y_train2, batch_size=64),
                                          steps_per_epoch = steps, epochs = epochs,
                                          validation_data = (x_valid2, y_valid2), 
                                          callbacks=[gray_checkpointer, gray_lr_reduction], verbose=2)
Epoch 1/20
 - 257s - loss: 0.7912 - acc: 0.7939 - val_loss: 0.2639 - val_acc: 0.9232

Epoch 00001: val_loss improved from 0.27773 to 0.26388, saving model to weights.best.gray_model.hdf5
Epoch 2/20
 - 246s - loss: 0.7671 - acc: 0.8008 - val_loss: 0.2861 - val_acc: 0.9197

Epoch 00002: val_loss did not improve from 0.26388
Epoch 3/20
 - 245s - loss: 0.7388 - acc: 0.8044 - val_loss: 0.2917 - val_acc: 0.9232

Epoch 00003: val_loss did not improve from 0.26388
Epoch 4/20
 - 242s - loss: 0.7273 - acc: 0.8091 - val_loss: 0.2842 - val_acc: 0.9239

Epoch 00004: val_loss did not improve from 0.26388
Epoch 5/20
 - 249s - loss: 0.7195 - acc: 0.8105 - val_loss: 0.2909 - val_acc: 0.9232

Epoch 00005: val_loss did not improve from 0.26388
Epoch 6/20
 - 265s - loss: 0.7158 - acc: 0.8116 - val_loss: 0.2784 - val_acc: 0.9225

Epoch 00006: val_loss did not improve from 0.26388
Epoch 7/20
 - 279s - loss: 0.6965 - acc: 0.8137 - val_loss: 0.2907 - val_acc: 0.9218

Epoch 00007: val_loss did not improve from 0.26388
Epoch 8/20
 - 271s - loss: 0.6951 - acc: 0.8175 - val_loss: 0.2848 - val_acc: 0.9232

Epoch 00008: val_loss did not improve from 0.26388
Epoch 9/20
 - 254s - loss: 0.6683 - acc: 0.8229 - val_loss: 0.2688 - val_acc: 0.9274

Epoch 00009: val_loss did not improve from 0.26388
Epoch 10/20
 - 250s - loss: 0.6747 - acc: 0.8199 - val_loss: 0.2731 - val_acc: 0.9267

Epoch 00010: val_loss did not improve from 0.26388
Epoch 11/20
 - 253s - loss: 0.6568 - acc: 0.8248 - val_loss: 0.2816 - val_acc: 0.9281

Epoch 00011: val_loss did not improve from 0.26388

Epoch 00011: ReduceLROnPlateau reducing learning rate to 8.589935605414213e-05.
Epoch 12/20
 - 249s - loss: 0.6588 - acc: 0.8245 - val_loss: 0.2763 - val_acc: 0.9323

Epoch 00012: val_loss did not improve from 0.26388
Epoch 13/20
 - 248s - loss: 0.6460 - acc: 0.8303 - val_loss: 0.2771 - val_acc: 0.9331

Epoch 00013: val_loss did not improve from 0.26388
Epoch 14/20
 - 248s - loss: 0.6342 - acc: 0.8281 - val_loss: 0.2871 - val_acc: 0.9288

Epoch 00014: val_loss did not improve from 0.26388
Epoch 15/20
 - 247s - loss: 0.6265 - acc: 0.8331 - val_loss: 0.2660 - val_acc: 0.9281

Epoch 00015: val_loss did not improve from 0.26388
Epoch 16/20
 - 248s - loss: 0.6320 - acc: 0.8291 - val_loss: 0.2780 - val_acc: 0.9288

Epoch 00016: val_loss did not improve from 0.26388
Epoch 17/20
 - 252s - loss: 0.6257 - acc: 0.8340 - val_loss: 0.2639 - val_acc: 0.9331

Epoch 00017: val_loss did not improve from 0.26388
Epoch 18/20
 - 250s - loss: 0.6122 - acc: 0.8354 - val_loss: 0.2821 - val_acc: 0.9246

Epoch 00018: val_loss did not improve from 0.26388
Epoch 19/20
 - 251s - loss: 0.6188 - acc: 0.8328 - val_loss: 0.2683 - val_acc: 0.9274

Epoch 00019: val_loss did not improve from 0.26388
Epoch 20/20
 - 259s - loss: 0.6102 - acc: 0.8371 - val_loss: 0.2816 - val_acc: 0.9274

Epoch 00020: val_loss did not improve from 0.26388
In [62]:
hide_code
# Load the model with the best validation accuracy
gray_model.load_weights('weights.best.gray_model.hdf5')
# Calculate classification accuracy on the testing set
gray_score = gray_model.evaluate(x_test2, y_test2)
gray_score
1419/1419 [==============================] - 11s 8ms/step
Out[62]:
[0.290765018877721, 0.9231853420000163]

Let's compare the results with classifying algorithms.

In [ ]:
hide_code
# Fit the classifier and get the accuracy score
y_train2_c = np.array([np.argmax(y) for y in y_train2])
y_test2_c = np.array([np.argmax(y) for y in y_test2])
clf = GradientBoostingClassifier().fit(x_train2.reshape(-1, 32*32), y_train2_c)
clf.score(x_test2.reshape(-1, 32*32), y_test2_c)
In [ ]:
hide_code
# Fit the classifier and get the accuracy score
clf2 = RandomForestClassifier().fit(x_train2.reshape(-1, 32*32), y_train2_c)
clf2.score(x_test2.reshape(-1, 32*32), y_test2_c)

Step 5. Create a Multi-Label Classification Model

Color Images

In [71]:
hide_code
def multi_model():    
    model_input = Input(shape=(32, 32, 3))
    x = BatchNormalization()(model_input)
    # TODO: Define a model architecture
    x = Conv2D(32, (3, 3), padding='same')(model_input)
    x = LeakyReLU(alpha=0.02)(x)
    x = MaxPooling2D(pool_size=(2, 2))(x)    
    x = Dropout(0.25)(x)
    
    x = Conv2D(128, (3, 3), padding='same')(x)
    x = LeakyReLU(alpha=0.02)(x)
    x = MaxPooling2D(pool_size=(2, 2))(x)    
    x = Dropout(0.25)(x)
              
    x = GlobalMaxPooling2D()(x)
    
    x = Dense(1024)(x)
    x = LeakyReLU(alpha=0.02)(x)
    x = Dropout(0.25)(x)
    
    x = Dense(128)(x)  
    x = LeakyReLU(alpha=0.02)(x)
    x = Dropout(0.25)(x)
    
    y1 = Dense(33, activation='softmax')(x)
    y2 = Dense(4, activation='softmax')(x)
    
    model = Model(inputs=model_input, outputs=[y1, y2])
    
    # TODO: Compile the model
    model.compile(loss='categorical_crossentropy', optimizer='nadam', metrics=['accuracy'])
    return model

multi_model = multi_model()
In [72]:
hide_code
# Display the model architecture
multi_model.summary()
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_2 (InputLayer)            (None, 32, 32, 3)    0                                            
__________________________________________________________________________________________________
conv2d_11 (Conv2D)              (None, 32, 32, 32)   896         input_2[0][0]                    
__________________________________________________________________________________________________
leaky_re_lu_18 (LeakyReLU)      (None, 32, 32, 32)   0           conv2d_11[0][0]                  
__________________________________________________________________________________________________
max_pooling2d_11 (MaxPooling2D) (None, 16, 16, 32)   0           leaky_re_lu_18[0][0]             
__________________________________________________________________________________________________
dropout_18 (Dropout)            (None, 16, 16, 32)   0           max_pooling2d_11[0][0]           
__________________________________________________________________________________________________
conv2d_12 (Conv2D)              (None, 16, 16, 128)  36992       dropout_18[0][0]                 
__________________________________________________________________________________________________
leaky_re_lu_19 (LeakyReLU)      (None, 16, 16, 128)  0           conv2d_12[0][0]                  
__________________________________________________________________________________________________
max_pooling2d_12 (MaxPooling2D) (None, 8, 8, 128)    0           leaky_re_lu_19[0][0]             
__________________________________________________________________________________________________
dropout_19 (Dropout)            (None, 8, 8, 128)    0           max_pooling2d_12[0][0]           
__________________________________________________________________________________________________
global_max_pooling2d_6 (GlobalM (None, 128)          0           dropout_19[0][0]                 
__________________________________________________________________________________________________
dense_14 (Dense)                (None, 1024)         132096      global_max_pooling2d_6[0][0]     
__________________________________________________________________________________________________
leaky_re_lu_20 (LeakyReLU)      (None, 1024)         0           dense_14[0][0]                   
__________________________________________________________________________________________________
dropout_20 (Dropout)            (None, 1024)         0           leaky_re_lu_20[0][0]             
__________________________________________________________________________________________________
dense_15 (Dense)                (None, 128)          131200      dropout_20[0][0]                 
__________________________________________________________________________________________________
leaky_re_lu_21 (LeakyReLU)      (None, 128)          0           dense_15[0][0]                   
__________________________________________________________________________________________________
dropout_21 (Dropout)            (None, 128)          0           leaky_re_lu_21[0][0]             
__________________________________________________________________________________________________
dense_16 (Dense)                (None, 33)           4257        dropout_21[0][0]                 
__________________________________________________________________________________________________
dense_17 (Dense)                (None, 4)            516         dropout_21[0][0]                 
==================================================================================================
Total params: 305,957
Trainable params: 305,957
Non-trainable params: 0
__________________________________________________________________________________________________
In [74]:
hide_code
# Create callbacks
multi_checkpointer = ModelCheckpoint(filepath='weights.best.multi.hdf5', 
                                     verbose=2, save_best_only=True)
multi_lr_reduction = ReduceLROnPlateau(monitor='val_loss', 
                                       patience=5, verbose=2, factor=0.8)
In [75]:
hide_code
# Train the model
multi_history = multi_model.fit(x_train3, y_train3_list, 
                                validation_data=(x_valid3, y_valid3_list), 
                                epochs=100, batch_size=64, verbose=0, 
                                callbacks=[multi_checkpointer, multi_lr_reduction])
Epoch 00001: val_loss improved from inf to 4.40898, saving model to weights.best.multi.hdf5

Epoch 00002: val_loss improved from 4.40898 to 4.20733, saving model to weights.best.multi.hdf5

Epoch 00003: val_loss improved from 4.20733 to 4.01372, saving model to weights.best.multi.hdf5

Epoch 00004: val_loss improved from 4.01372 to 3.91702, saving model to weights.best.multi.hdf5

Epoch 00005: val_loss improved from 3.91702 to 3.79861, saving model to weights.best.multi.hdf5

Epoch 00006: val_loss did not improve from 3.79861

Epoch 00007: val_loss did not improve from 3.79861

Epoch 00008: val_loss did not improve from 3.79861

Epoch 00009: val_loss improved from 3.79861 to 3.65847, saving model to weights.best.multi.hdf5

Epoch 00010: val_loss did not improve from 3.65847

Epoch 00011: val_loss did not improve from 3.65847

Epoch 00012: val_loss did not improve from 3.65847

Epoch 00013: val_loss improved from 3.65847 to 3.53820, saving model to weights.best.multi.hdf5

Epoch 00014: val_loss did not improve from 3.53820

Epoch 00015: val_loss improved from 3.53820 to 3.41594, saving model to weights.best.multi.hdf5

Epoch 00016: val_loss did not improve from 3.41594

Epoch 00017: val_loss improved from 3.41594 to 3.40702, saving model to weights.best.multi.hdf5

Epoch 00018: val_loss did not improve from 3.40702

Epoch 00019: val_loss did not improve from 3.40702

Epoch 00020: val_loss did not improve from 3.40702

Epoch 00021: val_loss improved from 3.40702 to 3.16133, saving model to weights.best.multi.hdf5

Epoch 00022: val_loss did not improve from 3.16133

Epoch 00023: val_loss did not improve from 3.16133

Epoch 00024: val_loss did not improve from 3.16133

Epoch 00025: val_loss improved from 3.16133 to 3.15801, saving model to weights.best.multi.hdf5

Epoch 00026: val_loss did not improve from 3.15801

Epoch 00027: val_loss did not improve from 3.15801

Epoch 00028: val_loss did not improve from 3.15801

Epoch 00029: val_loss did not improve from 3.15801

Epoch 00030: val_loss did not improve from 3.15801

Epoch 00030: ReduceLROnPlateau reducing learning rate to 0.001600000075995922.

Epoch 00031: val_loss did not improve from 3.15801

Epoch 00032: val_loss did not improve from 3.15801

Epoch 00033: val_loss improved from 3.15801 to 3.12298, saving model to weights.best.multi.hdf5

Epoch 00034: val_loss did not improve from 3.12298

Epoch 00035: val_loss did not improve from 3.12298

Epoch 00036: val_loss did not improve from 3.12298

Epoch 00037: val_loss improved from 3.12298 to 2.96928, saving model to weights.best.multi.hdf5

Epoch 00038: val_loss did not improve from 2.96928

Epoch 00039: val_loss did not improve from 2.96928

Epoch 00040: val_loss did not improve from 2.96928

Epoch 00041: val_loss did not improve from 2.96928

Epoch 00042: val_loss did not improve from 2.96928

Epoch 00042: ReduceLROnPlateau reducing learning rate to 0.0012800000607967378.

Epoch 00043: val_loss did not improve from 2.96928

Epoch 00044: val_loss did not improve from 2.96928

Epoch 00045: val_loss did not improve from 2.96928

Epoch 00046: val_loss did not improve from 2.96928

Epoch 00047: val_loss did not improve from 2.96928

Epoch 00047: ReduceLROnPlateau reducing learning rate to 0.0010240000672638416.

Epoch 00048: val_loss did not improve from 2.96928

Epoch 00049: val_loss did not improve from 2.96928

Epoch 00050: val_loss did not improve from 2.96928

Epoch 00051: val_loss did not improve from 2.96928

Epoch 00052: val_loss did not improve from 2.96928

Epoch 00052: ReduceLROnPlateau reducing learning rate to 0.0008192000910639763.

Epoch 00053: val_loss did not improve from 2.96928

Epoch 00054: val_loss did not improve from 2.96928

Epoch 00055: val_loss did not improve from 2.96928

Epoch 00056: val_loss did not improve from 2.96928

Epoch 00057: val_loss did not improve from 2.96928

Epoch 00057: ReduceLROnPlateau reducing learning rate to 0.0006553600542247295.

Epoch 00058: val_loss did not improve from 2.96928

Epoch 00059: val_loss did not improve from 2.96928

Epoch 00060: val_loss did not improve from 2.96928

Epoch 00061: val_loss did not improve from 2.96928

Epoch 00062: val_loss did not improve from 2.96928

Epoch 00062: ReduceLROnPlateau reducing learning rate to 0.0005242880433797836.

Epoch 00063: val_loss did not improve from 2.96928

Epoch 00064: val_loss did not improve from 2.96928

Epoch 00065: val_loss did not improve from 2.96928

Epoch 00066: val_loss did not improve from 2.96928

Epoch 00067: val_loss did not improve from 2.96928

Epoch 00067: ReduceLROnPlateau reducing learning rate to 0.0004194304347038269.

Epoch 00068: val_loss did not improve from 2.96928

Epoch 00069: val_loss did not improve from 2.96928

Epoch 00070: val_loss did not improve from 2.96928

Epoch 00071: val_loss did not improve from 2.96928

Epoch 00072: val_loss did not improve from 2.96928

Epoch 00072: ReduceLROnPlateau reducing learning rate to 0.0003355443477630615.

Epoch 00073: val_loss did not improve from 2.96928

Epoch 00074: val_loss did not improve from 2.96928

Epoch 00075: val_loss did not improve from 2.96928

Epoch 00076: val_loss did not improve from 2.96928

Epoch 00077: val_loss did not improve from 2.96928

Epoch 00077: ReduceLROnPlateau reducing learning rate to 0.00026843547821044924.

Epoch 00078: val_loss did not improve from 2.96928

Epoch 00079: val_loss did not improve from 2.96928

Epoch 00080: val_loss did not improve from 2.96928

Epoch 00081: val_loss did not improve from 2.96928

Epoch 00082: val_loss did not improve from 2.96928

Epoch 00082: ReduceLROnPlateau reducing learning rate to 0.00021474838722497226.

Epoch 00083: val_loss did not improve from 2.96928

Epoch 00084: val_loss did not improve from 2.96928

Epoch 00085: val_loss did not improve from 2.96928

Epoch 00086: val_loss did not improve from 2.96928

Epoch 00087: val_loss did not improve from 2.96928

Epoch 00087: ReduceLROnPlateau reducing learning rate to 0.00017179871210828426.

Epoch 00088: val_loss did not improve from 2.96928

Epoch 00089: val_loss did not improve from 2.96928

Epoch 00090: val_loss did not improve from 2.96928

Epoch 00091: val_loss did not improve from 2.96928

Epoch 00092: val_loss did not improve from 2.96928

Epoch 00092: ReduceLROnPlateau reducing learning rate to 0.00013743897434324027.

Epoch 00093: val_loss did not improve from 2.96928

Epoch 00094: val_loss did not improve from 2.96928

Epoch 00095: val_loss did not improve from 2.96928

Epoch 00096: val_loss did not improve from 2.96928

Epoch 00097: val_loss did not improve from 2.96928

Epoch 00097: ReduceLROnPlateau reducing learning rate to 0.00010995117481797934.

Epoch 00098: val_loss did not improve from 2.96928

Epoch 00099: val_loss did not improve from 2.96928

Epoch 00100: val_loss did not improve from 2.96928

We should have an accuracy greater than 3% for the first target (letter) and greater than 25% for the second target (background).

In [76]:
hide_code
# Load the model with the best validation accuracy
multi_model.load_weights('weights.best.multi.hdf5')
# Calculate classification accuracy on the testing set
multi_scores = multi_model.evaluate(x_test3, y_test3_list, verbose=0)

print("Scores: \n" , (multi_scores))
print("First label. Accuracy: %.2f%%" % (multi_scores[3]*100))
print("Second label. Accuracy: %.2f%%" % (multi_scores[4]*100))
Scores: 
 [8.749844092731328, 2.8440989943941855, 5.905745039194549, 0.18252290353714537, 0.3883016209647721]
First label. Accuracy: 18.25%
Second label. Accuracy: 38.83%

Grayscaled Images

In [78]:
hide_code
def gray_multi_model():    
    model_input = Input(shape=(32, 32, 1))
    x = BatchNormalization()(model_input)
    
    # TODO: Define a model architecture
    x = Conv2D(32, (5, 5), padding='same')(model_input)
    x = LeakyReLU(alpha=0.02)(x)
    x = MaxPooling2D(pool_size=(2, 2))(x)    
    x = Dropout(0.25)(x)
    
    x = Conv2D(256, (5, 5), padding='same')(x) 
    x = LeakyReLU(alpha=0.02)(x)
    x = MaxPooling2D(pool_size=(2, 2))(x)    
    x = Dropout(0.25)(x)
              
    x = GlobalMaxPooling2D()(x)
    
    x = Dense(1024)(x) 
    x = LeakyReLU(alpha=0.02)(x)
    x = Dropout(0.25)(x)
    
    x = Dense(256)(x) 
    x = LeakyReLU(alpha=0.02)(x)
    x = Dropout(0.25)(x)
    
    y1 = Dense(33, activation='softmax')(x)
    y2 = Dense(4, activation='softmax')(x)
       
    model = Model(inputs=model_input, outputs=[y1, y2])
    
    # TODO: Compile the model
    model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])  
    
    return model

gray_multi_model = gray_multi_model()
In [79]:
hide_code
# Create callbacks
gray_multi_checkpointer = ModelCheckpoint(filepath='weights.best.gray_multi.hdf5', 
                                          verbose=2, save_best_only=True)
hide_code
# Display the model architecture
gray_multi_lr_reduction = ReduceLROnPlateau(monitor='val_loss', 
                                            patience=10, verbose=2, factor=0.8)
In [80]:
hide_code
# Train the model
gray_multi_history = gray_multi_model.fit(x_train4, y_train4_list, 
                                          validation_data=(x_valid4, y_valid4_list), 
                                          epochs=100, batch_size=64, verbose=0, 
                                          callbacks=[gray_multi_checkpointer, gray_multi_lr_reduction])
Epoch 00001: val_loss improved from inf to 4.56719, saving model to weights.best.gray_multi.hdf5

Epoch 00002: val_loss improved from 4.56719 to 4.10845, saving model to weights.best.gray_multi.hdf5

Epoch 00003: val_loss improved from 4.10845 to 3.82228, saving model to weights.best.gray_multi.hdf5

Epoch 00004: val_loss did not improve from 3.82228

Epoch 00005: val_loss improved from 3.82228 to 3.57119, saving model to weights.best.gray_multi.hdf5

Epoch 00006: val_loss improved from 3.57119 to 3.50969, saving model to weights.best.gray_multi.hdf5

Epoch 00007: val_loss did not improve from 3.50969

Epoch 00008: val_loss improved from 3.50969 to 3.41744, saving model to weights.best.gray_multi.hdf5

Epoch 00009: val_loss improved from 3.41744 to 3.38803, saving model to weights.best.gray_multi.hdf5

Epoch 00010: val_loss improved from 3.38803 to 3.01899, saving model to weights.best.gray_multi.hdf5

Epoch 00011: val_loss improved from 3.01899 to 2.74828, saving model to weights.best.gray_multi.hdf5

Epoch 00012: val_loss improved from 2.74828 to 2.63922, saving model to weights.best.gray_multi.hdf5

Epoch 00013: val_loss did not improve from 2.63922

Epoch 00014: val_loss improved from 2.63922 to 2.56891, saving model to weights.best.gray_multi.hdf5

Epoch 00015: val_loss improved from 2.56891 to 2.19898, saving model to weights.best.gray_multi.hdf5

Epoch 00016: val_loss did not improve from 2.19898

Epoch 00017: val_loss did not improve from 2.19898

Epoch 00018: val_loss did not improve from 2.19898

Epoch 00019: val_loss improved from 2.19898 to 2.15843, saving model to weights.best.gray_multi.hdf5

Epoch 00020: val_loss did not improve from 2.15843

Epoch 00021: val_loss improved from 2.15843 to 1.88533, saving model to weights.best.gray_multi.hdf5

Epoch 00022: val_loss improved from 1.88533 to 1.59052, saving model to weights.best.gray_multi.hdf5

Epoch 00023: val_loss did not improve from 1.59052

Epoch 00024: val_loss improved from 1.59052 to 1.50788, saving model to weights.best.gray_multi.hdf5

Epoch 00025: val_loss improved from 1.50788 to 1.39603, saving model to weights.best.gray_multi.hdf5

Epoch 00026: val_loss did not improve from 1.39603

Epoch 00027: val_loss improved from 1.39603 to 1.21846, saving model to weights.best.gray_multi.hdf5

Epoch 00028: val_loss did not improve from 1.21846

Epoch 00029: val_loss did not improve from 1.21846

Epoch 00030: val_loss improved from 1.21846 to 1.14028, saving model to weights.best.gray_multi.hdf5

Epoch 00031: val_loss did not improve from 1.14028

Epoch 00032: val_loss did not improve from 1.14028

Epoch 00033: val_loss did not improve from 1.14028

Epoch 00034: val_loss improved from 1.14028 to 0.97151, saving model to weights.best.gray_multi.hdf5

Epoch 00035: val_loss did not improve from 0.97151

Epoch 00036: val_loss did not improve from 0.97151

Epoch 00037: val_loss did not improve from 0.97151

Epoch 00038: val_loss did not improve from 0.97151

Epoch 00039: val_loss did not improve from 0.97151

Epoch 00040: val_loss improved from 0.97151 to 0.91962, saving model to weights.best.gray_multi.hdf5

Epoch 00041: val_loss did not improve from 0.91962

Epoch 00042: val_loss did not improve from 0.91962

Epoch 00043: val_loss did not improve from 0.91962

Epoch 00044: val_loss improved from 0.91962 to 0.82838, saving model to weights.best.gray_multi.hdf5

Epoch 00045: val_loss did not improve from 0.82838

Epoch 00046: val_loss improved from 0.82838 to 0.79367, saving model to weights.best.gray_multi.hdf5

Epoch 00047: val_loss did not improve from 0.79367

Epoch 00048: val_loss did not improve from 0.79367

Epoch 00049: val_loss did not improve from 0.79367

Epoch 00050: val_loss did not improve from 0.79367

Epoch 00051: val_loss did not improve from 0.79367

Epoch 00052: val_loss improved from 0.79367 to 0.68909, saving model to weights.best.gray_multi.hdf5

Epoch 00053: val_loss did not improve from 0.68909

Epoch 00054: val_loss did not improve from 0.68909

Epoch 00055: val_loss did not improve from 0.68909

Epoch 00056: val_loss did not improve from 0.68909

Epoch 00057: val_loss did not improve from 0.68909

Epoch 00058: val_loss did not improve from 0.68909

Epoch 00059: val_loss did not improve from 0.68909

Epoch 00060: val_loss improved from 0.68909 to 0.65689, saving model to weights.best.gray_multi.hdf5

Epoch 00061: val_loss did not improve from 0.65689

Epoch 00062: val_loss did not improve from 0.65689

Epoch 00063: val_loss did not improve from 0.65689

Epoch 00064: val_loss did not improve from 0.65689

Epoch 00065: val_loss did not improve from 0.65689

Epoch 00066: val_loss did not improve from 0.65689

Epoch 00067: val_loss did not improve from 0.65689

Epoch 00068: val_loss did not improve from 0.65689

Epoch 00069: val_loss did not improve from 0.65689

Epoch 00070: val_loss improved from 0.65689 to 0.56727, saving model to weights.best.gray_multi.hdf5

Epoch 00071: val_loss did not improve from 0.56727

Epoch 00072: val_loss did not improve from 0.56727

Epoch 00073: val_loss did not improve from 0.56727

Epoch 00074: val_loss did not improve from 0.56727

Epoch 00075: val_loss did not improve from 0.56727

Epoch 00076: val_loss did not improve from 0.56727

Epoch 00077: val_loss did not improve from 0.56727

Epoch 00078: val_loss did not improve from 0.56727

Epoch 00079: val_loss did not improve from 0.56727

Epoch 00080: val_loss did not improve from 0.56727

Epoch 00080: ReduceLROnPlateau reducing learning rate to 0.000800000037997961.

Epoch 00081: val_loss did not improve from 0.56727

Epoch 00082: val_loss did not improve from 0.56727

Epoch 00083: val_loss did not improve from 0.56727

Epoch 00084: val_loss did not improve from 0.56727

Epoch 00085: val_loss did not improve from 0.56727

Epoch 00086: val_loss did not improve from 0.56727

Epoch 00087: val_loss did not improve from 0.56727

Epoch 00088: val_loss did not improve from 0.56727

Epoch 00089: val_loss did not improve from 0.56727

Epoch 00090: val_loss improved from 0.56727 to 0.53355, saving model to weights.best.gray_multi.hdf5

Epoch 00091: val_loss did not improve from 0.53355

Epoch 00092: val_loss did not improve from 0.53355

Epoch 00093: val_loss did not improve from 0.53355

Epoch 00094: val_loss did not improve from 0.53355

Epoch 00095: val_loss did not improve from 0.53355

Epoch 00096: val_loss did not improve from 0.53355

Epoch 00097: val_loss did not improve from 0.53355

Epoch 00098: val_loss did not improve from 0.53355

Epoch 00099: val_loss did not improve from 0.53355

Epoch 00100: val_loss did not improve from 0.53355

Epoch 00100: ReduceLROnPlateau reducing learning rate to 0.0006400000303983689.

We should have an accuracy greater than 3% for the first target (letter) and greater than 25% for the second target (background).

In [81]:
hide_code
# Load the model with the best validation accuracy
gray_multi_model.load_weights('weights.best.gray_multi.hdf5')
# Calculate classification accuracy on the testing set
gray_multi_scores = gray_multi_model.evaluate(x_test4, y_test4_list, verbose=0)

print("Scores: \n" , (gray_multi_scores))
print("First label. Accuracy: %.2f%%" % (gray_multi_scores[3]*100))
print("Second label. Accuracy: %.2f%%" % (gray_multi_scores[4]*100))
Scores: 
 [0.585417575624898, 0.5349602406927193, 0.05045733699766877, 0.8308668076109936, 0.9901338971106413]
First label. Accuracy: 83.09%
Second label. Accuracy: 99.01%

Step 6. Keras Applications

Choose one of the keras applications and try to reach an accuracy greater than 30%

Color Images

In [37]:
hide_code
# Create bottleneck features
resize_x_train = np.array([scipy.misc.imresize(x_train[i], (48,48,3)) 
                           for i in range(0, len(x_train))]).astype('float32')
resize_x_valid = np.array([scipy.misc.imresize(x_valid[i], (48,48,3)) 
                           for i in range(0, len(x_valid))]).astype('float32')
resize_x_test = np.array([scipy.misc.imresize(x_test[i], (48,48,3)) 
                          for i in range(0, len(x_test))]).astype('float32')

vgg16_x_train = preprocess_input(resize_x_train)
vgg16_x_valid = preprocess_input(resize_x_valid)
vgg16_x_test = preprocess_input(resize_x_test)

vgg16_base_model = VGG16(weights='imagenet', include_top=False)
x_train_bn = vgg16_base_model.predict(vgg16_x_train)
x_valid_bn = vgg16_base_model.predict(vgg16_x_valid)
x_test_bn = vgg16_base_model.predict(vgg16_x_test)
In [ ]:
hide_code
# Save bottleneck features
#x_train_bn = np.squeeze(x_train_bn)
#x_valid_bn = np.squeeze(x_valid_bn)
#x_test_bn = np.squeeze(x_test_bn)

np.save('x_train_bn.npy', x_train_bn)
np.save('x_valid_bn.npy', x_valid_bn)
np.save('x_test_bn.npy', x_test_bn)
In [ ]:
hide_code
# Load bottleneck features
x_train_bn = np.load('x_train_bn.npy')
x_valid_bn = np.load('x_valid_bn.npy')
x_test_bn = np.load('x_test_bn.npy')
In [51]:
hide_code
def vgg16_model():
    model = Sequential()
    # TODO: Define a model architecture
    
    model.add(GlobalAveragePooling2D(input_shape=x_train_bn.shape[1:]))
    
    model.add(Dense(2048))
    model.add(LeakyReLU(alpha=0.02))
    model.add(Dropout(0.5))
        
    model.add(Dense(256))
    model.add(LeakyReLU(alpha=0.02))
    model.add(Dropout(0.5))
    
    model.add(Dense(33, activation='softmax'))
    # TODO: Compile the model     
    model.compile(loss='categorical_crossentropy',optimizer='nadam',metrics=['accuracy'])
    return model

vgg16_model = vgg16_model()
In [52]:
hide_code
# Create callbacks
vgg16_checkpointer = ModelCheckpoint(filepath='weights.best.vgg16.hdf5', 
                                     verbose=2,save_best_only=True)

vgg16_lr_reduction = ReduceLROnPlateau(monitor='val_loss', 
                                       patience=10,verbose=2,factor=0.8)
In [53]:
hide_code
# Fit the model 
vgg16_history = vgg16_model.fit(x_train_bn,y_train, 
                                validation_data=(x_valid_bn, y_valid),
                                epochs=70, batch_size=128, 
                                callbacks=[vgg16_checkpointer, 
                                           vgg16_lr_reduction], 
                                verbose=0);
Epoch 00001: val_loss improved from inf to 13.18783, saving model to weights.best.vgg16.hdf5

Epoch 00002: val_loss improved from 13.18783 to 2.88023, saving model to weights.best.vgg16.hdf5

Epoch 00003: val_loss improved from 2.88023 to 2.48637, saving model to weights.best.vgg16.hdf5

Epoch 00004: val_loss improved from 2.48637 to 2.27948, saving model to weights.best.vgg16.hdf5

Epoch 00005: val_loss improved from 2.27948 to 2.12670, saving model to weights.best.vgg16.hdf5

Epoch 00006: val_loss improved from 2.12670 to 1.99492, saving model to weights.best.vgg16.hdf5

Epoch 00007: val_loss improved from 1.99492 to 1.85828, saving model to weights.best.vgg16.hdf5

Epoch 00008: val_loss improved from 1.85828 to 1.76830, saving model to weights.best.vgg16.hdf5

Epoch 00009: val_loss improved from 1.76830 to 1.72557, saving model to weights.best.vgg16.hdf5

Epoch 00010: val_loss improved from 1.72557 to 1.70302, saving model to weights.best.vgg16.hdf5

Epoch 00011: val_loss did not improve from 1.70302

Epoch 00012: val_loss improved from 1.70302 to 1.63408, saving model to weights.best.vgg16.hdf5

Epoch 00013: val_loss improved from 1.63408 to 1.63218, saving model to weights.best.vgg16.hdf5

Epoch 00014: val_loss improved from 1.63218 to 1.61494, saving model to weights.best.vgg16.hdf5

Epoch 00015: val_loss improved from 1.61494 to 1.58993, saving model to weights.best.vgg16.hdf5

Epoch 00016: val_loss improved from 1.58993 to 1.56691, saving model to weights.best.vgg16.hdf5

Epoch 00017: val_loss did not improve from 1.56691

Epoch 00018: val_loss improved from 1.56691 to 1.54014, saving model to weights.best.vgg16.hdf5

Epoch 00019: val_loss improved from 1.54014 to 1.50607, saving model to weights.best.vgg16.hdf5

Epoch 00020: val_loss did not improve from 1.50607

Epoch 00021: val_loss did not improve from 1.50607

Epoch 00022: val_loss did not improve from 1.50607

Epoch 00023: val_loss improved from 1.50607 to 1.49742, saving model to weights.best.vgg16.hdf5

Epoch 00024: val_loss improved from 1.49742 to 1.46901, saving model to weights.best.vgg16.hdf5

Epoch 00025: val_loss improved from 1.46901 to 1.44264, saving model to weights.best.vgg16.hdf5

Epoch 00026: val_loss did not improve from 1.44264

Epoch 00027: val_loss did not improve from 1.44264

Epoch 00028: val_loss did not improve from 1.44264

Epoch 00029: val_loss improved from 1.44264 to 1.43446, saving model to weights.best.vgg16.hdf5

Epoch 00030: val_loss did not improve from 1.43446

Epoch 00031: val_loss did not improve from 1.43446

Epoch 00032: val_loss did not improve from 1.43446

Epoch 00033: val_loss did not improve from 1.43446

Epoch 00034: val_loss did not improve from 1.43446

Epoch 00035: val_loss did not improve from 1.43446

Epoch 00036: val_loss did not improve from 1.43446

Epoch 00037: val_loss did not improve from 1.43446

Epoch 00038: val_loss did not improve from 1.43446

Epoch 00039: val_loss did not improve from 1.43446

Epoch 00039: ReduceLROnPlateau reducing learning rate to 0.001600000075995922.

Epoch 00040: val_loss improved from 1.43446 to 1.42423, saving model to weights.best.vgg16.hdf5

Epoch 00041: val_loss did not improve from 1.42423

Epoch 00042: val_loss did not improve from 1.42423

Epoch 00043: val_loss did not improve from 1.42423

Epoch 00044: val_loss improved from 1.42423 to 1.39349, saving model to weights.best.vgg16.hdf5

Epoch 00045: val_loss did not improve from 1.39349

Epoch 00046: val_loss did not improve from 1.39349

Epoch 00047: val_loss did not improve from 1.39349

Epoch 00048: val_loss did not improve from 1.39349

Epoch 00049: val_loss did not improve from 1.39349

Epoch 00050: val_loss did not improve from 1.39349

Epoch 00051: val_loss did not improve from 1.39349

Epoch 00052: val_loss did not improve from 1.39349

Epoch 00053: val_loss did not improve from 1.39349

Epoch 00054: val_loss did not improve from 1.39349

Epoch 00054: ReduceLROnPlateau reducing learning rate to 0.0012800000607967378.

Epoch 00055: val_loss did not improve from 1.39349

Epoch 00056: val_loss did not improve from 1.39349

Epoch 00057: val_loss did not improve from 1.39349

Epoch 00058: val_loss did not improve from 1.39349

Epoch 00059: val_loss did not improve from 1.39349

Epoch 00060: val_loss did not improve from 1.39349

Epoch 00061: val_loss did not improve from 1.39349

Epoch 00062: val_loss did not improve from 1.39349

Epoch 00063: val_loss did not improve from 1.39349

Epoch 00064: val_loss did not improve from 1.39349

Epoch 00064: ReduceLROnPlateau reducing learning rate to 0.0010240000672638416.

Epoch 00065: val_loss did not improve from 1.39349

Epoch 00066: val_loss did not improve from 1.39349

Epoch 00067: val_loss did not improve from 1.39349

Epoch 00068: val_loss did not improve from 1.39349

Epoch 00069: val_loss did not improve from 1.39349

Epoch 00070: val_loss did not improve from 1.39349
In [54]:
hide_code
# Plot the training history
history_plot(vgg16_history, 0)
In [55]:
hide_code
# Load the model with the best validation accuracy
vgg16_model.load_weights('weights.best.vgg16.hdf5')
# Calculate classification accuracy on the testing set
vgg16_scores = vgg16_model.evaluate(x_test_bn,y_test)
print("Accuracy: %.2f%%" % (vgg16_scores[1]*100))
vgg16_scores
1419/1419 [==============================] - 0s 250us/step
Accuracy: 58.00%
Out[55]:
[1.5458970134572465, 0.5799859057353196]

Grayscaled Images

In [56]:
hide_code
# Create bottleneck features
resize_x_train2 = np.array([scipy.misc.imresize(x_train2_color[i], (48,48,3)) 
                            for i in range(0, len(x_train2_color))]).astype('float32')
resize_x_valid2 = np.array([scipy.misc.imresize(x_valid2_color[i], (48,48,3)) 
                            for i in range(0, len(x_valid2_color))]).astype('float32')
resize_x_test2 = np.array([scipy.misc.imresize(x_test2_color[i], (48,48,3)) 
                           for i in range(0, len(x_test2_color))]).astype('float32')

vgg16_x_train2 = preprocess_input(resize_x_train2)
vgg16_x_valid2 = preprocess_input(resize_x_valid2)
vgg16_x_test2 = preprocess_input(resize_x_test2)

vgg16_base_model2 = VGG16(weights='imagenet', include_top=False)
x_train_bn2 = vgg16_base_model2.predict(vgg16_x_train2)
x_valid_bn2 = vgg16_base_model2.predict(vgg16_x_valid2)
x_test_bn2 = vgg16_base_model2.predict(vgg16_x_test2)
In [ ]:
hide_code
# Save bottleneck features
#x_train_bn2 = np.squeeze(x_train_bn2)
#x_valid_bn2 = np.squeeze(x_valid_bn2)
#x_test_bn2 = np.squeeze(x_test_bn2)

np.save('x_train_bn2.npy', x_train_bn2)
np.save('x_valid_bn2.npy', x_valid_bn2)
np.save('x_test_bn2.npy', x_test_bn2)
In [ ]:
hide_code
# Load bottleneck features
x_train_bn2 = np.load('x_train_bn2.npy')
x_valid_bn2 = np.load('x_valid_bn2.npy')
x_test_bn2 = np.load('x_test_bn2.npy')
In [57]:
hide_code
def vgg16_gray_model():
    model = Sequential()
    
    # TODO: Define a model architecture
    model.add(GlobalAveragePooling2D(input_shape=x_train_bn2.shape[1:]))
    
    model.add(Dense(2048))
    model.add(LeakyReLU(alpha=0.01))    
    model.add(Dropout(0.5))
        
    model.add(Dense(256))
    model.add(LeakyReLU(alpha=0.01))
    model.add(Dropout(0.5))
    
    model.add(Dense(33,activation='softmax'))
    
    # TODO: Compile the model     
    model.compile(loss='categorical_crossentropy',optimizer='rmsprop',metrics=['accuracy'])
    return model

vgg16_gray_model = vgg16_gray_model()
In [58]:
hide_code
# Create callbacks
vgg16_gray_checkpointer = ModelCheckpoint(filepath='weights.best.vgg16_gray.hdf5', 
                                          verbose=2,save_best_only=True)
vgg16_gray_lr_reduction = ReduceLROnPlateau(monitor='val_loss', 
                                            patience=5,verbose=2,factor=0.5)
In [59]:
hide_code
# Fit the model 
vgg16_gray_history = vgg16_gray_model.fit(x_train_bn2,y_train2, 
                                          validation_data=(x_valid_bn2, y_valid2),
                                          epochs=70,batch_size=128, 
                                          callbacks=[vgg16_gray_checkpointer, 
                                                     vgg16_gray_lr_reduction], 
                                          verbose=0);
Epoch 00001: val_loss improved from inf to 14.41310, saving model to weights.best.vgg16_gray.hdf5

Epoch 00002: val_loss improved from 14.41310 to 3.19180, saving model to weights.best.vgg16_gray.hdf5

Epoch 00003: val_loss improved from 3.19180 to 2.90512, saving model to weights.best.vgg16_gray.hdf5

Epoch 00004: val_loss improved from 2.90512 to 2.66898, saving model to weights.best.vgg16_gray.hdf5

Epoch 00005: val_loss improved from 2.66898 to 2.56208, saving model to weights.best.vgg16_gray.hdf5

Epoch 00006: val_loss improved from 2.56208 to 2.39597, saving model to weights.best.vgg16_gray.hdf5

Epoch 00007: val_loss improved from 2.39597 to 2.20028, saving model to weights.best.vgg16_gray.hdf5

Epoch 00008: val_loss improved from 2.20028 to 2.15364, saving model to weights.best.vgg16_gray.hdf5

Epoch 00009: val_loss improved from 2.15364 to 2.05387, saving model to weights.best.vgg16_gray.hdf5

Epoch 00010: val_loss improved from 2.05387 to 1.95761, saving model to weights.best.vgg16_gray.hdf5

Epoch 00011: val_loss did not improve from 1.95761

Epoch 00012: val_loss improved from 1.95761 to 1.87979, saving model to weights.best.vgg16_gray.hdf5

Epoch 00013: val_loss improved from 1.87979 to 1.76557, saving model to weights.best.vgg16_gray.hdf5

Epoch 00014: val_loss did not improve from 1.76557

Epoch 00015: val_loss did not improve from 1.76557

Epoch 00016: val_loss improved from 1.76557 to 1.72918, saving model to weights.best.vgg16_gray.hdf5

Epoch 00017: val_loss improved from 1.72918 to 1.69652, saving model to weights.best.vgg16_gray.hdf5

Epoch 00018: val_loss did not improve from 1.69652

Epoch 00019: val_loss improved from 1.69652 to 1.64543, saving model to weights.best.vgg16_gray.hdf5

Epoch 00020: val_loss did not improve from 1.64543

Epoch 00021: val_loss improved from 1.64543 to 1.64085, saving model to weights.best.vgg16_gray.hdf5

Epoch 00022: val_loss did not improve from 1.64085

Epoch 00023: val_loss did not improve from 1.64085

Epoch 00024: val_loss improved from 1.64085 to 1.62769, saving model to weights.best.vgg16_gray.hdf5

Epoch 00025: val_loss did not improve from 1.62769

Epoch 00026: val_loss did not improve from 1.62769

Epoch 00027: val_loss did not improve from 1.62769

Epoch 00028: val_loss did not improve from 1.62769

Epoch 00029: val_loss did not improve from 1.62769

Epoch 00029: ReduceLROnPlateau reducing learning rate to 0.0005000000237487257.

Epoch 00030: val_loss did not improve from 1.62769

Epoch 00031: val_loss improved from 1.62769 to 1.62578, saving model to weights.best.vgg16_gray.hdf5

Epoch 00032: val_loss did not improve from 1.62578

Epoch 00033: val_loss did not improve from 1.62578

Epoch 00034: val_loss did not improve from 1.62578

Epoch 00035: val_loss did not improve from 1.62578

Epoch 00036: val_loss did not improve from 1.62578

Epoch 00036: ReduceLROnPlateau reducing learning rate to 0.0002500000118743628.

Epoch 00037: val_loss did not improve from 1.62578

Epoch 00038: val_loss did not improve from 1.62578

Epoch 00039: val_loss did not improve from 1.62578

Epoch 00040: val_loss did not improve from 1.62578

Epoch 00041: val_loss did not improve from 1.62578

Epoch 00041: ReduceLROnPlateau reducing learning rate to 0.0001250000059371814.

Epoch 00042: val_loss did not improve from 1.62578

Epoch 00043: val_loss did not improve from 1.62578

Epoch 00044: val_loss did not improve from 1.62578

Epoch 00045: val_loss did not improve from 1.62578

Epoch 00046: val_loss did not improve from 1.62578

Epoch 00046: ReduceLROnPlateau reducing learning rate to 6.25000029685907e-05.

Epoch 00047: val_loss did not improve from 1.62578

Epoch 00048: val_loss did not improve from 1.62578

Epoch 00049: val_loss did not improve from 1.62578

Epoch 00050: val_loss did not improve from 1.62578

Epoch 00051: val_loss did not improve from 1.62578

Epoch 00051: ReduceLROnPlateau reducing learning rate to 3.125000148429535e-05.

Epoch 00052: val_loss did not improve from 1.62578

Epoch 00053: val_loss did not improve from 1.62578

Epoch 00054: val_loss did not improve from 1.62578

Epoch 00055: val_loss did not improve from 1.62578

Epoch 00056: val_loss did not improve from 1.62578

Epoch 00056: ReduceLROnPlateau reducing learning rate to 1.5625000742147677e-05.

Epoch 00057: val_loss did not improve from 1.62578

Epoch 00058: val_loss did not improve from 1.62578

Epoch 00059: val_loss did not improve from 1.62578

Epoch 00060: val_loss did not improve from 1.62578

Epoch 00061: val_loss did not improve from 1.62578

Epoch 00061: ReduceLROnPlateau reducing learning rate to 7.812500371073838e-06.

Epoch 00062: val_loss did not improve from 1.62578

Epoch 00063: val_loss did not improve from 1.62578

Epoch 00064: val_loss did not improve from 1.62578

Epoch 00065: val_loss did not improve from 1.62578

Epoch 00066: val_loss did not improve from 1.62578

Epoch 00066: ReduceLROnPlateau reducing learning rate to 3.906250185536919e-06.

Epoch 00067: val_loss did not improve from 1.62578

Epoch 00068: val_loss did not improve from 1.62578

Epoch 00069: val_loss did not improve from 1.62578

Epoch 00070: val_loss did not improve from 1.62578
In [60]:
hide_code
# Plot the training history
history_plot(vgg16_gray_history, 0)
In [61]:
hide_code
# Load the model with the best validation accuracy
vgg16_gray_model.load_weights('weights.best.vgg16_gray.hdf5')
# Calculate classification accuracy on the testing set
vgg16_gray_scores = vgg16_gray_model.evaluate(x_test_bn2, y_test2)
print("Accuracy: %.2f%%" % (vgg16_gray_scores[1]*100))
vgg16_gray_scores
1419/1419 [==============================] - 0s 255us/step
Accuracy: 59.41%
Out[61]:
[1.694364378576635, 0.5940803382243801]

Step 7. Predictions

Display predictions for the models with the best accuracy.

Color Images

In [65]:
hide_code
# Create a list of symbols
symbols = ['а','б','в','г','д','е','ё','ж','з','и','й',
           'к','л','м','н','о','п','р','с','т','у','ф',
           'х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я']
In [66]:
hide_code
# Model predictions for the testing dataset
y_test_predict = model.predict_classes(x_test)
In [67]:
hide_code
# Display true labels and predictions
fig = plt.figure(figsize=(18, 18))
for i, idx in enumerate(np.random.choice(x_test.shape[0], size=16, replace=False)):
    ax = fig.add_subplot(4, 4, i + 1, xticks=[], yticks=[])
    ax.imshow(np.squeeze(x_test[idx]))
    pred_idx = y_test_predict[idx]
    true_idx = np.argmax(y_test[idx])
    ax.set_title("{} ({})".format(symbols[pred_idx], symbols[true_idx]),
                 color=("#4876ff" if pred_idx == true_idx else "darkred"))

Grayscaled Images

In [68]:
hide_code
# Model predictions for the testing dataset
y_test2_predict = gray_model.predict_classes(x_test2)
In [70]:
hide_code
# Display true labels and predictions
fig = plt.figure(figsize=(18, 18))
for i, idx in enumerate(np.random.choice(x_test2.shape[0], size=16, replace=False)):
    ax = fig.add_subplot(4, 4, i + 1, xticks=[], yticks=[])
    ax.imshow(np.squeeze(x_test2[idx]), cmap=cm.bone)
    pred_idx = y_test2_predict[idx]
    true_idx = np.argmax(y_test2[idx])
    ax.set_title("{} ({})".format(symbols[pred_idx], symbols[true_idx]),
                 color=("#4876ff" if pred_idx == true_idx else "darkred"))