<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ershveer Singh Saini on Medium]]></title>
        <description><![CDATA[Stories by Ershveer Singh Saini on Medium]]></description>
        <link>https://medium.com/@ershveers?source=rss-170ac36bb9f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*w4wZ5FEL0sUMTBhmOjodTA.jpeg</url>
            <title>Stories by Ershveer Singh Saini on Medium</title>
            <link>https://medium.com/@ershveers?source=rss-170ac36bb9f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:10:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ershveers/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[3D brain tumour segmentation and visualisation for improved clinical understanding]]></title>
            <link>https://medium.com/@ershveers/3d-brain-tumour-segmentation-and-visualisation-for-improved-clinical-understanding-98ad5168f015?source=rss-170ac36bb9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/98ad5168f015</guid>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Ershveer Singh Saini]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 12:42:21 GMT</pubDate>
            <atom:updated>2025-09-02T16:16:59.430Z</atom:updated>
            <content:encoded><![CDATA[<p>Deep learning segmentation models for brain tumors have achieved remarkable accuracy, yet their ‘black-box’ nature poses a challenge for clinical use. Clinicians require not only accurate predictions, but also understandable explanations of how and why a model reached its conclusions, especially in high-stakes settings like neuro-oncology. Visualisation tools such as heatmaps and uncertainty overlays serve as interpretable bridges between complex model behaviors and human intuition. By making predictions, model attention, and confidence transparent, these visualisations foster clinicians’ trust, support diagnostic reasoning, and facilitate actionable insights. Therefore, the focus of this work is not solely segmentation, but rather how to interpret and communicate model outputs effectively to clinicians through visualisation. Visual representations such as saliency heatmaps and uncertainty overlays make AI decisions more interpretable and actionable for clinicians. Attribution-based tools like Grad-CAM, integrated gradients, and maps highlight image regions influencing model outputs, enhancing localisation and interpretability. Meanwhile, visualising uncertainty through methods like Monte Carlo Dropout helps clinicians understand the model’s confidence, prioritize review of ambiguous areas, and avoid overconfidence in automated outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*SzX_p6g_76RSfVSqK9qGRg.png" /><figcaption>Project Overview</figcaption></figure><h3><strong>BraTS Dataset</strong></h3><p>The Brain Tumor Segmentation (BraTS) challenge, held annually at the MICCAI (Medical Image Computing and Computer Assisted Intervention) conference since 2012, provides a benchmarking platform for developing and evaluating automated brain tumor segmentation methods using state-of-the-art deep learning.</p><p>The BraTS 2021 dataset consists of multimodal 3D MRI scans from glioma patients, collected across multiple institutions under varying imaging protocols, ensuring realistic heterogeneity. Each case includes four MRI sequences- T1, T1-contrast (T1ce), T2, and FLAIR, along with the expert-annotated ground truth labels for tumor subregions (necrosis, edema, and enhancing tumor). Data are provided in NIfTI format as volumetric grids of voxels, a voxel is the 3D equivalent of a pixel, representing a small cube of tissue in volumetric imaging, unlike a 2D photograph, which has height and width, this data also has depth, allowing for a full, three-dimensional representation of the brain and tumor making the dataset a standard benchmark for developing and comparing brain tumor segmentation algorithms.</p><p>For each patient, five distinct 3D volumetric MRI scans are provided. T1-weighted (T1): Provides detailed anatomical information. T1-weighted with contrast enhancement(T1-ce): Uses a contrast agent to highlight the active, enhancing parts of the tumor and necrotic core. T2-weighted (T2): Is particularly sensitive to areas with high water content, clearly showing the edema (swelling) around the tumor. Fluid Attenuated Inversion Recovery (FLAIR): Like T2, but suppresses the signal from cerebrospinal fluid, making the edema even more conspicuous and the Segmentation file.</p><h3>Data Processing</h3><p>The MRI scans and their corresponding segmentation masks, which are in the NIfTI format, were loaded using the nibabel library. The intensity values of the MRI images (Flair, T1ce, T2) were scaled using MinMaxScaler from scikit-learn. Each modality was reshaped to a 2D array, scaled between 0 and 1. This step helps in standardizing the intensity range across different scans. The segmentation masks have classes represented by values 0,1,2, and 4. To work with a consistent range of class indices for one-hot encoding and model output (0 to 3), the class value 4 was remapped to 3. The images and masks were centrally cropped to a uniform size of (128,128,128). This step is important for handling variations in image dimensions in the dataset and reducing computation load. The crop was applied to combined image modalities and to the segmentation mask. Volumes with very small tumor regions were filtered out. The was performed by checking the unique values and their counts in the cropped segmentation mask. If the proportion of non-background pixels was below a certain threshold (0.01), the sample was ignored during the saving process.</p><p>The three pre-processed modalities for each patient were stacked along a new dimension to create a multi-channel input tensor. The shape of this stacked tensor became (D,H,W,C), depth, height, width, channels, eg, (128,128,128,3). The preprocessed and cropped segmentation masks were converted from indexed class labels (0,1,2,3) into a one-hot encoded format. This results in a mask tensor of shape (D,H,W,C), depth, height, width, number of classes, eg, (128,128,128,4). The preprocessed image volumes and their corresponding one-hot encoded masks were saved. The saved preprocessed data was split into training, validation, and test sets with a ratio of 75% for training, 15% validation, and 10% test. BratsDataset and DataLoader were implemented to efficiently load the preprocessed numpy files during training, validation, and testing. This custom dataset handles loading the images and mask files, converting them to PyTorch tensors, and permuting the axes to the required format for 3D CNNs.</p><h3>3D Segmentation</h3><p>The 3D U-net is a convolutional neural network designed specifically for volumetric medical image segmentation, extending the original 2D U-Net by incorporating a third spatial dimension to capture contextual information across MRI slices. Its structure follows, as shown in Figure 1, a characteristic encoder-decoder design with skip connections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*KYHQljQ6ofYkklSVHujv4Q.png" /><figcaption>3D U-Net Architecture</figcaption></figure><p>Encoder: progressively downsamples the 3D volume, reducing spatial resolution while increasing the number of feature maps to capture an increasingly abstract representation of tumor structure.<br> <br>Bottleneck Layer: the central layer where the network encodes the most compressed representation of the input volume, retaining rich semantic features.<br> <br>Decoder: upsamples the feature amps back to the original spatial resolution. Skip connections link encoder layers to decoder layers, ensuring that fine-grained spatial details are preserved while reconstructing the segmentation mask. The output layer produced a multi-channel 3D segmentation mask, where each channel corresponds to a predicted tumor subregion.</p><p>The forward method features how the input tensor flows through the network. It shows the sequence of operations, including the down-sampling in the encoder, the bottleneck, the up-sampling and the skip connection in the decoder, and the final output convolution.</p><p>Then, initiate the U-Net 3D model with the 3 input channels (for the MRI modalities) and 4 output channels (for the classes). It then creates a dummy input tensor with a batch size of 1 and the expected dimensions. The input tensor is passed through the model to perform a forward pass, and the shape of the input and output tensors is printed. This is a simple check to ensure the model is structured correctly and the tensor dimensions are as expected. The output shape confirms that for a single input volume with 3 channels and dimensions 128x128x128, the model outputs a volume of the same spatial dimensions but with 4 channels, corresponding to the predicted logits for each class at every voxel.</p><h3><strong>Visualisation</strong></h3><h4>3D Visualization Web Application</h4><p>The primary purpose of this application is to provide a dynamic and intuitive tool for the qualitative analysis of the BraTS2021 dataset. Instead of viewing 2D slices, this tool reconstructs the tumor and surrounding brain anatomy as a complete 3D model, allowing for a more holistic understanding of the tumor size, shape, and location. The application is built using the Flask web framework, which runs on a local web server to handle data processing and render the final visualization in a standard web browser.</p><p>The application operates using a multi-page structure, with two main components or routes: a homepage for patient selection and another dedicated page for the 3D visualization. The homepage when the user first navigates to the web server’s address, this function is executed. Its job is to automatically scan the specified data directory and identify all the patient subfolders. It then generates a simple, user-friendly homepage containing a dropdown menu with all the patient IDs. This page allows the user to easily select any patient from the dataset for visualization.</p><p>Next, on the visualization page, Figures 2 and 3, when the user selects a patient and clicks ‘Visualize’, the browser is directed to a unique URL for that patient. This triggers the main visualization pipeline. The script loads the necessary NIfTI files for the selected patient, the ground truth segmentation, and the T1-weighted anatomical scan. The core of the 3D reconstruction happens here. The script processes both the T1 scan and the segmentation mask to create 3D surface models using the Marching Cube algorithm, which is a computer graphics method for extracting a polygonal mesh of an isosurface from three-dimensional volumetric data. It generates a separate mesh for the brain surface and for each tumor (Necrotic Core, Edema, and Enhancing Tumor) based on their labels in the segmentation mask. Using the Plotly library, an open-source graphic and data visualisation library, the script constructs a 3D scene, and each generated mesh is added to the scene as an object, with specific properties for colour, opacity, and lighting to ensure a clear and informative visual. Finally, the complete interactive figure is converted into a self-contained block of HTML and JavaScript. This HTML is then sent to the user’s web browser, which renders the final, interactive 3D plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkLCRCfBO5WS6zcNuD1YlA.png" /><figcaption>3D tumor mesh of patient</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwi7ys-vx-sOjhwm_cbXXA.png" /><figcaption>Whole 3D brain-tumor mesh of patient</figcaption></figure><h4>Softmax Probability Map</h4><p>Represent the model’s confidence for each class at each voxel. The Softmax function is applied to the raw neural network outputs at the end of the model and converts them into a probability distribution. For every voxel in the 3D scan, the Softmax ensures that each class’s scores are between 0 and 1 and that all class probabilities sum to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVDjiKnJbtgDyTvdTOAA_w.png" /><figcaption>Softmax Probability Map, for each class (Background, Necrotic core, Edema, and Enhancing Tumor), row-wise respectively, showing 5 slices [0,31,63,95,127], column-wise, for the axial plane, slice 95 shows the best tumor view, bright regions (yellow) represent high probability and strong model confidence, while darker regions (black) indicate lower probability and greater uncertainty about voxel belongs to that class.</figcaption></figure><p>In Figure 4, in the Softmax probability map, on the predicted images, for each of the four classes (Background, Necrotic core, Edema, Enhancing Tumor, order-wise), for selected slices, allows us to see the model’s confidence distribution across different regions and classes. A bright colour (like yellow or red in the ‘hot’ colourmap) indicates a high probability for that specific class at that voxel, meaning the model is more certain about that classification. Conversely, a dark colour (like black or dark red) indicates a low probability for that class at that voxel, meaning the model is less certain that the voxel belongs to that class. A higher intensity value (brighter colour) in a specific pixel of the probability map for a class indicates a higher likelihood that the corresponding voxel in the original image belongs to that class.</p><h4>Monte Carlo Dropout</h4><p>It is a widely used technique to estimate model uncertainty in deep learning by enabling dropout layers during inference and performing multiple stochastic forward passes. Each pass effectively samples a thinned version of the network, producing slightly different predictions. Averaging across predictions yields mean probabilities, while the variance provides an estimate of uncertainty, which is particularly valuable in safety-critical domains such as medical imaging. Each forward pass with dropout enabled will effectively use a slightly different thinned version of the network due to randomly dropping out neurons. This results in slightly different predictions.<br> The first equation estimates the mean probability by averaging predictions across many stochastic forward passes with dropout enabled, while the second equation uses the variance across passes to approximate the model’s uncertainty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOruJrTML5QdKuKjKZcm-w.png" /><figcaption>Monte Carlo Uncertainty Map, for each class (Necrotic core, Edema, and Enhancing Tumor), row-wise respectively, showing 5 slices [0,31,63,95,127], column-wise, for the axial plane, slice 95 shows the best tumor view, brighter regions indicate high variance, where the model’s predictions fluctuate across runs, reflecting greater uncertainty. This is most visible near tumor boundaries, where tissue transitions are naturally ambiguous</figcaption></figure><p>As in Figure 5, bright color (yellow) indicates high variance. Dark color (red) indicates low variance. So, Low variance is generally a good sign because it means the model’s predictions for that region are consistent across different dropout masks, which indicates higher confidence in the prediction for the target class (Necrotic core, Edema, Enhancing Tumor), visualizing uncertainty. High variance (bright colors) shows that the model’s predictions for that region fluctuate significantly across runs, suggesting lower confidence or greater uncertainty about the classification of those pixels for the target class. Boundaries are ambiguous; the transition between different tissue types or tumor subregions in medical images is rarely perfectly sharp, and there is often a gradient of intensity at the edges. This indicates that the model is appropriately expressing higher uncertainty, challenging to segment.</p><h4>Grad-CAM (Gradient-weighted Class Activation Mapping)</h4><p>It is a popular method for visualising neural network decision-making by creating a class-specific heatmap based on the gradient signal flowing into convolutional layers. In medical imaging, Grad-CAM helps pinpoint regions of interest, such as tumor locations, to increase interpretability and clinicians’ trust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6u22ixtYPPacjf5PnkbBeQ.png" /><figcaption>Grad-CAM Heatmap, for each class (Necrotic core, Edema, Tumor, and Enhancing Tumor), row-wise respectively, showing 5 slices [0,31,63,95,127], column-wise, for the axial plane, slice 95 shows the best tumor view, highlights the regions most important for the model’s prediction by weighting feature maps with their gradients. Brighter areas in the heatmap show regions that contributed more strongly to the chosen class.</figcaption></figure><p>In Figure 6, it works by using the gradients of the target class score concerning the feature maps of a chosen convolutional layer. These gradients indicate the importance of each feature map for that class, by showing the MRI scans of the modalities row-wise, T1ce, FLAIR, T2, with 5 slices [0,31,63,95,127]. The gradients are then used as weights to compute a weighted sum of the feature maps. This weighted sum is passed through a ReLU activation to highlight positive contributions, resulting in a heatmap. This heatmap is then resized to the original image dimensions. A higher intensity value in the Grad-CAM heatmap overlaid on the original image indicates that the corresponding region in the input image was more important for the model’s prediction of the target class you selected for Grad-CAM. It visually shows the spatial regions that “activate” the network for a particular class.</p><h3><strong>Results</strong></h3><p>The 3D U-Net model was trained for 50 epochs to evaluate its performance on the brain tumor segmentation task. The training process and model performance were monitored using the Dice score, the intersection over union (IoU), and a combined loss function, with the results evaluated in the test set.</p><p>The proposed 3D U-Net model demonstrates robust performance on the held-out test set, achieving a mean Dice coefficient of 0.8394 across all tumor sub-regions and an overall Monte Carlo accuracy of 86.52 percent. The model exhibits particularly strong segmentation capability for the necrotic core region (Dice:0.8443, IoU:0.7702) and edema (Dice:0.8501, IoU:0.7785), while maintaining competitive performance for the enhancing tumor region (Dice: 0.8248, IoU: 0.7539). The relatively low test loss of 0.1492 indicates good model convergence without overfitting, as evidenced by the minimal gap between validation and test performance metrics. These results are particularly noteworthy considering the model was trained for only 50 epochs due to computational constraints, suggesting that the architecture effectively learned discriminative features for multi-class brain tumor segmentation. The balanced performance across all tumor sub-regions demonstrates the model’s ability to distinguish between complex tissue boundaries, which is crucial for clinical applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*cRTtT5cXmduOPq75fJFbJQ.png" /><figcaption>Test set evaluation results, where class 0 is background, class 1 is Necrotic core, class 2 is Edema, and class 3 is Enhancing tumor.</figcaption></figure><p>The proposed 3D U-Net model demonstrates robust performance on the held-out test set, achieving a mean Dice coefficient of 0.8394 across all tumor sub-regions and an overall Monte Carlo accuracy of 86.52 percent. The model exhibits particularly strong segmentation capability for the necrotic core region (Dice:0.8443, IoU:0.7702) and edema (Dice:0.8501, IoU:0.7785), while maintaining competitive performance for the enhancing tumor region (Dice: 0.8248, IoU: 0.7539). The relatively low test loss of 0.1492 indicates good model convergence without overfitting, as evidenced by the minimal gap between validation and test performance metrics. These results are particularly noteworthy considering the model was trained for only 50 epochs due to computational constraints, suggesting that the architecture effectively learned discriminative features for multi-class brain tumor segmentation. The balanced performance across all tumor sub-regions demonstrates the model’s ability to distinguish between complex tissue boundaries, which is crucial for clinical applications.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, this project demonstrates that a 3D U-Net, coupled with advanced interpretability techniques, serves as a powerful and transparent tool for automated brain tumor segmentation. The ability to not only produce accurate segmentation masks but also to provide insights into the model’s confidence and reasoning is a critical step towards building trust and facilitating the adoption of such AI-driven tools in a clinical setting. The visualization and analyses performed in this work lay the groundwork for a more comprehensive understanding of tumor morphology, which can ultimately aid clinicians in diagnosis, treatment planning, and patient monitoring. The application leverages the Marching Cubes algorithm to generate interactive 3D surface models of the brain and constituent tumor subregions. This provides a powerful and accessible platform for the qualitative analysis and intuitive understanding of complex volumetric medical data.</p><p>Github link: <a href="https://github.com/evssaini/3D_brain_tumour.git">https://github.com/evssaini/3D_brain_tumour.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98ad5168f015" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis of research paper: ‘Humans Have an Expectation That Gaze Is Directed Toward Them’]]></title>
            <link>https://medium.com/@ershveers/humans-have-an-expectation-that-gaze-is-directed-toward-them-d88ff4b947f8?source=rss-170ac36bb9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d88ff4b947f8</guid>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cognitive-robotic]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ershveer Singh Saini]]></dc:creator>
            <pubDate>Wed, 21 May 2025 09:24:06 GMT</pubDate>
            <atom:updated>2025-05-22T09:02:01.205Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>My understanding</strong></h3><p>The paper “Humans Have an Expectation That Gaze Is Directed Toward Them” investigates how people perceive the direction of another’s gaze and posits that humans carry an inherent bias toward interpreting ambiguous gaze as being directed at them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQCa37kbdEX1_bHLH4XKfw.png" /></figure><p>The authors employed a Bayesian framework to model gaze perception, proposing that when visual information is degraded or uncertain, such as in low-light conditions or when the eyes are obscured by noise, the brain’s prior expectation of direct gaze exerts a stronger influence on perception.</p><p>In their experiments, participants viewed synthetic faces with varied gaze deviations under low and high uncertainty conditions. By adding fractal noise selectively to the eye region, the researchers manipulated the reliability of the sensory signal. The responses, measured as the proportion of “direct” versus “averted” gaze judgments, were fitted with a logistic function to estimate discrimination thresholds and biases.</p><p>The data showed that increased uncertainty resulted in a systematic shift: ambiguous stimuli were more likely to be perceived as looking directly at the observer. Moreover, the Bayesian model, incorporating a Gaussian prior, accounted for a large proportion of the variance in the observed judgments.</p><p>The study concludes that the adult visual system not only processes sensory gaze information but also relies on prior expectations, a mechanism that may have important implications for social communication and understanding atypical gaze processing in clinical populations.</p><p>Link to research paper: <a href="https://www.cell.com/current-biology/fulltext/S0960-9822(13)00332-1?_returnURL=https%3A%2F%2Flinkinghub.elsevier.com%2Fretrieve%2Fpii%2FS0960982213003321%3Fshowall%3Dtrue">https://www.cell.com/current-biology/fulltext/S0960-9822(13)00332-1?_returnURL=https%3A%2F%2Flinkinghub.elsevier.com%2Fretrieve%2Fpii%2FS0960982213003321%3Fshowall%3Dtrue</a></p><h3><strong>Dataset I used</strong></h3><p>‘The Columbia Gaze Data Set’<strong> </strong>is a comprehensive collection of high-resolution facial images specifically designed for research on gaze tracking and perception. It consists of thousands of face images captured under controlled conditions with detailed information about each subject’s gaze direction and head pose.</p><p>In addition to the images, the dataset provides extensive metadata, including camera configuration details, such as focal lengths and sensor sizes, organized in an Excel file, and precise eye corner coordinates recorded via Omron’s OKAO Vision system (as detailed in the associated CSV file). These annotations enable researchers to accurately locate facial landmarks and calibrate automated gaze tracking algorithms.</p><p>The dataset is valuable for investigating how humans interpret gaze direction, analyzing the relationship between head orientation and eye gaze, and developing robust machine learning models for gaze estimation. Its rich annotations support precise evaluation of discrimination thresholds and biases in gaze perception.</p><p>Researchers use the dataset both to explore fundamental questions in social cognition, such as the inherent bias to perceive direct gaze, and to benchmark computational methods for automated gaze detection. In summary, the Columbia Gaze Data Set is an important resource that combines high-quality visual data with detailed calibration information, making it ideal for advancing studies in computer vision, human behavior, and neuropsychology.</p><p>The data set contains a total of 5,880 high-resolution images of 56 subjects (32 male, 24 female), and each image has a resolution of 5,184 x 3,456 pixels. 21 of its subjects are Asian, 19 are White, 8 are South Asian, 7 are Black, and 4 are Hispanic or Latino. Its subjects range from 18 to 36 years of age, and 21 of them wear prescription glasses.</p><p>The data set includes images for each combination of five horizontal head poses (0°, ±15°, ±30°), seven horizontal gaze directions (0°, ±5°, ±10°, ±15°), and three vertical gaze directions (0°, ±10°) for each subject. This means that we collected five gaze locking images (0° vertical and horizontal gaze direction) for each subject: one for each head pose.</p><p>Link to dataset: <a href="https://ceal.cs.columbia.edu/columbiagaze/">https://ceal.cs.columbia.edu/columbiagaze/</a></p><p>Github: <a href="https://github.com/evssaini/Human_Gaze_Project_Work.git">https://github.com/evssaini/Human_Gaze_Project_Work.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d88ff4b947f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deeper Networks for Image Classification, analysis on convolutional neural network (CNN)…]]></title>
            <link>https://medium.com/@ershveers/deeper-networks-for-image-classification-analysis-on-convolutional-neural-network-cnn-40e6437a5406?source=rss-170ac36bb9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/40e6437a5406</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[self-study]]></category>
            <category><![CDATA[projects]]></category>
            <dc:creator><![CDATA[Ershveer Singh Saini]]></dc:creator>
            <pubDate>Sun, 11 May 2025 10:31:07 GMT</pubDate>
            <atom:updated>2025-05-11T10:54:58.286Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deeper Networks for Image Classification, analysis on convolutional neural network (CNN) architectures.</h3><p>This article details an experimental study on applying and evaluating deep Convolutional Neural Networks (CNNs) for image classification tasks using MNIST and CIFAR-10 datasets. The article focuses on implementing and comparing two CNN architectures, VGG16 and ResNet18. The study involves training these networks under different conditions, including training from scratch, for the simpler MNIST dataset and utilizing transfer learning with pre-trained weights for the more complex CIFAR-10 dataset. The report describes the data loading, preprocessing, model building, training, and evaluation methodologies. Results are presented and evaluated properly, supported by training logs, loss, and accuracy curves. A critical analysis of the pros and cons of each architecture based on their performance and training characteristics on the chosen datasets. The article highlights the impact of the design of architectures and transfer learning alongside the advanced training techniques used to achieve high accuracy on image classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rw-u6qHNC3cdZcmBN7p_CA.png" /><figcaption>AI generated</figcaption></figure><ol><li><strong>Introduction</strong></li></ol><p>Image classification stands as a fundamental issue in the domain of computer vision, with numerous applications ranging from autonomous driving to medical imaging to content moderation. In recent years, deep CNNs have been emerging and revolutionised the field of AI. Their capacity to model complex patterns through multiple layers of convolution and non-linear operations, combined with advancements in computing power, as well as the large-scale labelled dataset.</p><p>This aims to provide hands-on experience in applying such architectures to the datasets mentioned above and evaluating these deep CNNs for image classification. The objectives are:</p><p>1. Implement and train VGG16, ResNet18 for image classification.</p><p>2. Utilize the MNIST dataset and an additional dataset, called CIFAR-10, to evaluate the networks.</p><p>3. Perform and evaluate the classification tasks, including monitoring the training process and quantitatively assessing the results.</p><p>4. Conduct a critical analysis of the models chosen, based on their architectural principles and experimental performance.</p><p>2. <strong>Methodology</strong></p><p>This section outlines the dataset used, the data preprocessing and augmentation techniques applied, and the architectures of the deep CNNs implemented for the image classification tasks.</p><p>2.1 Datasets:</p><p>2.1.1. MNIST</p><p>The dataset consists of 60,000 grayscale images of handwritten digits (0–9) for training, 50,000 images, 10,000 for validation (after splitting), and 10,000 for testing. Each image has a resolution of 28x28 pixels, for compatibility with the CNN architectures, which are typically designed for colour images, the grayscale channel was replicated three times to create a pseudo RGB input. Moreover, the images were resized into 224x224 pixels, the standard input size of models pre-trained on ImageNet, to facilitate potential transfer learning experiments and ensure compatibility with the architecture of the network, which is designed for larger inputs.</p><p>2.1.2. CIFAR-10</p><p>This dataset comprises of 60,000 colour images across 10 classes. The dataset is split into 50,000 training images, out of that 5,000 used for validation and rest 10,000 used for testing. Each image has a resolution of 32x32 pixels, this dataset presents a more challenging classification task as compared to MNIST due to its colour nature and more diverse object categories.</p><p>2.2 Data Preprocessing and Augmentation:</p><p>Consistent and appropriate data processing is crucial for training deep CNNs.</p><p>The steps I followed:</p><p>a. Resizing the images from both MNIST and CIFAR-10 datasets, into 224x224 pixels. For MNIST this action was crucial to match the expected input dimensions of the deep networks. Whereas for CIFAR-10, resizing was also applied to align with the input size of models pre-trained on ImageNet, for test and validation sets, a standard approach of resizing to 256x256 followed by a centre crop to 224x224 was used to maintain consistency.</p><p>b. Tensor conversations, images were converted to PyTorch tensors, scaling the pixel values to the range [0,1].</p><p>c. Normalization was essential to center the data and scale it to a similar range, thus improving the training stability:</p><p>· For the MNIST dataset, which was trained from scratch, normalization was performed using the dataset’s mean (0.1307) and standard deviation (0.3081) for grayscale images, which were then applied across the three replicated channels.</p><p>· For CIFAR-10 and MNIST, when using pre-trained models, normalization was performed using the mean (0.485, 0.456, 0.406) and standard deviation (0.229, 0.224, 0.225) of the ImageNet dataset. This is important when using pre-trained weights, as the model expects input data to be normalized in the same way as the data it was originally trained on.</p><p>d. Channel Replication (MNIST dataset), for MNSIT, as mentioned before, the single grayscale channel was replicated three times to create a 3-channel input, compatible with the standard input layer of the chosen CNN architectures.</p><p>e. Data Augmentation (CIFAR-10), for training, to reduce overfitting, particularly when using a large model such as VGG16 or ResNet18 on a relatively smaller dataset like CIFAR-10, data augmentation includes:</p><p>· RandomResizedCrop(224, scale=(0.8, 1.0)): Randomly crops a portion of the image and resizes it to 224x224.</p><p>· RandomHorizontalFlip(): Randomly flips the image horizontally.</p><p>· RandomRotation(15): Randomly rotates the image by up to 15 degrees.</p><p>· ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2): Randomly adjusts the brightness, contrast, and saturation of the images. Data augmentation was applied <em>only</em> to the training set, the validation and test sets were used only for resizing and normalization.</p><p>2.3 Architectures:</p><p>a. VGG16: This architecture is characterized by its simplicity and uses 3x3 filter, stacked in a uniform manner to increase the depth. The ‘D’ configuration of VGG16, with 16 layers, was used. It consists of 13 convolution layers and 3 fully connected layers, separated by max-pooling layers.</p><p>b. ResNet18: This architecture addresses the degradation problem in very deep networks by the introduction of ‘residual connections’, that allow gradients to flow more easily through the network. It has 18 layers; the structure involves convolution layers followed by blocks containing residual connections and ending with global average pooling layer and a fully connected layer.</p><p>Pre- built implementation of these architectures from torchvision.models were primarily used to establish structures for CIFAR-10, their weights pre-trained on ImageNet. A manual implementation of VGG16 was also attempted on CIFAR-10 dataset from scratch as a learning experience.</p><p>2.4 Model Adaptation:</p><p>To adapt the pre-built models to the specific datasets:</p><p>a. Input Layer: For the MNIST dataset, which is grayscale, the first convolutional layer of each network was modified to accept 3 input channels after the grayscale channel replication, and for the CIFAR-10, which already a 3 channels, sucha type of modification was not needed.</p><p>b. Classification Layer: The final fully connected layer of each network, classifier was replaced to output 10 features, corresponding to the 10 classes in both MNIST and CIFAR-10 dataset, the input size to the new classifier was matched to the output size of the network’s feature extractor after the last convolution layer/ pooling layer, in consideration of 224x224 input image size.</p><p>3. <strong>Implementation Details</strong></p><p>This section talks about the training and evaluation setup, including optimization, regularization, scheduling, and early stopping. It will also shed light upon the implementation process and the evidence collected.</p><p>3.1 Training Setup:</p><p>The models were trained using the following setup:</p><p>1. Loss Function: Cross Entropy Loss (nn.CrossEntropyLoss) was used, a very common choice for many for multi-class classification, for the enhanced training on CIFAR-10, label smoothing, with a factor of 0.1 was applied to the Cross Entropy Loss. Label smoothing is a regularization technique that encourages the model to be less confident in its predictions, improving generalization.</p><p>2. Optimizer: The Adam optimizer (optim.Adam or optim.AdamW) was used to update the weights of the model during the training phase. AdamW is a variant that decouples weight decay from the L2 regularization term in the loss function, which often most of the times leads to better performance.</p><p>3. Learning Rate: An initial learning rate was set, 0.01 for initial MNIST runs, then 0.001 or 0.0005 for CIFAR-10 fine-tuning.</p><p>4. Weight Decay: For the enhanced training on CIFAR-10, weight decay, L2 regularization, was used through the optimizer, AdamW, to penalize large weights and reduce overfitting to be reduced.</p><p>5. Batch size: The batch size was set to 64 for initial runs and increased to 128 for the enhanced CIFAR-10 training to potentially improve gradient estimates and utilize GPU memory more efficiently.</p><p>6. Epochs: The number of training epochs was set, 20 initially, then to 50 for enhanced training.</p><p>7. Device: Training was performed on Google Colab Pro, GPU.</p><p>8. Transfer Learning and Fine Tuning: For the CIFAR-10 dataset, the models were trained using trained learning, and pre-trained weights from ImageNet were loaded. The final classifier layers were replaced to match the 10 CIFAR-20 classes. Fine-tuning involved training the entire network, although initial experiments sometimes included freezing the earlier layers of the feature extractor for a few epochs before unfreezing them.</p><p>9. Learning Rate Scheduling: To adjust the learning rate during training, a scheduler was employed for the enhanced CIFAR-10 runs. ReducedLROnPlateau was used; its role is to reduce the learning rate when the validation accuracy stops.</p><p>10. Early Stopping: To prevent overfitting and reduce unnecessary training, early stopping was implemented. Training was halted if the validation accuracy did not improve for a set number of epochs (patience), and the model state dictionary with the best validation accuracy was saved.</p><p>The project was implemented using the PyTorch deep learning framework. The code was developed and executed within Google Colab Pro notebooks to utilize GPU resources. The code was modularized into sections for data processing, model definition, training loop, and evaluation.</p><p>The implementation code for each model and dataset combination covered all the aspects, allowing for consistent training, evaluation, and documentation across the experiments. The best-performing model based on validation accuracy was saved using torch. Save to be loaded later for the final evaluation on the test size.</p><p>4. <strong>Implementation Process Analysis</strong></p><p>This section presents the analysis of the implementation process and observed training dynamics, referencing the collected evidence.</p><p>The implementation process involved adapting the chosen architectures and training procedures to the characteristics of the MNIST and CIFAR-10 datasets.</p><p>1. Early Underfitting: Initial CIFAR-10 scratch Training, when attempting to train VGG16 from scratch on the CIFAR-10 dataset without sufficient data augmentation or a carefully tuned learning rate, the model showed underfitting, which resulted in test accuracy close to random guessing, the loss and accuracy curves in the training logs showed minimal or no improvement over many epochs, indicating the model not efficiently learning from the data.</p><p>2. Impact of Transfer Learning: Introducing transfer learning by loading pre-trained weights from ImageNet significantly improved the initial performance on CIFAR-10. Using the pre-trained VGG16 and ResNet18 models as feature extractors and fine tuning them on CIFAR-10 resulted in better accuracies. This demonstrated the efficiency of leveraging featured learned from a large-scale dataset.</p><p>3. Addressing Overfitting and Improving Generalization: CIFAR-10 fine-tuning, transfer learning provided a good starting point, achieving higher accuracies, but still required further optimization and regularization. The training logs and validation curves revealed signs of overfitting, where the training accuracy continued to rise while the validation accuracy came to a plateau or kept decreasing. To prevent or mitigate this and improve generalization, several techniques were implemented:</p><p>a. Enhanced Data Augmentation: Applying data augmentation (RandomResizedCrop, RandomHorizontalFlip, RandomRotation, ColorJitter) during the training expanded the dataset, and made the model more robust to variations in the input images. The loss and accuracy plots showed a reduction in the gap between training and validation performance.</p><p>b. Learning Rate Scheduling: By using a learning rate schedular like ReduceLROnPlateau, helped the optimizer converge more efficiently in the later stages of fine-tuning. The logs shoed the learning rate decreasing when validation accuracy stopped improving, thus allowing for finer adjustment to the weights.</p><p>c. Regularization: weight decay, dropout, BatchNorm, Label Smoothing, the inclusion of weight decay in the optimizer, dropout layers in the classifier, batch normalization, and label smoothing in the loss function, all contributed to preventing overfitting and improving the model’s ability to generalize to unseen data. The validation curves in the graph became smoother and reached higher levels.</p><p>d. Early Stopping: Implementation of early stopping based on validation accuracy ensured that training halted when performance on the validation set plateaued, thus model to prevent the further overfitting to the training data. The saved model with the best validation accuracy was used for the test evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ov3OoyArSbLkhwdMDCmsQ.png" /><figcaption>VGG16 on MNIST</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUd-DUKM2Sisep4duKCvmA.png" /><figcaption>ResNEt-18 on MNIST</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpSLuhqz2Dw3wXcIeJudgg.png" /><figcaption>VGG16 on CIFAR-10, did not perform well enough, overfitting</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ve8TPL1aiwkshdVYjP_3g.png" /><figcaption>VGG16 on CIFAR-10, used transfer learning, around 80% accuracy on validation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P26L3wKOnzOoV_W04fSfUg.png" /><figcaption>VGG16 on CIFAR-10, improved version of transfer learning, with 92% accuracy on validation.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHG7dj0iCRbxWbdPrOSk1Q.png" /><figcaption>ResNet18 on CIFAR-10, 93% accuracy on validation.</figcaption></figure><p>5. <strong>Critical Analysis</strong></p><p>This section provides a critical analysis of the performance and characteristics of the VGG16 and ResNet18 architectures based on the results.</p><p>1. Performance on MNIST: The MNIST dataset is relatively simple, and it is expected to achieve very high accuracy, in this case, advance features of ResNet18 may not offer a significant advantage in terms of peak accuracy compared to the depth of VGG16. However, training times and convergence speed might differ.</p><p>2. Performance on CIFAR-10: With the colour images and greater visual diversity, it provides a better benchmark for evaluating the capabilities of these deeper networks. When fine-tuned with a pre-trained weight, significant performance differences are often seen, such as below:</p><p>a. VGG16: While achieving a good accuracy with fine tuning, this network might be more prone to overfitting on CIFAR-10 dataset as compared to ResNet18 due to its large number of parameters in the fully connected layers. The training curves will show a more significant gap between training and validation accuracy, if data augmentations and regularizations are not applied.</p><p>b. ResNet18: With its connections, it is generally expected to perform very good on CIFAR-10 when it is fined tuned, the residual connections help in training deeper networks more effectively, leading to a better generalization and better high accuracy as compared to the VGG16 network, when dataset is larger enough. ResNet’s architecture is often better, and efficient in terms of computation than the VGG16 for the similar levels of accuracy.</p><p>3. Architecture Principles: The results reflect the core design principles of each network, VGG’s performance showcases the importance of depth where whereas the ResNet’s effectiveness shows the power of residual learning and a performant model.</p><p>4. Training Characteristics: The training logs and plots provide how each network converges, factors like steepness of loss curve, the rate of accuracy increase, and the degree of overfitting offer insights into the training dynamics.</p><p>6. <strong>Conclusion</strong></p><p>This project successfully implemented and evaluated VGG16 and ResNet18 architectures for image classification on MNIST and CIFAR-10 datasets. The experiments show the effectiveness of deep CNNs for these tasks and highlights the critical role of data processing, augmentation, and training techniques, transfer learning, to achieve high accuracy on datasets.</p><p>The analysis of the architecture revealed that while all can perform well on a simple task like MNIST, their distinct design principles lead to differences in performance, efficiency, and training characteristics on a more challenging dataset like CIFAR-10. ResNet’s residual connections represent significant advancements over the simpler depth of VGG, often resulting in better generalization and efficiency when applied with transfer learning.</p><p>Github:<br><a href="https://github.com/evssaini/Deeper-Networks-for-Image-Classification.git">https://github.com/evssaini/Deeper-Networks-for-Image-Classification.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40e6437a5406" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>