Zero Labs
Industry News / AI

Comparative Analysis of Artificial Neural Networks for Image Classification on CIFAR-10

Source · Towards AI By Abdul Wadood

From the publisher’s feed, collected in the ZeroLabs newsroom.

Abstract:This paper presents a comparative study of multiple artificial neural network architectures for multi-class image classification using the CIFAR-10 dataset. A baseline Multi-Layer Perceptron (MLP), standard Convolutional Neural Networks (CNNs), a custom deep CNN with batch normalisation and dropout, ResNet-50, and a custom ResNet variant were implemented and evaluated. Models were benchmarked using accuracy, precision, recall, F1-score, confusion matrices, and ROC-AUC curves. Results demonstrate that deeper, well-tuned CNN architectures significantly outperform the baseline MLP, achieving up to 81% test accuracy, while the ResNet-based models highlight the challenges of applying transfer learning on small image sizes without architectural adjustments. This comparative analysis provides practical insights for students and practitioners designing deep learning pipelines for image classification tasks.Source code: https://github.com/abdulwadoodmotla/Benchmarking_CIFAR10Section 1. IntroductionIn the ever-evolving field of machine learning, image classification emerges as a key area to focus on. The CIFAR-10 dataset serves as a benchmark to assess the performance artificial neural networks in recognising and categorising theses images. This report delves into the analysis of different artificial neural network architectures which includes MLP used as the foundational model due to its simplicity and limitations in capturing spatial relationships. The sophisticated CNNs which has revolutionised the image recognition were explored in this report too. The investigation was further extended to the use of ResNet architecture which is well known to solve the vanishing gradient problem by using the innovative skip connections.The cutting-edge techniques implemented in this report include the use of batch normalisation, dropout regularisation, a suite of metrics to perform comparative analysis. The models’ performance was analysed using validation accuracy, precision, recall, f1 scores and Receiver Operating Characteristic — Area Under the Curve.Through this comprehensive report, insights from the use of different architectures in image classification have been uncovered and recommendations have been made to further refine the field.Section 2. Related workThe research (Aslam & Ali Bou Nassif, 2023) worked on CIFAR-10 dataset to develop image classification models using the a custom Convolutional Neural Network (CNN), VGG-16 and 19, K-Nearest Neighbours (K-NN) and Random Forest Classifier. The architectures of the models were compared in the paper with changing filter sizes and their performance was compared using the metrics — precision, recall and F1-score. The best models were custom CNN which achieved 88% accuracy. As compared to the research paper, this report explores more complex architectures.(Doon et al., 2018) tackles the task of classifying CIFAR-10 images too. It focuses on using Deep CNNs with 6 convolutional layers, 3 pooling layers and 3 fully connected layers. Adam and RMSprop optimisation techniques were used, and the best accuracy achieved was 87.8% on test data. In 8888IE report and this report, both focus on the use of optimisation and regularisation techniques but this report provides an exhaustive discussion of a range of models used from a simple MLP to a custom ResNet used as compared only one Deep CNN model used in the (Doon et al., 2018) research.Similarly, the research by (Handral et al., 2022) have worked on multi-class image classification using CIFAR-10 dataset mainly using CNN and ResNet but also worked on simple 2 layer ANN, SoftMax classifier and nearest neighbour classifier. It experiments with a 56-layer deep ResNet model and achieves a high accuracy of 99%. The model was also cross-validated and achieved a validation score of 93.6%. (Handral et al., 2022) mainly focuses on the model performance under memory constraints. As compared to (Handral et al., 2022), this report focuses on a broader aspect of neural network models with various architectures and analyse their relative performance.Section 3. The datasetThe dataset chosen for this image classification task is CIFAR-10 (Canadian Institute for Advanced Research) (Keras, n.d.). The dataset contains 60,000 colour images with 10 different classes. The classes present are: airplanes, birds, cars, cats, deer, frogs, dogs, trucks, ships, and horses.Figure 1: DatasetEach class contains 6000 images. The dataset was divided into training and test files, 50,000 images were used for training purpose and 10,000 images were used to test the model performance.To have an insight of potential biases in colouration of the images, the following graph shows the colour distribution. It can be noticed that red and green are slightly higher than blue.Figure 2: Colour distributionThe histograms in the below figure show the pixel intensity against the pixel count. It shows the overall diverse content in the images.Figure 3: Pixel distribution histograms3.1. Pre-processing the dataThe data was pre-processed using the following techniques to prepare it to train the models.The dataset was pre-segmented and each image had the size 32x32. This ensures fair comparison of model performances because of uniform image size when different algorithms are trained. Secondly, smaller images of 32x32 allowed more computational efficiency so it would not require high-end GPUs to train the models.Image flattening was performed on the dataset to be used for the Multi-Layer Perceptron (MLP) model as MLP accepts input in 1D. As a result, the 2D images were converted to 1D. Flattening the image for MLP allowed the model to process the data and train on it.Figure 4: Image flatteningAs the dataset contains 10 different categorical attributes, the need to be converted to integers to make it interpretable for the models. One hot encoding was done to convert the categorical class labels to binary matrix. This would prevent the model to assume any natural order in the order of classes.Figure 5: Labels before encodingFigure 6: Labels after one-hot encodingIn such digital images, the pixel intensity for each primary colour is represented by a 8-bit integer. This allows to get 255 different colour intensities. For the consistency and uniformity in the input data these pixel values were normalised to a range of 0–1 instead of using the 0–255 range. This was achieved by converting the pixel values to float and then dividing by 255.Figure 7: Without normalisationFigure 8:Images after normalisationSection 4. MethodsTo perform the multi-class image classification task, the following architectures were used. All the models included:Activation functions:· ReLu (Rectified Linear Unit): This is used to introduce non-linearity which thus helps the network to learn complex patterns (Brownlee, 2019).· Softmax activation function is used in output layers which converts the final layer’s output results into probabilities, these probabilities correspond to the likelihood of the input image belonging to one of the 10 classes in the CIFAR-10 dataset.Optimisation and loss:· Adam optimizer: The optimizer is responsible to update the weights according to the gradient of the loss function.· Categorical cross-entropy: It was used as the loss function for training models.K-fold cross-validation:K-fold validation was applied to train all the models by splitting it into 5 folds.All the models were trained for upto 10 epochs using the same pre-processed data and the results were analysed.The next section explains the architectures used for this task.4.1 Multi-Layer Perceptron (MLP)In this task of image classification, it is crucial to establish a baseline benchmark. The Multi Layer Perceptron (MLP) being a simple and easy to implement algorithm served as an ideal baseline model. Though having some limitations, for example, capturing spatial hierarchies in the images MLP provides a simple approach to the fundamentals of Neural Networks.4.1.1 How MLP worksA typical multi-layer perceptron consists of an input layer, single or multiple hidden layers and an output layer. Each layer consists of nodes, also known as neurons, fully connected to the subsequent layer (Abirami & Chitra, 2020). The input layer is responsible to receive the input data and the hidden layers compute the weighted sum of the inputs, applies a bias and then the result is passed to a non-linear activation function e.g ReLu (Rectified Linear Unit).Finally, the in the output layer, SoftMax activation function is used.Figure 9:MLP architectureFigure 9:MLP architecture(Abirami & Chitra, 2020)4.1.2 MLP application in CIFAR-10 datasetTo use the MLP in the CIFAR-10 dataset, the input data needs to be flattened. This is necessary as the input layer receives 1Dimensional vectors and not 2Dimensional image data.The MLP model was defined using ‘Sequential’ API. 512 neurons were chosen in the first dense layer and 256 for the second one because of the complexity of dataset, it was necessary to have enough parameters to detect the complex patterns and relationships in the image data. ReLu activation was used for this layer.The output layer consisted of 10 neurons and the SoftMax activation function. The class having the highest probability is then taken as the model’s prediction.The model was compiled using Adam Optimizer, categorical cross-entropy and the accuracy metric was added to evaluate the model performance.Finally, the model’s performance was evaluated by checking how good is the model in generalisation (its performance on unseen data).Figure 10: MLP summary of implemented architecture4.2 Convolutional Neural Networks (CNN)4.2.1 How CNNs workDue to the ability to capture spatial hierarchies in image data, CNNs have emerged as cornerstone in the image recognition tasks. CNNs can view the 2Dimensional grid of pixels which made it an ideal choice for this image classification task. The CNNs mainly consist of convolutional layers, pooling layers and dense layers.The convolutional layers use “filters” to perform the convolutional operation on the input image. It captures the spatial features on the image including the texture, edges, and the patterns.Followed by the convolutional layers are the pooling layers which mainly perform the down sampling operations reducing the dimensionality of the feature maps. The dimensionality reduction helps reduce the parameters and hence the computation so that overfitting could be controlled, and model can focus more on the prominent features (Chen et al., 2021).The fully connected dense layers are used to classify the images into one of the 10 classes of the CIFAR-10 dataset.The final layer uses SoftMax function to produce a probability distribution for the classes.Figure 11: CNN(Mathworks, n.d.)4.2.1 CNN application in CIFAR-10 datasetTo demonstrate the efficiency of the CNNs, two CNN models were developed using the CIFAR-10 dataset. A simple CNN model and a more complex and hyper tuned CNN model was developed which included additional layers, batch normalisation and dropout layers. This was done to explore the benefits of a more complex and deeper architecture.Simple CNN architectureThe simple CNN architecture consisted of 122,570 parameters. It had 3 convolutional layers and includes pooling layers and a dense layer.Figure 12: Simple CNN architectureCustom CNN architectureThe advanced custom architecture included dropout layers for better regularisation, batch normalisation was added to get better training stability. It had eight convolutional layers with increasing filters.Figure 13: Custom CNN architecture4.3 ResNet-50 and Custom ResNetTo illustrate the advancements in the deep learning architecture design ResNet 50 and a custom ResNet were used.The vanishing gradient problem is one of the critical challenges in training deep neural networks because the gradients increasingly become smaller as they backpropagate. ResNets can use skip connections to address this issue and allow the gradient flow more freely in the network.ResNet-50 was used so that through transfer learning, the knowledge gained by the pre-trained model on ImageNet can help boost the performance on a relatively smaller dataset CIFAR-10.In addition to ResNet-50, a custom ResNet model was built so that the architecture can be tailored for the dataset. This helped to analyse how different configurations affect the performance on such image classification task.4.3.1 How ResNet worksResNet uses the residual learning technique to ease the training of the networks. Unlike the traditional models, ResNet uses ‘shortcut connections’ which skip few layers. In traditional networks, each layer needs to learn the underlying mapping directly.In other words, let H(x) be the underlying mapping that needs to be learnt by the multiple layers. A layer in ResNet will learn the difference between the input x and H(x) which can be denoted asF(x)=H(x)−xThis mitigates the vanishing gradient problem during backpropagation and eases the optimization (geeksforgeeks, 2020).The main part of its architecture are the series of ResNet blocks. They are designed to learn from the difference between input and the desired output of the block. Each ResNet block consists of two convolutional layers with batch normalisation and ReLU activation. To form the shortcut connection, the output of second convolutional layer is added to the block’s input and the passed through the activation function. To ensure that the shortcut connection can be added to the main path, 1x1 convolution was used in the shortcut path for matching dimensions.Then, global average pooling follows the ResNet blocks to reduce the number of parameters and the computational complexity, hence making the model more efficient.Finally, it uses an output dense layer to output the probability distribution over the classes using the SoftMax activation.Figure 14: How ResNet works(geeksforgeeks, 2020)4.3.2 Application of ResNet in CIFAR-10The ResNet architectures were developed initially for the ImageNet classification tasks where much larger images are involved as compared to the small 32x32 images in CIFAR-10. As the ImageNet data has different classes and to adapt the model to CIFAR-10 the top layer of ResNet-50 was removed so a new layer classifier layer for CIFAR-10 can be added. The weights were frozen so that transfer learning can be leveraged to improve performance. Global average pooling was used to reduce the spatial dimensions from the output of the final convolutional block. Lastly, a new dense layer was added with 10 neurons, along with softmax activation so the images from CIFAR-10 can be classified to one of the classes.Finally, the model is compiled using Adam optimiser and categorical-class entropy. Then, the model was trained using the dataset.Figure 15: ResNet-50 architectureThe custom ResNet was designed using the Functional API unlike the Sequential API in ResNet-50, this allowed more flexibility to build the model. Explicit input and output layers were defined for a better flow of model’s data. The learning rate of adam was set to 0.001 for better performance.Figure 16: Custom ResNet architecture (see GitHub repository)4.4 Performance metricsTo perform comparative analysis on the performance of all the models, the key performance metrics considered are as follows:Cross-validation scoreThis was achieved by setting n-fold = 5. This is essential to test how well the model is in generalising so it can be used in real world unseen data. This gave an insight if the model was overfitting or underfitting.Training/Validation accuracy and lossTwo separate graphs for the model loss and accuracy during the training process were drawn. For all models, the left graph showed the model accuracy against each epoch and the right graph showed the loss. The training set line shows how well the model fits on the data it learns from while the validation set line shows how the model generalises on the new unseen data it is tested. In accuracy graph, if both the training and validation lines increase together, it indicates that the model learns effectively. If training line grows higher than validation, it indicates that the model is overfitting as it is not that good in generalising.Loss is the function to measure the error in the model’s predictions. In loss graph, the decreasing line indicates that the model’s predictions get closer to the true values. An overfitting model is indicated when the validation line stops decreasing as compared to the training line (Cristina, 2022).AccuracyTo provide a reliable measure of model’s overall performance on the task, ‘accuracy’ was used. It measures the proportion of correctly predicted results to the total results.Precision and recallPrecision is the proportion of correctly predicted positive results to the total positive results. On the other hand, recall measures the proportion of correctly predicted positive observations to the total observations in the actual class. These metrics are helpful in identifying the model’s performance in terms of false positives and false negatives (Huilgol, 2020).F1 scoreIt is the harmonic mean of precision and recall, it provides a balance between the important metrics, precision and recall. It is a significant metric as it takes both the false positives and false negatives into account.Confusion matrixIt provides a detailed breakdown of the predictions made across all classes by showing their true positives, true negatives, false positives and false negatives. This metric was used as it provides an insight of where the model may be confusing the classes.The diagonal values present the correctly classified result of each class, while the off-diagonal values are the wrongly classified results (Huilgol, 2020).The colour intensity of the heatmap show the magnitude of values.Receiver Operating Characteristic (ROC) Curve and Area Under the Curve (AUC)To get a graphical representation of model’s performance, ROC-AUC metric was used. The ROC curve is plotted for the true positive rate against the false positive rate. AUC is the measure of the are under ROC curve. The values for the area are out of 1 and the closer it is to 1 means the model is better in performing classification for that class.Section 5. Experimental ResultsThe test data consisting of 10,000 images was used for evaluation after training the models for 10 epochs. Implementation details and full source code are available on GitHub.5.1 MLPThe baseline MLP model gave an accuracy of 46.8% which mean only around 50% of the results on average were correctly predicted by the classifier.The evaluation was performed on 313 batches.Validation accuracy and loss scoreAverage Validation Loss: 1.69Average Validation Accuracy: 39.64%Training/Validation accuracy and loss graphsThe graphs show significant gap between training and validation of the model.Figure 17: Accuracy/Loss graph for MLPConfusion Matrix:The ‘automobile’ images got the most accuracy of 609 out of 1000 images being correctly identified.The ‘bird’ class got the least accuracy of only 241 out of 1000 (24%) images being classified correctly while 210 images of ‘bird’ were wrongly predicted as ‘deer’.Figure 18: Confusion Matrix for MLPClassification ReportFrom precision column, it can be noticed that the most accurate positive predictions were for ‘automobile’ 52% of the timeThe recall score shows the ability of the model to find the relevant cases for each class, for example, ‘automobile’ had a class had a recall of 61%, which means that the model identified the actual ‘automobile’ images 64% of the time.The overall test accuracy of the model was 0.45, giving an overview of model’s performance.Figure 19: Performance metrics for MLPROC-AUCThe following image shows the ROC — AUC. The steepness of the curves towards the y-axis (True positive rate) show that the model achieved relatively good true positive rate as compared to the false positive rate. The average AUC achieved is 0.856.Figure 20: ROC-AUC for MLP5.2 Simple CNNValidation accuracy and loss scoreAverage Validation Loss: 1.04Average Validation Accuracy: 63.57%Training/Validation accuracy and loss graphsThe diagram below shows the accuracy and loss graphs on validation and train sets. The validation line stops growing as compared to the training line, indicate possibility of overfitting.Figure 21: Accuracy/Loss for CNNConfusion matrixThe confusion matrix for the simple CNN model shows that the highest number of correctly identified images were of ‘ship which were 879/1000 and the least number of accurately identified images were of ‘cat’ which were 517/1000 and it was confused mostly with ‘dog’ with 174/1000 ‘cat’ images wrongly classified as ‘dog’.Figure 22: Confusion matrix for CNNClassification reportAccording to the following classification report, ‘automobile had the highest ‘precision’ while ‘cat’ having the least.The model got an overall test accuracy of 70%.Figure 23: Performance metrics for CNNROC-AUCThe ROC curve shows high steepness towards the true positive rate and the Area Under the Curve the averace AUC was 95.4% while the highest was 0.98 for ‘automobile’ and the lowest of ‘0.90’ for ‘cat’.Figure 24: ROC-AUC for CNN5.3 Custom CNNValidation accuracy and loss scoreAverage Validation Loss: 0.83Average Validation Accuracy: 72.19%Training/Validation accuracy and loss graphsThe graphs below show less gap between the validation and training lines as compared to simple CNN model.Figure 25: Accuracy/Loss for Custom CNNConfusion matrixThe custom CNN had a similar confusion matrix result as the simple CNN, showing the ‘frog’ class as the most accurately identified images and ‘cat’ and ‘bird’ as the least accurately.Figure 26: Confusion matrix for custom CNNPerformance metricsThe performance matrix below shows a test accuracy of 81%. The highest precision was for the ‘ship’ and ‘horse’ class being 91%. The recall was highest for ‘frog’ being 94%.Figure 27: Performance metrics for custom CNNROC-AUCThe ROC curve was the steeper than the simple CNN and the best AUC was for ‘frog’, ‘horse’, ‘ship’, ‘airplane’ and ‘truck’ being 0.99. The average AUC was 98.1%.Figure 28: ROC-AUC for custom CNN5.4 ResNet-50Validation accuracy and loss scoreAverage Validation Loss: 5.44Average Validation Accuracy: 49.33%Training/Validation accuracy and loss graphsThe below diagram shows that the ResNet-50 model did not perform well, as the validation line is very volatile. The fluctuations show that the model is inconsistent in generalisation.Figure 29: Accuracy/Loss for ResNet-50Confusion matrixThe confusion matrix for ResNet-50 shows the best accuracy for accurately predicting for the class ‘frog of 908/1000 and the least for ‘dog of 430/1000. Most of the ‘dog’ images were confused by the model with the ‘cat’ class.Figure 30: Confusion Metrics for ResNet-50Performance metricsAfter observing the performance matrix for the ResNet-50 model, it can be noticed that the model achieved an overall F1-score of 0.70. The best precision was for the ‘ship’ and least for ‘cat’ .Figure 31: Performance metrics for ResNet-50ROC-AUCThe ROC curves show good steepness towards the True positive rate axis. The ‘automobile’ class got the highest AUC score as the model was better able to distinguish for this class. The average AUC was 0.956.Figure 32: ROC-AUC for ResNet-505.5 Custom ResNetValidation accuracy and loss scoreLoss: 1.00Accuracy: 66.59%Training/Validation accuracy and loss graphsThe graphs below show notable fluctuations for validation and the gap between validation and train graphs is high. This indicates poor fitness of the model on data.Figure 33: Accuracy/Loss for custom ResNetConfusion matrixThe confusion matrix for the custom ResNet model shows the highest accurate results predicted 895/1000 for the ‘ship class and the least accurate were 312/1000 for the ‘cat as it many of its images were confused by the model for ‘deer’ and ‘dog’ classes.Figure 34: Confusion matrix for custom ResNetPerformance metricsAs shown in the performance matrix below, the module had an overall accuracy of 65%. The highest precision was recorded for ‘truck’ class of 90.0% .Figure 35: Performance metrics for custom ResNetROC-AUCThe ROC-AUC curve below shows that the average AUC score was 0.95 with ‘automobile’ class having the highest.Figure 36: ROC-AUC for custom ResNetConsolidated results:Figure 37: Consolidated resultsSection 6. Discussion and future workThe results in the previous section show that MLP achieved the lowest validation accuracy of 39.64% as it had significant gap between training and validation. This poor performance was expected as MLPs are not well-suited for capturing the spatial hierarchies from images.Simple CNN achieved a validation accuracy of 63.57%, while the custom CNN model achieved 72.19%. This shows that a deeper CNN with better tuning using batch normalisation and regularising techniques help the model capture complex features of the images.The Resnet-50 had an accuracy of 49.33%. It had high validation loss making it inconsistent in generalisation. The reason behind poor performance was that it is pre-trained on ImageNet dataset which has larger images as compared to CIFAR-10 and without adaption to this dataset, it could not perform better.The custom ResNet achieved validation accuracy of 66.6% but the fluctuations in the validation accuracy graph indicate overfitting. The architecture was although customised for CIFAR-10 but it was too complex to be trained on this dataset and required further hyper tuning to achieve better results.Among all the evaluated models, Custom CNN achieved the highest accuracy and handled overfitting in much better way as its architecture was tuned according to the CIFAR-10 dataset and tailored feature maps were used.A hybrid model could be created according to the study (Lu et al., 2022) using convolutional layers and the attention layers of Visual transformers to train on this dataset. By implementing this hybrid architecture the spatial organisation of the images can be better learnt by the model, hence improving its performance.ReferencesAbirami, S., & Chitra, P. (2020). Multilayer Perceptron — an overview | ScienceDirect Topics. Www.sciencedirect.com. https://www.sciencedirect.com/topics/computer-science/multilayer-perceptronAslam, S., & Ali Bou Nassif. (2023). Deep learning based CIFAR-10 classification. Deep Learning Based CIFAR-10 Classification. https://doi.org/10.1109/aset56582.2023.10180767Brownlee, J. (2019, April 20). A Gentle Introduction to the Rectified Linear Unit (ReLU) for Deep Learning Neural Networks. Machine Learning Mastery. https://machinelearningmastery.com/rectified-linear-activation-function-for-deep-learning-neural-networks/Chen, L., Li, S., Bai, Q., Yang, J., Jiang, S., & Miao, Y. (2021). Review of Image Classification Algorithms Based on Convolutional Neural Networks. Remote Sensing, 13(22), 4712. https://doi.org/10.3390/rs13224712Cristina, S. (2022, October 18). Plotting the Training and Validation Loss Curves for the Transformer Model — MachineLearningMastery.com. MachineLearningMastery.com. https://machinelearningmastery.com/plotting-the-training-and-validation-loss-curves-for-the-transformer-model/Doon, R., Kumar Rawat, T., & Gautam, S. (2018, November 1). Cifar-10 Classification using Deep Convolutional Neural Network. IEEE Xplore. https://doi.org/10.1109/PUNECON.2018.8745428geeksforgeeks. (2020, June 3). Residual Networks (ResNet) — Deep Learning. GeeksforGeeks. https://www.geeksforgeeks.org/residual-networks-resnet-deep-learning/Handral, P., Kulkarni, R., MD, S., & Kumar, N. (2022, May 4). CIFAR-10 Image Classification with Convolutional Neural Networks. Ijarsct. https://ijarsct.co.in/Paper3887.pdfHuilgol, P. (2020, September 3). Precision vs Recall | Precision and Recall Machine Learning. Analytics Vidhya. https://www.analyticsvidhya.com/blog/2020/09/precision-recall-machine-learning/Lu, Z., Xie, H., Liu, C., & Zhang, Y. (2022). Bridging the Gap Between Vision Transformers and Convolutional Neural Networks on Small Datasets. https://arxiv.org/pdf/2210.05958.pdfMathworks. (n.d.). What Is a Convolutional Neural Network? | 3 things you need to know. Www.mathworks.com. https://www.mathworks.com/discovery/convolutional-neural-network.html#:~:text=Tutorials%20and%20examples-Team, K. (n.d.). Keras documentation: CIFAR10 small images classification dataset. Keras.io. https://keras.io/api/datasets/cifar10/Comparative Analysis of Artificial Neural Networks for Image Classification on CIFAR-10 was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.