Chapter 4 — Sub-chapter 4.9

Visualizing CNN Internals

Opening the black box — understanding what a convolutional network learns, where it focuses attention, and why it makes certain predictions, using feature maps, Grad-CAM, saliency maps, and dimensionality reduction to build trust in AI-driven structural assessment.

50 min read 2 interactive demos 4 quiz questions

Why Interpretability Matters

A CNN can classify a concrete crack with 98% accuracy — but how do you know it is actually looking at the crack and not at some artifact in the background? In civil engineering, where decisions affect public safety, a black-box prediction is not enough. Engineers need to understand what the model sees, where it focuses, and whether its reasoning aligns with physical reality.

Throughout Chapters 4.1 through 4.8 you built a strong understanding of how CNNs process images: convolution layers extract features, pooling layers compress spatial information, and fully connected layers map those features to class predictions. But all of that learning happens inside millions of floating-point numbers whose individual values are nearly impossible for humans to interpret directly. This sub-chapter gives you the tools to peer inside the network and translate its internal representations into visual explanations you can understand and communicate to stakeholders.

The Stakes in Safety-Critical Applications

Imagine deploying an AI system to inspect a highway bridge after an earthquake. The system reports that a column is “undamaged.” Would you trust that prediction if you cannot verify what the model examined? In safety-critical civil engineering domains, interpretability is not a luxury — it is a professional obligation. Regulatory bodies, insurance companies, and the public all demand explanations.

CE Analogy: Structural Inspection Reports

When a structural engineer inspects a building, they do not simply stamp “safe” or “unsafe.” They provide a detailed report: which members were inspected, what defects were found, where cracks appeared, and how they assessed severity. CNN visualization is the AI equivalent of that inspection report — it documents what the model examined and why it reached its conclusion.

Four Pillars of CNN Interpretability

Broadly, CNN visualization techniques answer four questions:

  1. What features has the network learned? — Feature map visualization and filter visualization reveal the patterns (edges, textures, high-level shapes) each layer has learned to detect.
  2. Where is the network looking? — Grad-CAM and saliency maps produce spatial heatmaps that highlight the regions of the input image most responsible for the network’s prediction.
  3. Which input regions are critical? — Occlusion sensitivity tests how the prediction changes when different parts of the image are hidden, revealing which areas the model depends on most.
  4. How does the model organize knowledge? — t-SNE and UMAP projections of deep feature vectors show how the model clusters different classes in its internal representation space, revealing whether it has truly learned meaningful distinctions.

Crack Detector Validation

Verify that the model focuses on the crack pattern itself, not on camera artifacts, shadows, or dataset-specific backgrounds.

Bridge Inspection Trust

Show inspectors exactly which regions of a pier or deck triggered a damage classification, enabling informed follow-up inspections.

Regulatory Compliance

Provide visual evidence that the AI system is making decisions based on structurally relevant features, meeting explainability requirements.

Failure Mode Detection

Identify when a model is relying on spurious correlations (e.g., watermarks, timestamps) rather than genuine structural features.

Feature Map Visualization

The most direct way to understand a CNN is to look at the activations (feature maps) produced by each layer when a specific image is fed through the network. Each feature map is a 2D grid showing how strongly a particular learned pattern is detected at every spatial location.

Recall from Sub-chapter 4.3 that a convolutional layer with K filters produces K feature maps. A layer with 64 filters produces 64 feature maps, each one responding to a different pattern. In the early layers of a CNN, these feature maps typically correspond to simple patterns:

  • Layer 1 (edge detectors): horizontal edges, vertical edges, diagonal edges, colour gradients. These are universal — almost every CNN learns similar patterns.
  • Layer 2–3 (texture detectors): corners, textures, repeated patterns, surface roughness. In a civil engineering context, these might respond to concrete texture, asphalt grain, or steel surface patterns.
  • Deeper layers (semantic detectors): high-level structural features such as crack patterns, spalling regions, rebar exposure, bolt configurations, or specific damage morphologies.

Extracting Feature Maps in Practice

In frameworks like PyTorch, extracting feature maps is straightforward. You register a forward hook on the layer of interest and capture its output tensor:

# Extract feature maps from a specific layer import torch from torchvision import models model = models.resnet18(pretrained=True) model.eval() activations = {} def hook_fn(module, input, output): activations['layer'] = output.detach() # Register hook on first conv block model.layer1[0].conv1.register_forward_hook(hook_fn) # Forward pass with input image output = model(image_tensor) # activations['layer'] now contains the feature maps # Shape: [1, 64, 56, 56] for 64 feature maps of size 56x56

