aboutsummaryrefslogtreecommitdiff
path: root/lenet.py
blob: c9ef78cc8bf25f2aa4a4231788e54426d385418b (plain)
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
from __future__ import print_function
import tensorflow.keras as keras
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D
from tensorflow.keras import backend as K
from tensorflow.keras import optimizers
import matplotlib.pyplot as plt
from tensorflow.keras.metrics import categorical_accuracy
import numpy as np
import random

def import_mnist():
  from tensorflow.examples.tutorials.mnist import input_data
  mnist = input_data.read_data_sets("MNIST_data/", reshape=False)
  X_train, y_train = mnist.train.images, mnist.train.labels
  X_validation, y_validation = mnist.validation.images, mnist.validation.labels
  X_test, y_test = mnist.test.images, mnist.test.labels
  y_train = keras.utils.to_categorical(y_train, 10)
  y_validation = keras.utils.to_categorical(y_validation, 10)  
  y_test = keras.utils.to_categorical(y_test, 10)
  return X_train, y_train, X_validation, y_validation, X_test, y_test

def plot_images(images, cls_true, cls_pred=None):
    assert len(images) == len(cls_true) == 9
    img_shape = (32, 32)
    # Create figure with 3x3 sub-plots.
    fig, axes = plt.subplots(3, 3)
    fig.subplots_adjust(hspace=0.3, wspace=0.3)
    for i, ax in enumerate(axes.flat):
        # Plot image.
        ax.imshow(images[i].reshape(img_shape), cmap='binary')
        # Show true and predicted classes.
        if cls_pred is None:
            xlabel = "True: {0}".format(cls_true[i])
        else:
            xlabel = "True: {0}, Pred: {1}".format(cls_true[i], cls_pred[i])
        ax.set_xlabel(xlabel)        
        ax.set_xticks([])
        ax.set_yticks([])  
    plt.show()

def plot_example_errors(y_pred, y_true, X_test):
    y_pred = np.argmax(y_pred, axis=1)
    y_true = np.argmax(y_true, axis=1)
    correct_prediction = np.equal(y_pred, y_true)
    incorrect = np.equal(correct_prediction, False)
    images = X_test[incorrect]
    cls_pred = y_pred[incorrect]
    cls_true = y_true[incorrect]
    plot_images(images=images[0:9], cls_true=cls_true[0:9], cls_pred=cls_pred[0:9].astype(np.int))

def get_lenet(shape):
  model = keras.Sequential()
  model.add(Conv2D(filters=6, kernel_size=(3, 3), activation='relu', input_shape=shape))
  model.add(AveragePooling2D())
  
  model.add(Conv2D(filters=16, kernel_size=(3, 3), activation='relu'))
  model.add(AveragePooling2D())
  model.add(Flatten())
  
  model.add(Dense(units=120, activation='relu'))
  model.add(Dense(units=84, activation='relu'))
  model.add(Dense(units=10, activation = 'softmax'))
  return model

def plot_history(history, metric = None):
  # Plots the loss history of training and validation (if existing)
  # and a given metric
  
  if metric != None:
    fig, axes = plt.subplots(2,1)
    axes[0].plot(history.history[metric])
    try:
      axes[0].plot(history.history['val_'+metric])
      axes[0].legend(['Train', 'Val'])
    except:
      pass
    axes[0].set_title('{:s}'.format(metric))
    axes[0].set_ylabel('{:s}'.format(metric))
    axes[0].set_xlabel('Epoch')
    fig.subplots_adjust(hspace=0.5)
    axes[1].plot(history.history['loss'])
    try:
      axes[1].plot(history.history['val_loss'])
      axes[1].legend(['Train', 'Val'])
    except:
      pass
    axes[1].set_title('Model Loss')
    axes[1].set_ylabel('Loss')
    axes[1].set_xlabel('Epoch')
  else:
    plt.plot(history.history['loss'])
    try:
      plt.plot(history.history['val_loss'])
      plt.legend(['Train', 'Val'])
    except:
      pass
    plt.title('Model Loss')
    plt.ylabel('Loss')
    plt.xlabel('Epoch')

def train_classifier(x_train, y_train, x_val, y_val, batch_size=128, epochs=100, metrics=[categorical_accuracy], optimizer = None):
  shape = (32, 32, 1)

  # Pad data to 32x32 (MNIST is 28x28)
  x_train = np.pad(x_train, ((0,0),(2,2),(2,2),(0,0)), 'constant')
  x_val = np.pad(x_val, ((0,0),(2,2),(2,2),(0,0)), 'constant')

  model = get_lenet(shape)

  if optimizer == None:
      optimizer = optimizers.SGD(lr=0.001, decay=1e-6, momentum=0.9, nesterov=True)

  model.compile(loss='categorical_crossentropy', metrics=metrics, optimizer=optimizer)
  
  history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data = (x_val, y_val))
  plot_history(history)
  return model 

def test_classifier(model, x_test, y_true):
  x_test = np.pad(x_test, ((0,0),(2,2),(2,2),(0,0)), 'constant')
  y_pred = model.predict(x_test)
  print(categorical_accuracy(y_true, y_pred))
  plot_example_errors(y_pred, y_true, x_test)

# If file run directly, perform quick test
if __name__ == '__main__':
  x_train, y_train, x_val, y_val, x_t, y_t = import_mnist()
  model = train_classifier(x_train[:100], y_train[:100], x_val, y_val, epochs=1)
  test_classifier(model, x_t, y_t)