Skip to content

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Repository files navigation

๐Ÿง  Interactive CNN Neural Network Visualizer

Real-Time In-Browser Explainability, 3D Latent Space & Visual Inspection Suite for MNIST CNNs

Next.js React TypeScript Tailwind CSS License: MIT


An interactive, agency-grade web application designed to demystify deep learning for a 20-layer Convolutional Neural Network (CNN) trained on MNIST digit classification.

Built with Next.js 16, React 19, Tailwind CSS, HTML5 Canvas, SVG, and WebGL, this application executes 100% client-side forward pass inference and attribution math in pure TypeScriptโ€”visually rendering every filter kernel, feature map, batch normalization parameter, max pooling step, dense classification node, 3D latent vector embedding, and attribution heatmap in real time at 60 FPS.


๐Ÿš€ Getting Started

Tip

You can launch and test the visualizer locally in less than 2 minutes using Node.js.

Prerequisites

Requirement Supported Version Notes
Node.js v18.0.0 or higher Recommended LTS release
Package Manager npm v9+, pnpm, or yarn Native npm included with Node

Installation & Local Setup

  1. Clone the repository:

    git clone https://github.com/AmirHossein-84/Neural-Network-Visualizer.git
    cd Neural-Network-Visualizer/cnn-visualizer
  2. Install project dependencies:

    npm install
  3. Verify model manifest files: Ensure all 5 trained JSON manifests exist inside cnn-visualizer/public/model/:

    • ๐Ÿ“„ model_architecture.json
    • ๐Ÿ“„ conv_weights.json
    • ๐Ÿ“„ batchnorm_params.json
    • ๐Ÿ“„ dense_weights.json
    • ๐Ÿ“„ sample_predictions.json
  4. Start the local development server:

    npm run dev
  5. Open in browser: Navigate to http://localhost:3000.


๐Ÿ“‹ Table of Contents


Overview

Understanding the internal mechanisms of deep neural networks often feels like probing a black box. This visualizer exposes the inner workings of a trained 20-layer MNIST CNN model by enabling live digit drawing, real-time feature extraction inspection across 4 Conv2D layers, 1D/3D BatchNormalization tracking, 3D latent space embeddings, multi-mode explainability heatmaps, and interactive signal tracing through the Dense classification head.

Note

No backend or Python server is required during runtime. The model weights are loaded directly from static JSON manifests into a client-side TypeScript inference engine running on Web Worker background threads.


Key Features

๐Ÿ–Œ๏ธ Live Drawing Canvas & Input Modes

  • Interactive Canvas ($280 \times 280$): Draw custom digits with natural, continuous brush strokes automatically downsampled live to $28 \times 28$ grayscale float matrices.
  • Sample Test Gallery: Load pre-packaged test images from the MNIST dataset complete with ground-truth labels and model output confidences.

๐Ÿ”ฌ Advanced Explainability & Attribution Suite

  • Grad-CAM Pixel Sensitivity Heatmap: Calculates input pixel attribution gradients: $$S(i, j) = \left|\frac{\partial y_{\text{pred}}}{\partial x_{i,j}}\right|$$
  • Occlusion Sensitivity Mapping: Slides a $4 \times 4$ black mask across the grid to measure confidence drops: $$\text{Drop}{r,c} = P(y \mid x) - P(y \mid x{\text{masked } r,c})$$
  • SmoothGrad Noise Reduction: Averages 15 saliency passes over noisy variations ($x + \mathcal{N}(0, \sigma^2)$) to eliminate visual noise artifacts.
  • Contrastive Explanations ("Why 7 and not 1?"): Computes differential saliency between target digit vs a rival digit: $$\Delta S = \left|\frac{\partial y_{\text{target}}}{\partial x}\right| - \left|\frac{\partial y_{\text{rival}}}{\partial x}\right|$$
  • Receptive Field Inspector: Click any pixel in a feature map to highlight its exact $3 \times 3$ spatial receptive field window.
  • Interactive 3x3 Filter Editor: Modify kernel weights live or apply presets (Sobel Horizontal/Vertical, Sharpen, Ridge Detect).

๐ŸŒ 3D Latent Embedding & Architecture Battle

  • 3D Latent Point Cloud: Interactive WebGL 3D projection of 1,000 MNIST test samples in 128D dense_2 feature space. White animated marker tracks your live hand-drawn digit position.
  • Architecture Battle: Side-by-side real-time probability comparison between the 20-Layer Deep CNN vs a 2-Layer Simple MLP.

๐ŸŽฎ Gamified Adversarial Challenge Mode

  • Interactive AI Game: Test your drawing skills against 3 difficulty levels (Easy, Medium, Hard) to trick the model into misclassifying ambiguous digit strokes.
  • Score Tracking: Live score counters, high score persistence, and victory confetti animations when you successfully outsmart the neural network.