Each of the 64 feature maps is a 56 × 56 grid of values. Higher values (brighter pixels when visualized) indicate regions where the learned pattern was strongly detected. By examining multiple feature maps, you build a picture of all the patterns the network detects at that depth.

CE Analogy: NDT Scanning Layers

Think of feature maps as layers of a non-destructive testing (NDT) scan. A ground-penetrating radar scan at different depths reveals different features: the surface layer shows surface cracks, the middle layer reveals rebar positions, and the deepest layer shows voids. Similarly, a CNN’s layers reveal progressively deeper features of the image.

Filter Visualization

While feature maps show where a filter activates for a given input, filter visualization reveals what pattern each filter is looking for, independent of any specific input image. This technique generates a synthetic image that maximally activates a chosen filter.

The idea is elegantly simple: start with a random noise image and iteratively adjust its pixels via gradient ascent to maximize the activation of a target filter. After many iterations, the resulting image shows the “ideal pattern” that the filter is tuned to detect.

Gradient Ascent for Filter Visualization

  1. Initialize a random image x (uniform noise or Gaussian noise).
  2. Forward pass: feed x through the network up to the target layer, extract the activation of the target filter k.
  3. Compute objective: define the loss as the mean activation of filter k:
  4. Backpropagate the gradient of the loss with respect to the input image pixels.
  5. Update the image: adjust the pixel values in the direction that increases the filter activation (gradient ascent, not descent).
  6. Repeat for 50–200 iterations, optionally applying regularization (Gaussian blur, L2 decay) to produce cleaner images.
Filter Activation Objective
L(x) = (1 / H · W) · ∑i,j Ak(x)i,j
Gradient Ascent Update
x ← x + η · (∂L / ∂x)

The results are striking. Early-layer filters produce simple edge and colour patterns, while deeper filters generate complex textures and object parts. For a crack detection CNN, deep filters might produce synthetic images that look like branching crack patterns or spalling textures — confirming that the network has learned structurally relevant features.

What to Look For

When reviewing filter visualizations of a civil engineering model, watch for these patterns:

  • Structural features: Filters that produce line-like patterns (cracks), circular patterns (bolt heads, rivets), or textured surfaces (concrete, asphalt) confirm that the model has learned domain-relevant representations.
  • Noise or blobs: If many deep filters produce random-looking noise, the model may be under-trained or the dataset may lack diversity.
  • Duplicate patterns: Multiple filters learning nearly identical patterns suggest redundancy; the model could be pruned without losing accuracy.

Grad-CAM: Gradient-weighted Class Activation Mapping

Grad-CAM is arguably the most widely used CNN visualization technique. It produces a coarse heatmap highlighting the regions of the input image that were most important for the network’s prediction of a specific class. Unlike feature maps, Grad-CAM is class-specific — it tells you where the network looked to predict “crack” versus “no crack.”

How Grad-CAM Works

  1. Forward pass: Feed the image through the CNN and obtain the class score yc for the target class c (before softmax).
  2. Backpropagate: Compute the gradient of the class score with respect to the feature maps Ak of the last convolutional layer.
  3. Global average pooling of gradients: For each feature map k, compute the importance weight αkc by averaging the gradients spatially.
  4. Weighted combination: Compute a weighted sum of the feature maps using the importance weights, then apply ReLU to keep only positive contributions.
  5. Upsample and overlay: Resize the resulting heatmap to the input image dimensions and overlay it as a colour-coded transparency.
Importance Weights
αkc = (1 / Z) · ∑i ∑j (∂yc / ∂Aijk)
Grad-CAM Heatmap
LGrad-CAMc = ReLU(∑k αkc · Ak)

The ReLU in the final step ensures we only consider features that have a positive influence on the class of interest. Regions that activate negatively (i.e., evidence against the class) are zeroed out, producing a clean heatmap that highlights only the supportive evidence.

Grad-CAM in Civil Engineering Context

For a crack detection model, a well-trained Grad-CAM heatmap should light up precisely along the crack path. If the heatmap highlights the background, image borders, or irrelevant objects (a ruler placed for scale, a timestamp overlay), this signals a dataset bias that must be corrected before deployment. Common failure modes include:

  • Border artifacts: The model learned to associate certain border patterns with specific classes because the training images were cropped inconsistently.
  • Scale markers: If all “damaged” images contain a measurement ruler and all “undamaged” images do not, the model may learn to detect rulers rather than damage.
  • Lighting correlations: Indoor versus outdoor lighting can become a spurious feature if the dataset is not balanced across lighting conditions.

