Classification / Neural Network
Convolutional Neural Network, CNN
2023-12-26
CNN as the artificial neural network for image classification has many advantages. As previously shown in other blogs, ANN itself produces good results. However, as you might need a higher resolution image to distinguish between a dog and a cat, object detection can be done efficiently by extracting features from the image at lower resolution rather than completely utilizing all the pixels. In this way, we can save a significant amount of computation time and memory cost.
Algorithm perspective, in ANN we calculate the coefficients as many as the number corresponding to the number of pixels in the input layer times the nodes in the hidden layer, however, CNN need far less number of unknowns to find so-called filters in the convolutional layer, which can be further reduced by the pooling operation. But the structure of the output layer becomes larger due to the filters. Therefore, as the number of pixels increases and the number of nodes in the output layer decreases, the efficiency of CNN becomes greater compared to ANN.
CNN introduces convolutional layers and pooling layers instead of the existing fully connected layers, which are used repeatedly as shown in the figure below. The example below explains the case of training MNIST handwritten digits of 28x28 size. After using 32 kernels of size 5x5, followed by pooling kernels of size 2x2 with a stride of 2, it outputs 32 convolutional layers of size 12x12, and then, in the second convolutional layer, 64 kernels of size 5x5 are used with 2x2 pooling, producing a final output of 64 layers of size 4x4. This is then transformed into a one-dimensional size of 4x4x64=1024 and finally connected to 10 output nodes with full connectivity.

We will review the convolutional operation and Pooling operation in next.
(1) Convolutional operation
The following example shows the process of performing a convolution operation using a 2x2 kernel on a 4x4 input image. The stride used here is of size 1, meaning the 4x4 image reduces to a 3x3 image in the end. The convolution operation is defined as the sum of element-wise products, similar to the SUMPRODUCT function in Excel. The user only defines the size of the kernel, and the content of the kernel is automatically determined through CNN operations based on the given dataset. Thus, the given convolution kernel functions to extract certain features, effectively serving as a filter. Following demonstrates how the kernel extracts features for two different diagonals. For the yellow filter which only highlights the backslash pattern of the image, so that Case A where it is applied to the same patter, it reports a high value but Case B does not.

(2) Pooling operation
The purpose of pooling operation is to further compress the data. In the example below, through a pooling operation with a 2x2 kernel size and a stride of 2, a 4x4 image is reduced to 2x2. There are two types of pooling: average pooling, which takes the average value of the target, and max pooling, which takes the maximum value among them. Max pooling is commonly taken for an effectiveness.

(3) Estimate the size of output image after each operation
Because we use cells in Worksheet, it is crucial to pre-calculate the size of the resulting coefficients before any calculations for CNN involving convolution, or transposed convolution, or pooling operations, which result in changes to the size of the image.
(3.1) Convolution
The output size varies depending on the size of the kernel, padding, and stride. It is defined by the following formula.
Output_size = (Input_size + 2*Padding_size - Kernel_size) / Stride_size + 1
For example, using the blue image below as an input size of [5x5], with padding=2, kernel size=[3x3], and stride=1, the output image size becomes (5+2*2-3)/1+1 = 7 for both rows and columns.

(3.2) Transposed convolution
The size of the output image is expanded in the opposite way as follows.
Output_size = (Input_size - 1) x Stride_size + Kernel_size
In the example below, with input size = [2x3], kernel size = [3x3], and stride = 2, the final output will be the one with the size for rows, (2-1)*2+3 = 5 and for columns, (3-1)*2+3 =7.

(3.3) Pooling operation
Output_size = (Input_size - Kernel_size) / Stride_size + 1
For example, if the size of the input image, [6x6], kernel size = [2x2], and stride = 2, the output size becomes [3x3]
The dataset for implementing CNN in Excel performed classification for three cases of 0, 1, and 2 using the handwritten digit recognition of a 7x7 size demonstrated in ANN.
The structure is as follows, using the Sigmoid activation function for the convolutional layer and the Softmax for the output layer.

