CNN (Convolutional Neural network) using Gluon

CNN (Convolutional Neural network) using Gluon

Introduction:

Convolutional Neural Network is deep learning networks, which have achieved an excellent result on images recognition, images classifications. objects detections, face recognition, etc. CNN is everywhere and its most popular deep learning architecture. CNN is majorly used in solving the image data challenge and video analytics too. Any data that has spatial relationships are ripe for applying CNN.

In the previous chapter, we covered the basic machine learning techniques or algorithms to solve regression and classification problem. In this chapter, we will explore the deep learning architecture such as CNN (Convolutional Neural Network). CNN’s are a biologically inspired variant of MLPs. CNN aka ConvNet, in this chapter we will use this term interchangeably. In this chapter, we will explore the below points.

  • Introduction of CNN
  • CNN architecture
  • Gluon API for CNN
  • CNN implementation with gluon
  • Image segmentation using CNN

CNN Architecture:

CNN’s are regularised version of multilayer perceptrons. MLPs are the fully connected neural networks, means each neuron in one layer has a connection to all neuron in the next layer. CNN’s design inspired by vision processing of living organisms. Without conscious effort, we make predictions about everything we see and act upon them. When we see something, we label every object based on what we have learned in the past

Hubel and Wiesel in the 1950s and 1960s showed that the How cat’s visual cortex work. The animal visual cortex is the most powerful visual processing system in existence. As we all know that the visual cortex contains a complex arrangement of cells. These cells are sensitive to small sub-regions of the visual field, called a receptive field. The sub-regions are tiled to cover the entire visual field. These cells act as your local filters over the input space and are well-suited to exploit the strong spatially local correlation present in natural images. This is just a higher level intro of How cortex work. CNN is designed to recognize visual patterns directly from pixel images with minimal preprocessing.

Now let us make things simple, think about how our brain thinks and the human brain is a very powerful machine. Everyone works differently and it’s clear that we all have our own ways of learning and taking in new information. “A picture is worth a thousand words” is an English language adage. It refers to the notion that a complex idea can be conveyed with just a single picture, this picture conveys its meaning or essence more effectively than a description does. We see plenty of images every day, our brain is processing them and store them. But what about the machine, how a machine can understand, process and store meaningful insight from that image. In simple term, each image is an arrangement of a pixel, arranged in a special order. If some order or color get changed that effect the image as well. From the above explanation, you can understand that images in machine represent and processed in the form of pixels. Before CNN’s comes into the form it’s very hard to do image processing. Scientists around the world have been trying to find different ways to make computers to extract meaning from visual data(image, video) for about 60+ years from now, and the history of CV (Computer Vision), which is deeply fascinating.

The most fascinating paper was published by two neurophysiologists — David Hubel and Torsten Wiesel — in 1959 as I mentioned above the paper titled was “Receptive fields of single neurons in the cat’s striate cortex”. This duo ran pretty experiments over a cat. They placed electrodes into the primary visual cortex area of an anesthetized cat’s brain and observed, or at least tried to, the neuronal activity in that region while showing the animal various images. Their first efforts were fruitless; they couldn’t get the nerve cells to respond to anything. After a few months of research, they noticed accidentally they caught that one neuron fired as they were slipping a new slide into the projector. Hubel and Wiesel realized that what got the neuron excited was the movement of the line created by the shadow of the sharp edge of the glass slide.