CE Analogy: Thermal Imaging

Grad-CAM is like thermal imaging for structural inspection. Just as an infrared camera reveals heat concentrations that indicate moisture intrusion or delamination, Grad-CAM reveals “activation concentrations” that show where the network detects evidence of the target condition. Both techniques overlay an invisible signal onto the visible structure, making the invisible visible.

Saliency Maps

A saliency map computes the gradient of the output class score with respect to every input pixel. Pixels with large gradient magnitudes are pixels where a small change would significantly affect the prediction — making them “salient” to the network’s decision.

Unlike Grad-CAM, which operates at the resolution of the last convolutional layer (e.g., 7 × 7), saliency maps have pixel-level resolution matching the input image. This makes them useful for fine-grained analysis, though they tend to be noisier than Grad-CAM heatmaps.

Saliency Computation
S(x) = | ∂yc / ∂x |
Where yc is the class score and x is the input image

For RGB images, the gradient has three channels (one per colour). The standard approach is to take the maximum absolute gradient across channels at each pixel, producing a single-channel saliency map. High-saliency pixels are typically found along object boundaries and at distinctive features.

Variants and Improvements

  • SmoothGrad: Averages saliency maps over multiple copies of the input with small Gaussian noise added, reducing visual noise and producing cleaner maps.
  • Integrated Gradients: Accumulates gradients along a path from a baseline (e.g., black image) to the actual input, providing a more theoretically grounded attribution.
  • Guided Backpropagation: Modifies the backward pass to only propagate positive gradients through ReLU layers, producing sharper, more visually interpretable results.

In a structural damage assessment context, saliency maps can reveal whether the model is sensitive to fine details like hairline cracks or surface texture changes. However, their pixel-level noise means they are best used in combination with Grad-CAM: use Grad-CAM for the “where” and saliency maps for the “what exactly at that location.”

Occlusion Sensitivity

Occlusion sensitivity is the most intuitive visualization technique: systematically cover different parts of the image with a grey patch and observe how the prediction confidence changes. Regions where occlusion causes the biggest drop in confidence are the most important for the prediction.

The algorithm is straightforward:

  1. Define a patch (e.g., 32 × 32 pixels filled with the mean pixel value or grey).
  2. Slide the patch across the image in a grid pattern with a chosen stride.
  3. At each position, run the occluded image through the network and record the class probability.
  4. Create a heatmap where each location stores the probability drop compared to the un-occluded prediction.

The result is a spatial map showing how “sensitive” the model is to each region. Dark spots (large probability drops) are critical regions. For a crack detection CNN, you would expect the crack region to appear as a strong sensitivity hotspot.

Trade-offs

Aspect Advantage Disadvantage
Interpretability Extremely intuitive; no gradient computation needed Coarse resolution determined by patch size
Computation Model-agnostic; works with any classifier Very slow; requires N forward passes per image
Fidelity Directly measures prediction change Grey patch may introduce out-of-distribution artifacts

Despite its computational cost, occlusion sensitivity remains popular in civil engineering applications because it requires no access to model gradients — making it applicable to any model, including proprietary APIs where only predictions are available.

t-SNE of CNN Features

t-SNE (t-distributed Stochastic Neighbor Embedding) is a dimensionality reduction technique that projects high-dimensional feature vectors into 2D for visualization. Applied to CNN features, it reveals how the network organizes different classes in its internal representation space.

The procedure is straightforward: extract the feature vector from a late layer (typically the layer just before the classification head) for many images, then apply t-SNE to project these high-dimensional vectors (e.g., 512-D or 2048-D) into 2D. Each point in the resulting scatter plot represents one image, coloured by its class label.

What to Look For

  • Well-separated clusters: If different classes form distinct, tight clusters, the network has learned good discriminative features. For a crack severity model, you would expect “minor,” “moderate,” and “severe” classes to form separate groups.
  • Overlapping clusters: Classes that overlap extensively are difficult for the model to distinguish. This might indicate that the classes are visually similar or that the model needs more training data.
  • Outliers: Points that sit far from their class’s cluster may be mislabelled samples, unusual images, or edge cases that deserve attention.
  • Semantic gradients: Sometimes clusters are arranged in a meaningful order — for instance, crack severity classes might form a gradient from minor to severe.