โบ๏ธ Forward Pass Model Debugger Playback

  • 3-Column Locked Dock: Fixed bottom controller for step-by-step model execution tracing.
  • Play Flow & Stepping: Automatically steps through all 20 layers every 1.2s or lets you step manually (โฎ Prev / โญ Next).
  • Auto-Tab Switching & Highlighting: Automatically switches between Conv Layers and Live Inference tabs, highlighting active layer cards in glowing cyan borders and scrolling them smoothly into view.

๐Ÿ•ธ๏ธ Dense Head Node-Link Visualizer

  • Interactive Node-Link Diagram: Visualizes the classification head sequence: $$\text{Flatten (3136)} \longrightarrow \text{Dense 1 (256)} \longrightarrow \text{Dense 2 (128)} \longrightarrow \text{Output (10)}$$
  • Hybrid Canvas + SVG Engine: GPU-accelerated 2D Canvas background line rendering with interactive SVG foreground nodes and viewport frustum culling.
  • Signal Pulse Particle Animation: Photon particles flowing along active weight paths (Cyan = +Weight, Crimson = -Weight).
  • Activation Threshold Slider: Filter out low-activation ReLU neurons ($0.0 \dots 0.5$).

๐Ÿ“ธ PNG Inspection Report Card

  • Full 10-Digit Report Export: Generates a downloadable $680 \times 420\text{px}$ PNG snapshot card showing the drawn digit, top prediction confidence, and all 10 output probability bars (0-9) formatted cleanly in two columns.

Visual Showcase


Tech Stack

graph TD
    Client["Client Browser"] --> Next["Next.js 16 (App Router)"]
    Next --> React["React 19 & Tailwind CSS v4"]
    React --> CanvasEngine["HTML5 2D Canvas & WebGL"]
    React --> Worker["Web Worker Thread"]
    Worker --> Engine["Pure TS Inference & Attribution Engine"]
    Engine --> Manifests["JSON Model Manifests (/public/model/)"]
Loading
Layer Technologies & Tools
Framework & UI Next.js 16 (App Router), React 19, Tailwind CSS v4, Lucide Icons, Canvas Confetti
Language TypeScript 5
Graphics Engine HTML5 2D Canvas, WebGL 3D Point Cloud, SVG Node-Link Diagram
Inference Engine Pure TypeScript client-side forward pass (src/lib/inference.ts), Web Worker thread (src/workers/inference.worker.ts)
Model Training Python 3, TensorFlow / Keras 2.x (train_mnist_model.py)

System Architecture

1. Model Training & JSON Manifest Export

The model is trained using Python (train_mnist_model.py) on Google Colab with GPU acceleration.

Important

The exact 20-layer Keras architecture sequence is:

Input(28, 28, 1) 
  โž” Conv2D(32, 3x3, relu, padding='same') โž” BatchNorm โž” Conv2D(32, 3x3, relu, padding='same') โž” BatchNorm โž” MaxPool2D(2,2) โž” Dropout(0.25)
  โž” Conv2D(64, 3x3, relu, padding='same') โž” BatchNorm โž” Conv2D(64, 3x3, relu, padding='same') โž” BatchNorm โž” MaxPool2D(2,2) โž” Dropout(0.25)
  โž” Flatten(3136)
  โž” Dense(256, relu) โž” BatchNorm โž” Dropout(0.5)
  โž” Dense(128, relu) โž” BatchNorm โž” Dropout(0.5)
  โž” Dense(10, softmax)

The script exports 5 JSON manifests into cnn-visualizer/public/model/:

  • model_architecture.json: Layer manifest (types, names, output shapes, filter counts).
  • conv_weights.json: Conv2D filter kernels [out_channels][3][3][in_channels] & biases.
  • batchnorm_params.json: BatchNorm parameters (gamma, beta, moving_mean, moving_variance).
  • dense_weights.json: Weight matrices [in_units][out_units] & bias vectors.
  • sample_predictions.json: Pre-packaged MNIST test images with true labels & probabilities.
  • cnn_mnist_model.keras: Native Keras model file.

2. Client-Side Inference Engine