[Image Source: https://commons.wikimedia.org/wiki/File:Human_visual_pathway.svg]

The researchers observed, through their experimentation, that there are simple and complex neurons in the primary visual cortex and that visual processing always starts with simple structures such as oriented edges. This is the much simpler and familiar explanation. The invention does not happen overnight it took years and its evolutionary process to get the groundbreaking the result.

After Hubel and Wiesel there is nothing happen groundbreaking on their idea for a long time. In 1982, David Marr, a British neuroscientist, published another influential paper — “Vision: A computational investigation into the human representation and processing of visual information”. David gave us the next important insight i.e. vision is hierarchical. David introduced a framework for a vision where low-level algorithms that detect edges, curves, corners, etc., and that are used as stepping stones towards to form a high-level understanding of the image.

David Marr’s representational framework:

  • A Primal Sketch of an image, where edges, bars, boundaries, etc., are represented (inspired by Hubel and Wiesel’s research);
  • A 2½D sketch representation where surfaces, information about depth and discontinuities on an image are pieced together;
  • A 3D model that is hierarchically organized in terms of surface and volumetric primitives.

Davids framework was very abstract and high-level and there is no mathematical modeling was given that could be used in artificial learning. It’s a hypothesis. At the same time, Japanese computer scientist, Kunihiko Fukushima, also developed a framework inspired by Hubel and Wiesel. This method is a self-organizing artificial network of simple and complex cells that could recognize patterns and be unaffected by position shifts. The network is Neocognitron included several convolutional layers and whose receptive fields had weight. Fukushima’s Neocognitron the first ever deep neural network and it is a grandfather of today’s convents. And a few years later in 1989, a French scientist Yann LeCun applied a backpropagation style learning algorithm to Fukushima’s neocognitron architecture. After a few more trails and error and Yann released LeNet-5. LeCun applied his architecture and developed and released a commercial product for reading zip codes. Around 1999, scientist and researchers trying to do visual data analysis using Marr’s proposed method instead of feature-based object recognition.

This is just a brief overview and important milestones we have covered that will help us to understand How CNN was evolved. Let us talk about CNN’s architecture, like an every artificial neural network architecture this also having input, hidden layers and output layer. The hidden layers consist of a series of convolutional layers that convolve with multiplication or other dot product. CNN’s are a specialized kind of neural network for processing data that has a grid like a topology, like time series data, which can be thought as one-dimensional array (vector) grid taking samples at regular time intervals but image data can be thought of as a 2-D grid of pixels (matrix). The name “Convolutional neural network” indicates that the network employs a mathematical operation called convolution. Arranging the image in the 2-D grid of pixels is depending on the whether we are looking at a black and white or color image, we might have either one or multiple numerical values corresponding to each pixel. CNN-based neural network architectures now dominate the field of computer vision to such a level that hardly anyone these days would develop a commercial application or enter a competition or hackathon related to image recognition, object detection, or semantic segmentation, without basing their approach on them. There are so many modern CNN networks owe their designs to inspirations from biology. CNNs are very good in strong predictive performance and tend to be computationally efficient because easy to parallelize and has very fewer inputs as compared to a dense layer. If we use a fully connected neural network to deal with the image recognization then we need a huge number of parameters and hidden layers to address this. let us consider we have an image of 28*28*3 then the total number of weights in the hidden layer will be 2352 and it will lead to overfitting that’s why we are not using a fully connected neural network to process image data.

In the convolutional neural network, the neuron in the layer will be connected to a small region of the layer. CNN the neuron in a layer will only be connected small region of the layer before it, instead of all the neuron in a fully connected network.

The above fig shows the general architecture of CNNs. CNN is a type of feed forward artificial neural network in which the connectivity pattern between the neurons inspired by the animal visual cortex. The basic idea is that some of the neurons from the cortex will fire when exposed horizontal and some cortex will fire when exposed vertically and similarly some will fire when exposed diagonal edges and this the motivation behind the connectivity pattern.

In general, CNN has four layers.

  1. Convolution layer
  2. Max Pooling layer
  3. ReLU layer
  4. Fully connected

The main problem with image data is, images won’t always have the same images. There can be certain deformations. Similarly to how a child recognize objects, we can show a child a dog with black color and we told him this is a dog and on the next day when some other pet with black color comes to our house with four legs He has recognized with dog but actual that is not a dog and its goat. Similarly, we have to show some samples to find a common pattern to identify the objects. We have to show millions of pictures to an algorithm to understand the data and detect the object, with the help of these millions of a records algorithm can generalize the inputs and make predictions for the new observations.

Machine see in a different way than humans do. Their world consists of only 0’s and 1’s. CNNs have a different architecture than regular artificial neural networks. In the regular full connected neural network, we putting the input through the series of hidden layers and reach to the fully connected output layer that represents the predictions. CNNs following a bit different approach. All the layers of CNNs are organized in 3 dimensions: width, height, and depth and neurons in the one layer do not connect to all neurons in the next layer but only the small portion of it and the output layer will be the reduced to a single vector of probability scores, organized along the depth dimension. Below fig, illustrate NN(neural network) vs CNN.

As we said earlier, the output can be a single class or a probability of classes that best describes the image. Now, the hard part is understanding what each of these layers does. Let us understand this.

CNNs have two components

  1. Feature extraction part (The hidden layers): The hidden layer perform a series of convolutions and pooling operations during which the features are detected. If you had a picture of a human face, this is the part of where the network would recognize two eyes, nose, lips, and nose, etc.
  2. The Classification part (Fully connected output layer): As we said last classification layer is fully connected layers will serve as a classifier on top of extracted features.

Convolution layer:

Convolution layer is the main building blocks of CNN, as we said convolution refers to the combination of two mathematical functions to produce a third function. Convolution is performed on the input data with the use of filters or kernels ( filters or kernels term people use interchangeably). Apply filters over the input data to produce a feature map. Convolution is sliding over the input. At each and every location, matrix multiplication is performed and sums the result into the feature map.

Note that in the above example an image is 2 dimensional with width and height (black and white image). If the image is colored, it is considered to have one more dimension for RGB color. For that reason, 2-D convolutions are usually used for black and white images, while 3-D convolutions are used for colored images. Let us start with (5*5) input image with no padding and we use a (3*3) convolution filter to get an output image. In the first step, the filter sliding over the matrix and in the filter each element is multiplied with an element in the corresponding location. Then you sum all the results, which is one output value. Then, you repeat this process the same step by moving the filter by one column. And you get the second output. The step size as the filter slides across the image is called a stride. In this example Here, the stride is 1. The same operation is repeated to get the third output. A stride size greater than 1 will always downsize the image. If the size is 1, the size of the image will stay the same. In the above operation, we have shown you the operation in 2D, but in real life applications mostly, convolutions are performed in a 3D matrix with a dimension for width, height, width. Depth is a dimension because of the colors channels used in an image (Red Green Blue).

We perform a number of convolutions on our input matrix and for each operation uses a different kernel (filter), the result does store in feature maps. All feature maps put into a bucket together as a final output of convolutional layer. CNNs uses ReLU is the activation function and output of the convolution passed through the activation function. As I mentioned early in the paragraph the convolution filter can slide over the input matrix. Stride is the decisive steps in a specified direction. Stride is the size of the step the convolution filter moves each time. In general, people refer to stride value as 1, meaning the filter slides pixel by pixel.

The animation above shows stride size 1. Increasing the stride size, your filter is sliding over the input with a larger gap and thus has less overlap between the cells. The size of the feature map is always less than the input matrix and this leads to shrinking our feature map. To prevent shrinking of our feature map matrix we use padding. Padding means a layer of zero value pixels is added to surround the input with zeros. Padding helps us to improve performance, makes sure the kernel and stride size will fit in the input and also keeping the spatial size constant after performing convolution.

Max Pooling layer:

After the convolution operation, the next operation is pooling layer. Max pooling is a sample-based discretization process. If you can see the first diagram in that after every convolution layer there is max pooling layer. Max pooling layer is useful to controls the overfitting and shortens the training time. The pooling function continuously reduce the dimensionality to reduce the number of parameters and number of computation in the network. Max pooling is done by applying a max filter to usually non-overlapping subregions of the initial representation. It reduces the computational cost by reducing the number of parameters to learn and provides basic translation invariance to the internal representation.

Let’s say we have a 4×4 matrix representing our initial input.
Let’s say, as well, that we have a 2×2 filter that we’ll run over our input. We’ll have a stride of 2 (meaning the (dx, dy) for stepping over our input will be (2, 2)) and won’t overlap regions. For each of the regions represented by the filter, we will take the max of that region and create a new, output matrix where each element is the max of a region in the original input.

Max Pooling takes the maximum value in each window. These window sizes need to be specified beforehand. This decreases the feature map size while at the same time keeping the significant information.

ReLU layer:

The Rectified Linear Unit(ReLU) has become very popular in the last few years. ReLU is activation function similarly we have been using different activation function is a different artificial neural network. Activation function aka transfer function. The ReLU is the most used activation function in the world right now. Since it is used in almost all the convolutional neural networks or deep learning.

The ReLU function is ?(?)=max(0,?). As you can see, the ReLU is half rectified (from bottom). f(z) is zero when z is less than zero and f(z) is equal to z when z is above or equal to zero.

The ReLUs range is from 0 to infinity. ReLUs improve neural networks is by speeding up training. ReLU is idempotent. ReLU is the max function(x,0) with input x e.g. matrix from a convolved image. ReLU then sets all negative values in the matrix x to zero and all other values are kept constant. ReLU is executed after the convolution and therefore a nonlinear activation function like tanh or sigmoid. Each activation function takes a single number and performs a certain fixed mathematical operation on it. In simple words, the rectifier function does to an image like this is remove all the black elements from it keeping only positive value. We expect that any positive value will be returned unchanged whereas an input value of 0 or a negative value will be turned as the value 0. ReLU can allow your model to account for non-linearities and interactions so well. In gluon API we can use ReLU as inbuild implementation from Gluon.

net.add(gluon.nn.Dense(64, activation="relu"))

We can use a simple sample code of the ReLU function.

# rectified linear function
def rectified(x):
  return max(0.0, x)

Fully connected layer:

The fully connected layer is the fully connected neural network layer. This is also referred to as the classification layer. After completion of convolutional, ReLU and max-pooling layers, the classification part consists of a few fully connected layers. The fully connected layers can only accept 1 -Dimensional data. To convert our 3-D data to 1-D, we use the function in Python. This essentially arranges our 3-D volume into a 1-D vector.

This layer gives or returns us the output which is probabilistic value.

Types of CNN Architectures:

In the above section, we explained CNN general architecture but there are different flavors of CNN based some different combinations of layers. Let us try to explore those some useful and famous CNNs architectural style to solve some complex problem. CNNs are designed o recognize the visual patterns with minimal preprocessing from pixel images. The ImageNet project is a large visual database designed for object recognization research. This project runs an annual software contest the ImageNet Large Scale Visual Recognition Challenge (ILSVRC), where software programmer, researcher compete to correctly detect objects. In this section, we are exploring CNN architectures of ILSVRC top competitors.

Let us look into this picture this will give you a broad overview of how evaluation happen.

1. LeNet-5 — Leun et al

LeNet-5 is a 7 layer Convolutional neural network by LeCun et al in 1998. This was deployed in real life financial banking project to recognize handwritten digits on cheques. Image digitized in 32×32 pixel greyscale input images. The ability to process higher resolution images requires larger and more convolutional layers, so this technique is constrained by the availability of computing resources. At that time, the computational capacity was limited and hence the technique wasn’t scalable to large scale images.

2. AlexNet — Krizhevsky et al

AlexNet is a Convolutional neural network by Krizhevsky et al in 2012. It is outperformed significantly in all the prior competitors and won the ILSVRC challenge by reducing the top-5 error loss from 26% to 15.3%. The network was very similar to LeNet but was much more deeper with more filters per layer and had around 60 million parameters.

It consisted of 11×11, 5×5,3×3, convolutions, max pooling, dropout, data augmentation, ReLU activations, SGD with momentum. ReLU activation layer is attached after each every convolutional & fully connected layer except the last softmax layer. The figure certainly looks a bit scary. This is because the network was split into two halves, each trained simultaneously on two different GPUs. AlexNet was trained for 6 days simultaneously on two Nvidia Geforce GTX 580 GPUs. AlexNet was designed by the SuperVision group, consisting of Alex Krizhevsky, Geoffrey Hinton, and Ilya Sutskever. More simple picture

In AlexNet consist of 5 Convolutional Layers and 3 Fully Connected Layers. These 8 layers combined with two new concepts at that time — MaxPooling and ReLU activation gave their model edge results.

3. ZFNet –

The ILSVRC 2013 winner was also a CNN which is known as ZFNet. It achieved a top-5 error rate of 14.8% which is now already half of the prior mentioned non-neural error rate. They achieved this by tweaking the hyper-parameters of AlexNet while maintaining the same structure with additional Deep Learning elements. As this is similar to AlexNet and have some additional deep learning elements such as dropout, augmentation and Stochastic Gradient Descent with momentum with tweaking the hyperparameters.

4. VGGNet — Simonyan et al

The runner up of 2014 ILSVRC challenge is named VGGNet, because of the simplicity of its uniform architecture, it appeals to a simpler form of a deep convolutional neural network. VGGNet was developed by Simonyan and Zisserman. VGGNet consists of 16 convolutional layers and is very appealing because of its very uniform architecture. The architecture is very much similar to AlexNet with only 3×3 convolutions, but lots of filters. VGGNet Trained on 4 GPUs for 2–3 weeks. The weight configuration of the VGGNet is publicly available and has been used in many other applications and challenges as a baseline feature extractor. VGGNet consists of 138 million parameters, which can be a bit challenging to handle. As the weight configurations are available publicly so, this network is one of the most used choices for feature extraction from images.

VGGNet has 2 simple rules

  1. Each Convolutional layer has configuration — kernel size = 3×3, stride = 1×1, padding = same. The only thing that differs is a number of filters.
  2. Each Max Pooling layer has configuration — windows size = 2×2 and stride = 2×2. Thus, we half the size of the image at every Pooling layer.

5. GoogLeNet/Inception –

The winner of the 2014 ILSVRC competition GoogleNet (Inception v1). achieved a top-5 error rate of 6.67% loss. GoogleNet used an inception module, a novel concept, with smaller convolutions that allowed the reduction of the number of parameters to a mere 4 million. GoogleNet was very close to the human level performance which the organizers of the challenge were now forced to evaluate. Googlenet was inspired by CNN LeNet but implemented a novel element which is nickname an inception module. It is used in batch normalization, image distortions, and RMSprop.

There are two diagrams which are here to understand and visualize GoogleNet very well.

5. ResNet — Kaiming He et al

The 2015 ILSVRC competition brought about a top-5 error rate of 3.57%, which is lower than the human error on top-5. The ResNet (Residual Network) model used by Kaiming He et al at the competition. The network introduced a novel approach called skip connections. Skip connections are also known as gated units or gated recurrent units. this technique they were able to train a NN with 152 layers while still having lower complexity than VGGNet.

It achieves a top-5 error rate of 3.57% which beats human-level performance on this dataset. ResNet has residual connections. The idea came out as a solution to an observation — Deep neural networks perform worse as we keep on adding a layer. The observation brought about a hypothesis: direct mappings are hard to learn. So instead of learning mapping between the output of the layer and its input, learn the difference between them learn the residual.

The Residual neural network uses 1×1 convolutions to increase and decrease the dimensionality of the number of channels.

CNN using Gluon:

As part of this example, we are exploring MNIST data set using CNN. This is the best example to make our hands dirty with Gluon API layer to build CNNs. There four important part we have always consider while building any CNNs.

  1. The kernel size
  2. The filter count (i.e how many filters do we want to use)
  3. Stride (how big steps of the filters)
  4. Padding

Let us deep dive into MNIST using CNN. Recognize handwritten digits using Gluon API using CNNs.

To start with the example we need MNIST data set and need to import some python, gluon module.

import mxnet as mx
import numpy as np
import mxnet as mx
from mxnet import nd, gluon, autograd
from mxnet.gluon import nn
# Select a fixed random seed for reproducibility
mx.random.seed(42)
def data_xform(data):
    """Move channel axis to the beginning, cast to float32, and normalize to [0, 1]."""
    return nd.moveaxis(data, 2, 0).astype('float32') / 255
train_data = mx.gluon.data.vision.MNIST(train=True).transform_first(data_xform)
val_data = mx.gluon.data.vision.MNIST(train=False).transform_first(data_xform)

The above code can download MNIST data set at the default location (this could be.mxnet/datasets/mnist/ in the home directory) and creates Dataset objects, training data set (train_data), and validation data set (val_data) for training and validation we need both two datasets. We can use transform_first() method, to moves the channel axis of the images to the beginning ((28, 28, 1) → (1, 28, 28)) and cast them into the float32 and rescales them from [0,255] to [0,1]. The MNIST dataset is very small that’s why we loaded that in memory.

set the context

ctx = mx.gpu(0) if mx.context.num_gpus() > 0 else mx.cpu(0)

Then we need a training data set and validation data set with batch size 1 and shuffle the training set and non-shuffle validation dataset.

conv_layer = nn.Conv2D(kernel_size=(3, 3), channels=32, in_channels=16, activation='relu')
print(conv_layer.params)

define the convolutional layer in this example we considering 2-D dataset so, this one is 2-D convolutional with ReLU activation function. CNN is a more structured weight representation. Instead of connecting all inputs to all outputs, the characteristic,

# define like a alias
metric = mx.metric.Accuracy()
loss_function = gluon.loss.SoftmaxCrossEntropyLoss()

We are using softmax cross-entropy as a loss function.

lenet = nn.HybridSequential(prefix='LeNet_')
with lenet.name_scope():
    lenet.add(
        nn.Conv2D(channels=20, kernel_size=(5, 5), activation='tanh'),
        nn.MaxPool2D(pool_size=(2, 2), strides=(2, 2)),
        nn.Conv2D(channels=50, kernel_size=(5, 5), activation='tanh'),
        nn.MaxPool2D(pool_size=(2, 2), strides=(2, 2)),
        nn.Flatten(),
        nn.Dense(500, activation='tanh'),
        nn.Dense(10, activation=None),
    )

Filters can learn to detect small local structures like edges, whereas later layers become sensitive to more and more global structures. Since images often contain a rich set of such features, it is customary to have each convolution layer employ and learn many different filters in parallel, so as to detect many different image features on their respective scales. It’s good to have a more than one filter and do apply filters in parallel. The above code defines a CNN architecture called LeNet. The LeNet architecture is a popular network known to work well on digit classification tasks. We will use a version that differs slightly from the original in the usage of tanh activations instead of sigmoid.

Likewise, input can already have multiple channels. In the above example, the convolution layer takes an input image with 16 channels and maps it to an image with 32 channels by convolving each of the input channels with a different set of 32 filters and then summing over the 16 input channels. Therefore, the total number of filter parameters in the convolution layer is channels * in_channels * prod(kernel_size), which amounts to 4608 in the above example. Another characteristic feature of CNNs is the usage of pooling, means summarizing patches to a single number. This step lowers the computational burden of training the network, but the main motivation for pooling is the assumption that it makes the network less sensitive to small translations, rotations or deformations of the image. Popular pooling strategies are max-pooling and average-pooling, and they are usually performed after convolution.

lenet.initialize(mx.init.Xavier(), ctx=ctx)
lenet.summary(nd.zeros((1, 1, 28, 28), ctx=ctx))

the summary() method can be a great help, it requires the network parameters to be initialized, and an input array to infer the sizes.

output:- 
--------------------------------------------------------------------------------
        Layer (type)                                Output Shape         Param #
================================================================================
               Input                              (1, 1, 28, 28)               0
        Activation-1                <Symbol eNet_conv0_tanh_fwd>               0
        Activation-2                             (1, 20, 24, 24)               0
            Conv2D-3                             (1, 20, 24, 24)             520
         MaxPool2D-4                             (1, 20, 12, 12)               0
        Activation-5                <Symbol eNet_conv1_tanh_fwd>               0
        Activation-6                               (1, 50, 8, 8)               0
            Conv2D-7                               (1, 50, 8, 8)           25050
         MaxPool2D-8                               (1, 50, 4, 4)               0
           Flatten-9                                    (1, 800)               0
       Activation-10               <Symbol eNet_dense0_tanh_fwd>               0
       Activation-11                                    (1, 500)               0
            Dense-12                                    (1, 500)          400500
            Dense-13                                     (1, 10)            5010
================================================================================
Parameters in forward computation graph, duplicate included
   Total params: 431080
   Trainable params: 431080
   Non-trainable params: 0
Shared params in forward computation graph: 0
Unique parameters in model: 431080

First conv + pooling layer in LeNet.

Now we train LeNet with similar hyperparameters as learning rate 0.04, etc. Note that it is advisable to use a GPU if possible since this model is significantly more computationally demanding to evaluate and train.

trainer = gluon.Trainer(
    params=lenet.collect_params(),
    optimizer='sgd',
    optimizer_params={'learning_rate': 0.04},
)
metric = mx.metric.Accuracy()
num_epochs = 10
for epoch in range(num_epochs):
    for inputs, labels in train_loader:
        inputs = inputs.as_in_context(ctx)
        labels = labels.as_in_context(ctx)
        with autograd.record():
            outputs = lenet(inputs)
            loss = loss_function(outputs, labels)
        loss.backward()
        metric.update(labels, outputs)
        trainer.step(batch_size=inputs.shape[0])
    name, acc = metric.get()
    print('After epoch {}: {} = {}'.format(epoch + 1, name, acc))
    metric.reset()
for inputs, labels in val_loader:
    inputs = inputs.as_in_context(ctx)
    labels = labels.as_in_context(ctx)
    metric.update(labels, lenet(inputs))
print('Validaton: {} = {}'.format(*metric.get()))
assert metric.get()[1] > 0.985

Let us visualize the network accuracy. Some wrong predictions on the training and validation set.

def get_mislabeled(loader):
    """Return list of ``(input, pred_lbl, true_lbl)`` for mislabeled samples."""
    mislabeled = []
    for inputs, labels in loader:
        inputs = inputs.as_in_context(ctx)
        labels = labels.as_in_context(ctx)
        outputs = lenet(inputs)
        # Predicted label is the index is where the output is maximal
        preds = nd.argmax(outputs, axis=1)
        for i, p, l in zip(inputs, preds, labels):
            p, l = int(p.asscalar()), int(l.asscalar())
            if p != l:
                mislabeled.append((i.asnumpy(), p, l))
    return mislabeled
import numpy as np
sample_size = 8
wrong_train = get_mislabeled(train_loader)
wrong_val = get_mislabeled(val_loader)
wrong_train_sample = [wrong_train[i] for i in np.random.randint(0, len(wrong_train), size=sample_size)]
wrong_val_sample = [wrong_val[i] for i in np.random.randint(0, len(wrong_val), size=sample_size)]
import matplotlib.pyplot as plt
fig, axs = plt.subplots(ncols=sample_size)
for ax, (img, pred, lbl) in zip(axs, wrong_train_sample):
    fig.set_size_inches(18, 4)
    fig.suptitle("Sample of wrong predictions in the training set", fontsize=20)
    ax.imshow(img[0], cmap="gray")
    ax.set_title("Predicted: {}\nActual: {}".format(pred, lbl))
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
fig, axs = plt.subplots(ncols=sample_size)
for ax, (img, pred, lbl) in zip(axs, wrong_val_sample):
    fig.set_size_inches(18, 4)
    fig.suptitle("Sample of wrong predictions in the validation set", fontsize=20)
    ax.imshow(img[0], cmap="gray")
    ax.set_title("Predicted: {}\nActual: {}".format(pred, lbl))
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)

Leave a Reply