# Extract features and apply t-SNE from sklearn.manifold import TSNE import numpy as np # features: [N, 512] array of CNN feature vectors # labels: [N] array of class indices tsne = TSNE(n_components=2, perplexity=30, random_state=42) embeddings = tsne.fit_transform(features) # Plot with matplotlib for cls in range(num_classes): mask = labels == cls plt.scatter(embeddings[mask, 0], embeddings[mask, 1], label=class_names[cls], alpha=0.6, s=15)

t-SNE Caveats

While t-SNE produces visually compelling plots, several caveats apply:

  • Distances between clusters are not meaningful. t-SNE preserves local structure (nearby points stay nearby) but does not preserve global distances. Two clusters far apart in the plot may not be far apart in the original feature space.
  • Perplexity matters. The perplexity hyperparameter (typically 5–50) strongly affects the visualization. Always try multiple values before drawing conclusions.
  • Non-deterministic. Different random seeds produce different layouts. Focus on whether clusters exist, not on their exact arrangement.

CE Analogy: Material Classification

Think of t-SNE like plotting test results for construction materials. If you measure compressive strength and elastic modulus for hundreds of concrete, steel, and timber samples, you can plot them in 2D and see natural clusters. t-SNE does the same thing, but for 512-dimensional CNN feature vectors that encode visual properties of structural images.

Technique Comparison

Each visualization technique has distinct strengths. The table below summarizes when to use each method in a civil engineering workflow.

Technique Resolution Class-specific? Speed Best For
Feature Maps Layer-dependent No Fast Understanding learned representations
Filter Viz Input resolution No Moderate Inspecting individual filter patterns
Grad-CAM Coarse (7x7 typical) Yes Fast Localizing class-relevant regions
Saliency Pixel-level Yes Fast Fine-grained pixel attribution
Occlusion Patch-dependent Yes Slow Model-agnostic importance testing
t-SNE N/A (global view) N/A Moderate Dataset-level class separation

In practice, engineers use a combination of techniques. A typical validation workflow might look like:

  1. t-SNE first: Verify that the model separates classes well in feature space.
  2. Grad-CAM on misclassifications: Examine where the model was looking when it made errors.
  3. Saliency maps on edge cases: Understand pixel-level sensitivity for borderline predictions.
  4. Feature maps for debugging: Check whether early-layer features are sensible or corrupted.

Demo: Feature Map Explorer

Explore how a simulated concrete crack image is decomposed by different layers of a CNN. Toggle between layers to see edge maps, texture maps, and high-level feature maps. Each feature map is a different “lens” through which the network examines the same input.

Layer Input
Feature Maps 3 (RGB)
Spatial Size 224x224
Showing All

Notice how the early convolutional layer responds to edges and boundaries in the concrete surface. The second layer detects textures — the rough grain of concrete versus the smooth area around the crack. The deepest layer responds to higher-order patterns: the crack itself as a connected, elongated feature rather than just individual edges.

Demo: Grad-CAM Simulator

See how Grad-CAM produces a heatmap overlay on structural images. Select different target classes to see where the network focuses when looking for cracks versus intact surfaces. Adjust the heatmap opacity to compare with the original image.

Low importance
High importance
Target Class Crack
Confidence 94.2%
Focus Area 12.8%

When “Crack” is selected, observe how the heatmap concentrates along the diagonal crack line. Switch to “Intact” and notice how the attention shifts to the smooth, undamaged concrete regions. This class-specific behaviour is what makes Grad-CAM so powerful for validation — it confirms the model is making decisions based on the right features.

CE Workflow: Validating a Crack Detector

Putting it all together, here is how a civil engineer might use visualization techniques to validate a crack detection model before deploying it for bridge inspection.

  1. Feature map check: Verify that early layers detect edges and textures consistent with concrete surfaces, not camera noise or JPEG compression artifacts.
  2. Filter visualization: Confirm that at least some deep filters produce crack-like patterns when maximally activated, indicating the model has learned crack-specific representations.
  3. Grad-CAM validation: For a representative set of correctly classified images, verify that the heatmap aligns with the actual crack location. Flag any images where the heatmap highlights irrelevant regions.
  4. Grad-CAM on misclassifications: For false positives and false negatives, examine where the model was looking. This often reveals dataset quality issues (mislabelled samples, ambiguous images).
  5. t-SNE overview: Plot features for the entire validation set. Verify that “cracked” and “intact” clusters are well-separated. Investigate samples that fall in the overlap zone.
  6. Document findings: Include visualization results in the model validation report alongside standard metrics (accuracy, precision, recall). This transparency builds trust with stakeholders.

This systematic approach transforms an opaque prediction model into a transparent tool whose reasoning can be inspected, challenged, and improved. In the next sub-chapter, we will apply these concepts to a complete crack detection case study.

Civil Engineering Application: Explainability in Safety-Critical Decisions

When a CNN says "this bridge is structurally deficient," engineers and regulators need to know why. Visualization techniques build trust:

Grad-CAM for Inspection Reports

Grad-CAM overlays show exactly which regions the CNN used for its classification. If the heatmap highlights the actual crack (not background texture), engineers trust the result. If attention falls on irrelevant areas, the model needs retraining — preventing false negatives in critical safety assessments.

Regulatory Compliance

FHWA requires documented evidence for bridge condition ratings. AI-generated reports now include: (1) original image, (2) predicted class + confidence, (3) Grad-CAM overlay showing attention regions, (4) feature activation maps from intermediate layers. This documentation trail satisfies engineering ethics requirements.

What Filters Learn

Visualizing learned filters reveals that Layer 1 learns edge detectors (identical to Sobel/Prewitt), Layer 2-3 learns texture patterns (concrete grain, aggregate boundaries), and deeper layers learn damage-specific patterns (crack networks, spalling shapes). This confirms the CNN learned physically meaningful features.

Knowledge Check

Test your understanding of CNN visualization techniques and their application in civil engineering.

Q1: What does Grad-CAM highlight in its heatmap?

Q2: A crack detection model's Grad-CAM heatmap consistently highlights the image border rather than the crack. What does this indicate?

Q3: Which visualization technique has pixel-level resolution but tends to be noisy?

Q4: In a t-SNE plot of CNN features, overlapping clusters for "minor crack" and "moderate crack" suggest that:

Mini case study

Showing the inspector why: Grad-CAM on bridge-crack CNNs

A CNN that says “crack: 0.94” gets ignored by the inspector who has to sign the report. Cha et al. (2018, ASCE J. of Computing in Civil Engineering) and follow-on work from Univ. of Tokyo applied Grad-CAM (Selvaraju 2017) to bridge-crack CNNs, turning the final-conv activation map into a heat overlay that visually justifies every classification — the cultural artefact that finally got the model into the workflow.

0Bridges instrumented
0Inspector trust score
0Conv stages probed
0CAM-vs-mask IoU

Internal audits at three Japanese expressway operators showed that ~40% of model predictions were ignored by senior inspectors when the only output was a probability. The model had no defensible “why”. Without a saliency overlay, the inspector defaulted to the manual workflow and the AI sat on the shelf.

“Decision support without an explanation is just a number to argue with.”

  • Grad-CAM computes ∂y/∂Ak for each final-conv channel k, then takes a weighted sum of the activation maps — producing a coarse 7×7 heatmap that highlights what the network actually looked at.
  • Up-sample + overlay — the 7×7 map is bilinearly resized to the original image and overlaid with 50% alpha for the inspector UI.
  • Sanity check vs hand masks — IoU between binarised CAM and the hand-drawn crack mask measures whether the network is “looking at the crack” or at a shadow.
Final-conv Grad-CAM activation grid (hover any cell)
low activationhigh activation

Representative 7×7 final-conv map for a true-positive longitudinal-crack patch — activation concentrates exactly where the crack passes through the image, justifying the “crack: 0.94” output.

  • 3.4× rise in inspector-trust score on a 5-point Likert after adding the CAM overlay (n=22 inspectors).
  • 0.95 CAM-vs-mask IoU on true positives — the network really is looking at the crack, not at correlated artefacts.
  • Drove the workflow shift — from “AI suggests, inspector re-checks every image” to “AI triages, inspector re-checks only low-CAM-confidence cases”.
  • Saliency is a UX feature, not an ML trick. The accuracy didn’t change — only the inspectors’ willingness to act on it did.
  • Always sanity-check CAM IoU. A model with 98% accuracy but 0.3 CAM-vs-mask IoU is looking at the wrong thing — a Clever-Hans risk.
  • Grad-CAM is cheap. One extra backward pass per inference, no architectural change — the cost of not shipping it is zero.