Inference runs 100% client-side in TypeScript (src/lib/inference.ts) and Web Worker threads (src/workers/inference.worker.ts):

  1. conv2dSame: $3 \times 3$ 2D Convolution with stride 1 and 'same' zero-padding + ReLU activation.
  2. batchNorm3D & batchNorm1D: Inference mode Batch Normalization transformation: $$y_i = \frac{x_i - \text{moving_mean}_i}{\sqrt{\text{moving_var}_i + \epsilon}} \cdot \gamma_i + \beta_i$$
  3. maxPooling2D: $2 \times 2$ spatial Max Pooling with stride 2.
  4. flatten3D: Reshapes $[H, W, C]$ feature maps to 1D vector ($7 \times 7 \times 64 = 3136$).
  5. denseForward: Matrix vector multiplication $Y = \text{ReLU}(X \cdot W + B)$.
  6. softmax: Exponential probability normalization for 10 output classes.

3. Component Hierarchy

app/page.tsx (Main Viewport & Navigation Tabs)
 โ”œโ”€โ”€ DrawCanvas.tsx (280x280 Canvas + 28x28 Preview + Preset Digits)
 โ”œโ”€โ”€ SampleGallery.tsx (MNIST Test Set Carousel)
 โ”œโ”€โ”€ SaliencyOverlay.tsx (Grad-CAM, Occlusion, SmoothGrad & Contrastive Heatmaps)
 โ”œโ”€โ”€ OutputBars.tsx (Digit Probabilities & Winner Highlight)
 โ”œโ”€โ”€ ExportSnapshotButton.tsx (PNG 10-Digit Report Exporter)
 โ”œโ”€โ”€ ModelDebuggerBar.tsx (Persistent Playback Step Controller Dock)
 โ”œโ”€โ”€ ChallengeModeModal.tsx (Gamified AI Ambiguity Game)
 โ”œโ”€โ”€ LatentSpace3DModal.tsx (3D Latent Point Cloud & MLP Architecture Battle)
 โ”œโ”€โ”€ DenseLayerView.tsx (Hybrid Canvas/SVG Node-Link Classification Head)
 โ”‚    โ””โ”€โ”€ NeuronDetailPanel.tsx (Dense Neuron Inspector)
 โ”œโ”€โ”€ ConvLayerView.tsx (Conv2D Layer Accordion)
 โ”‚    โ”œโ”€โ”€ FilterGrid.tsx (3x3 Kernel Grid)
 โ”‚    โ””โ”€โ”€ FeatureMapGrid.tsx (Channel Thumbnails + Receptive Field Inspector)
 โ”œโ”€โ”€ FilterEditorModal.tsx (Live 3x3 Kernel Editor)
 โ”œโ”€โ”€ BatchNormPanel.tsx (Mean/Variance Sparklines)
 โ”œโ”€โ”€ PoolingComparisonView.tsx (Before vs After 2x2 MaxPool)
 โ””โ”€โ”€ DropoutCard.tsx (Inactive Rate Indicator)

Project Structure

Neural Network Visualizer/
โ”œโ”€โ”€ cnn-visualizer/                    # Next.js Web Application
โ”‚   โ”œโ”€โ”€ public/
โ”‚   โ”‚   โ””โ”€โ”€ model/                     # Exported Trained Model JSON Manifests
โ”‚   โ”‚       โ”œโ”€โ”€ model_architecture.json
โ”‚   โ”‚       โ”œโ”€โ”€ conv_weights.json
โ”‚   โ”‚       โ”œโ”€โ”€ batchnorm_params.json
โ”‚   โ”‚       โ”œโ”€โ”€ dense_weights.json
โ”‚   โ”‚       โ”œโ”€โ”€ sample_predictions.json
โ”‚   โ”‚       โ””โ”€โ”€ cnn_mnist_model.keras
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ app/                       # App Router (page.tsx, layout.tsx)
โ”‚   โ”‚   โ”œโ”€โ”€ components/                # UI & Visualization Components
โ”‚   โ”‚   โ”œโ”€โ”€ lib/                       # Inference Engine & Attribution Math
โ”‚   โ”‚   โ””โ”€โ”€ workers/                   # Background Web Worker Thread
โ”‚   โ”œโ”€โ”€ package.json
โ”‚   โ””โ”€โ”€ tsconfig.json
โ”œโ”€โ”€ train_mnist_model.py               # Colab Python Training & JSON Exporter Script
โ”œโ”€โ”€ cnn_mnist_model.keras              # Trained Keras Model Artifact
โ”œโ”€โ”€ conv_weights.json                  # Conv2D Weights Manifest
โ”œโ”€โ”€ batchnorm_params.json              # BatchNorm Parameters Manifest
โ”œโ”€โ”€ dense_weights.json                 # Dense Head Weights Manifest
โ”œโ”€โ”€ model_architecture.json            # Architecture Manifest
โ”œโ”€โ”€ sample_predictions.json            # Test Samples Manifest
โ”œโ”€โ”€ .gitignore
โ””โ”€โ”€ README.md

License

This project is licensed under the MIT License. Educational and personal use welcomed.

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages