Let's Visualize How CNN Works

Trying to interpret things

Introduction to CNNs

Convolutional Neural Networks (CNNs) have revolutionized the field of computer vision, enabling breakthroughs in image classification, object detection, and more. I recently started reading papers from scratch and during that I am trying to implement and understand things more deeply. This is partly inspired by the original AlexNet paper and Mechanistic Interpretability work by Chris Olah. I had many questions while reading the AlexNet paper, so I decided to write everything from scratch, and during that process, I got an idea to visualize things as I go.

My Takeaways from AlexNet

Original vs. Normalized Images

Original Image

- Description: The unaltered, raw input image with original pixel intensity values.
- Features: Retains original colors, brightness, and contrast as captured or provided in the dataset.
- Role: Serves as the initial input to the model without any preprocessing.

Original Image

Normalized Image

During my experiments, I noticed how this normalization step makes a huge difference in training. By scaling pixel values to a standard range (typically between 0 and 1 or -1 and 1), we're essentially leveling the playing field for all our input data. It's like giving our CNN a standardized language to work with, rather than having it deal with wildly varying scales. This preprocessing step might seem simple, but it's one of those foundational concepts that every deep learning practitioner should understand. Having the mean centered at 0 is particularly valuable, as it helps maintain gradient symmetry and works especially well with activation functions like tanh that are centered around 0. This centering enables the network to learn both positive and negative correlations more easily while helping to mitigate floating point precision issues. Remember, the goal isn't just to make the images look different - it's about making them more suitable for our neural networks to process and learn from. Through visualization, we can better appreciate how this transformation affects our input data, even if the changes aren't always obvious to the human eye.

- Normalization Techniques: - Visual Differences: May appear darker or differently colored due to standardized pixel intensity ranges.
- Purpose: Enhances model training stability and accelerates convergence by ensuring consistent input ranges.

Normalized Image

I won't go much into building models because there are way better sources for that.

Model Architecture

Creating a CNN involves stacking layers that progressively extract higher-level features from the input images. Below is a guide to building a simple CNN, with considerations for kernel sizes and padding.

model = models.Sequential()

# Convolutional Layer 1
model.add(layers.Conv2D(32, (3, 3), activation='relu', padding='same', input_shape=(height, width, channels)))
model.add(layers.MaxPooling2D((2, 2)))

# Convolutional Layer 2
model.add(layers.Conv2D(64, (5, 5), activation='relu', padding='same'))
model.add(layers.MaxPooling2D((2, 2)))

# Convolutional Layer 3
model.add(layers.Conv2D(128, (7, 7), activation='relu', padding='same'))
model.add(layers.MaxPooling2D((2, 2)))

# Fully Connected Layers
model.add(layers.Flatten())
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dense(num_classes, activation='softmax'))

Visualizing with Grad-CAM

Grad-CAM Overview

Gradient-weighted Class Activation Mapping (Grad-CAM) is a technique that uses the gradients of any target concept (e.g., a specific class) flowing into the final convolutional layer to produce a localization map highlighting important regions in the image for predicting the concept.

During my deep dive into CNNs, one question kept nagging at me: how can we actually see what our model is looking at? This is where Gradient-weighted Class Activation Mapping (Grad-CAM) comes in, and it feels like getting X-ray vision into our neural networks.

Kernel Analysis

Different kernel sizes in CNNs affect the receptive field and feature extraction capabilities. Let's analyze how kernel size impacts the network's ability to capture patterns through activation maps and Grad-CAM visualizations:

Key insights from kernel size comparison:

Padding Analysis

By examining Grad-CAM visualizations with different padding configurations, we can understand how padding affects feature detection and model performance. Below are visualizations demonstrating the impact of padding settings:

Key observations from the padding comparison:

Stride Analysis

Stride configuration significantly impacts feature detection and spatial resolution in CNNs. Let's examine how different stride values affect feature extraction through activation maps and Grad-CAM visualizations:

Key observations from stride comparison:

Conclusion

Building and visualizing CNNs is an iterative process that requires careful consideration of various architectural components:

Through visualization techniques like Grad-CAM, we can:

Next Steps

To continue your CNN journey:

  • Experiment with different architectural configurations using the concepts discussed
  • Apply these visualization techniques to your own models
  • Explore how combining different configurations affects model performance
  • Practice interpreting activation maps and Grad-CAM visualizations

For further reading, explore our resources and experiment with your own CNN models using the concepts discussed here.

Additional Resources

CNN Visualization Tools

  • Grad-CAM Resources:
    • Original Grad-CAM Paper: "Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization"
    • PyTorch Implementation: pytorch-grad-cam library
    • TensorFlow Implementation: tf-keras-vis library

Interactive Learning

  • CNN Explainer: Interactive visualization of CNNs
  • TensorFlow Playground: Experiment with neural networks in browser
  • Distill.pub's CNN Articles: Visual, interactive explanations of CNNs

Implementation Guides

  • Deep Learning Frameworks:
    • PyTorch CNN Tutorials
    • TensorFlow CNN Guides
    • FastAI CNN Implementation Examples

Further Reading

  • Research Papers:
    • "Visualizing and Understanding Convolutional Networks" by Zeiler and Fergus
    • "Deep Inside Convolutional Networks" by Simonyan et al.
    • "Understanding Deep Image Representations by Inverting Them"