(1) Sample preparation
The process of converting data that has been organized in a CSV format into 2-dimensional image data can be achieved using Excel's INDEX and Array functions. We only deal with the 0,1, & 2 dataset only. The total data is the size of 3147x50 which can be found at the "7x7" Worksheet. Column A is the label and rest of 49 data is the flattened 7x7 image data, For each of the 7 rows per the image, the respective functions are as follows.
For the first row,
=INDEX(Dataset, row number, {1,2,3,4,5,6,7}),
and for the last row,
=INDEX(Dataset, row number, {43,44,45,46,47,48,49})
Below is one example, and the result is color-coded through the Excel's conditional formatting.

(2) Cells place holding for the coefficients
(2.1) Convolution Layer
For this demo, we used a convolutional layer with a [7x7] input layer size, a kernel size of [4x4] using 3 kernels, with padding size=1 and stride size=1. The output size is determined according to the above formula.
Output_size = (Input_size + 2*Padding_size - Kernel_size) / Stride_size + 1 = ([7x7]+2*1-4)/1 + 1 = [6x6].
The total number of required coefficients is 51, as there is one threshold for each [4x4] filter per kernel, resulting in a total of 4x4x3+3 = 51 coefficients needed.
Below are shown three kernels of size [4x4] and their corresponding three [6x6] outputs.

(2.2) Pooling layer
Pooling layer uses the Kernel size of [2x2] and stride=2. The output size for the [6x6] output of the convolution layer as the input becomes
Output_size = (Input_size - Kernel_size) / Stride_size + 1 = ([6x6]-2)/2+1 = [3x3].
Picture below shows the output of the pooling layer derived from the equation above. We use the max pooling.

(2.3) Output layer
The operation of the output layer requires the output of the entire pooling layer to be flattened into a single sequence in a similar way 2D image converted into one single input layer for ANN before.
In this example, the result of the Pooling layer consists of 27 nodes, obtained from 3 kernels of size 3x3. These nodes are then fully connected to the nodes of the output layer. Since there are 3 nodes (0, 1, 2) in the output layer, a total of 28 coefficients are needed for each node, i.e., a 27-dimensional weight vector and one threshold for decision-making. Therefore, a total of 3x28 = 84 coefficients are required.

(3) Computation
(3.1) Convolution layer
The calculation is performed as the inner product of vectors followed by the output of the activation function, using padding of size 1 along the edges.

(3.2) Pooling layer
The operation of the pooling layer is performed with respect to the output of the convolutional layer by taking the maximum value (MAX) in the corresponding area of the color.

(3.3) Output layer
Output layer computation is done by Softmax.
\(P(z_i)=\phi (z_i)=\dfrac{\exp (z_i)}{\sum _j^{\ }\exp (z_j)}\)
First, for each output class, perform the inner product between the output of the pooling layer and the coefficients of each class,
zi = sumproduct( Output of the pooling layer, the coefficients of class i) - bias of class i
Then, calculate exp(zi) for the Softmax function.

Finally, compute probability using Softmax after calculation of all exp(zi)

To calculate the cost for optimization, Cross Entropy is used. For nodes corresponding to actual observations, it is log(P), and for the nodes that do not, it is log(1-P). The coefficients that maximize the total sum of this as the objective function are derived.
\(\text{Cost}=\sum _{\ }^{\ }y\log (P)+(1-y)\log (1-P)\)
(4) Run the Solver
Find the coefficients of the kernels and the output layer by optimizing the cost. Run the Solver with the following settings.

Following Confusion matrix shows the results of the model predicted for 2100 sample size.
| Prediction | ||||
| 0 | 1 | 2 | ||
| Measurement | 0 | 622 | 0 | 14 |
| 1 | 0 | 746 | 17 | |
| 2 | 17 | 19 | 665 |
From the Confusion matrix, we can calculate the accuracy and precision.
- Accuracy = (TP + TN) / (TP+TN+FP+FN) = 96.8%
- Precision) = TP / (TP + FP) = 96.80%
- Recall = TP / P = 96.81%
- F1 Score = 2 * PRE*REC/(PRE+REC) = 96.8%
If implemented as an ANN for the same case, the necessary parameters for calculation and comparison of results were presented in a table.
