Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To visualize CNN feature maps, capture the output tensor from a convolutional layer during a forward pass, select its channels, and display each channel as a two-dimensional image. This tutorial shows how to do that with PyTorch/TorchVision and TensorFlow/Keras, including preprocessing, plotting, and common fixes.

What a feature map shows

A convolution uses learned filters (also called kernels) to transform an input. Each output channel is a two-dimensional activation map: a spatial pattern of the filter’s responses to that input. The full output is the layer’s activation tensor. For a batch of images, its usual layout is (B, C, H, W) in PyTorch and (B, H, W, C) in TensorFlow/Keras. A layer with 64 output channels therefore produces 64 maps for each image.

These are different from the filter weights themselves. They are also different from Grad-CAM, which uses gradients to create a class-specific localization map, and from feature visualization methods that synthesize an input to maximize a neuron or channel. A raw feature-map grid shows channel responses for a particular real input; it does not by itself explain a predicted class.

Choose layers and prepare the input

Start with a few layers rather than every module. Early convolutional blocks retain more spatial detail; middle blocks offer a view of increasingly complex local patterns; final convolutional blocks have larger receptive fields, but their maps can be harder to interpret. A layer before pooling is often more useful for spatial inspection than one after global pooling. Compare pre- and post-ReLU outputs only when you have a reason: post-ReLU maps are nonnegative, while pre-ReLU maps preserve signed responses.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Preprocessing must match what the model expects. Use the correct color order, number of channels, resize policy, numeric range, mean and standard deviation, batch dimension, and device. A mismatch can make a valid model appear inactive or noisy. For pretrained TorchVision weights, use the transforms associated with those weights rather than assuming a universal normalization recipe.

PyTorch: extract intermediate outputs with TorchVision

For a traceable TorchVision model, create_feature_extractor() is a maintainable way to expose selected graph nodes. It traces the model, returns the requested nodes, and can omit downstream computation that is not needed. See the TorchVision feature extraction documentation. Node names are architecture-specific; names such as layer1 are common in ResNet models, not universal.

import torch
from PIL import Image
from torchvision.models import resnet18, ResNet18_Weights
from torchvision.models.feature_extraction import create_feature_extractor

weights = ResNet18_Weights.DEFAULT
model = resnet18(weights=weights).eval()
preprocess = weights.transforms()

# Check the model's actual node names before choosing them.
print(model)

extractor = create_feature_extractor(
    model,
    return_nodes={
        "layer1": "layer1",
        "layer2": "layer2",
        "layer3": "layer3",
    },
)

image = Image.open("example.jpg").convert("RGB")
image_tensor = preprocess(image).unsqueeze(0)

device = next(model.parameters()).device
image_tensor = image_tensor.to(device)

with torch.inference_mode():
    activations = extractor(image_tensor)

for name, tensor in activations.items():
    print(name, tensor.shape)

Inspect the model or traced graph to find valid names. If symbolic tracing fails because of dynamic control flow or an unsupported operation, try forward hooks or expose the desired output in the model’s forward() method. TorchVision’s graph-based approach and alternatives are also discussed in its FX feature-extraction overview.

Plot PyTorch channels in a grid

Each PyTorch channel is indexed as activation[batch, channel, height, width]. The function below accepts a single-image tensor shaped (1, C, H, W) or a channel-first tensor shaped (C, H, W). It plots a bounded number of channels and handles constant maps without dividing by zero.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
import math
import torch
import matplotlib.pyplot as plt

def plot_feature_maps(
    activation,
    max_channels=32,
    cols=8,
    cmap="viridis",
    normalize=True,
    figsize_scale=2.0,
):
    if isinstance(activation, torch.Tensor):
        activation = activation.detach().cpu()

    if activation.ndim == 4:
        if activation.shape[0] != 1:
            raise ValueError("Pass one image at a time or select a batch item first.")
        activation = activation[0]
    if activation.ndim != 3:
        raise ValueError(f"Expected (C,H,W) or (1,C,H,W), got {activation.shape}")

    channels = min(activation.shape[0], max_channels)
    rows = math.ceil(channels / cols)
    fig, axes = plt.subplots(
        rows, cols,
        figsize=(cols * figsize_scale, rows * figsize_scale),
        squeeze=False,
    )
    axes = axes.ravel()

    for channel in range(channels):
        feature_map = activation[channel].float().numpy()
        if normalize:
            low, high = feature_map.min(), feature_map.max()
            if high > low:
                feature_map = (feature_map - low) / (high - low)
            else:
                feature_map = feature_map * 0
        axes[channel].imshow(feature_map, cmap=cmap)
        axes[channel].set_title(f"Channel {channel}")
        axes[channel].axis("off")

    for axis in axes[channels:]:
        axis.axis("off")
    plt.tight_layout()
    plt.show()

For example, plot one extracted layer with plot_feature_maps(activations["layer1"], max_channels=16). Per-channel min–max normalization is for visibility: it makes each channel’s local variation easier to see but removes differences in absolute magnitude between channels. For quantitative comparisons across images or models, use a shared scale or documented limits instead.

Select channels deliberately

Showing the first channels is a convenient starting point, but channel order is not an importance ranking. You can select channels with high mean activation or high spatial variance. These rankings answer different descriptive questions, not which channels matter most to a class.

# activation shape: (1, C, H, W)
per_image = activation[0]

# Channels with the highest spatial mean
mean_scores = per_image.mean(dim=(1, 2))
mean_indices = mean_scores.argsort(descending=True)[:16]
plot_feature_maps(per_image[mean_indices], max_channels=16)

# Channels with the highest spatial variance
variance_scores = per_image.flatten(1).var(dim=1)
variance_indices = variance_scores.argsort(descending=True)[:16]
plot_feature_maps(per_image[variance_indices], max_channels=16)

Mean favors broadly active channels; variance favors channels that change across positions. Neither establishes class relevance. For a class-specific explanation, use a method such as Grad-CAM rather than interpreting activation magnitude as importance.

PyTorch: capture outputs with forward hooks

Hooks are useful for custom modules or quick inspection when graph-based extraction is inconvenient. A forward hook receives the module, its input arguments, and its output; its registration returns a handle that should be removed when finished. PyTorch documents this behavior in the Module API and lists activation visualization among hook use cases in its module notes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
import torch

activations = {}
handles = []

def save_activation(name):
    def hook(module, inputs, output):
        if isinstance(output, torch.Tensor):
            activations[name] = output.detach().cpu()
    return hook

for name, module in model.named_modules():
    if isinstance(module, torch.nn.Conv2d):
        handles.append(module.register_forward_hook(save_activation(name)))

try:
    activations.clear()
    with torch.inference_mode():
        _ = model(image_tensor)
finally:
    for handle in handles:
        handle.remove()
    handles.clear()

for name, tensor in activations.items():
    print(name, tensor.shape)

The example targets Conv2d modules, but the captured output may still be unsuitable for an image grid if a custom module returns a tuple or dictionary, or if the same module runs multiple times. Check the output type and shape before plotting. Some models place the visually useful tensor after a residual addition rather than at an individual convolution.

  • Clear the activation dictionary before each forward pass, and remove handles when done. Notebook cells rerun without cleanup can leave duplicate hooks attached.
  • Detach captured tensors and move them to the CPU to avoid retaining an autograd graph or unnecessarily holding GPU memory.
  • Forward hooks are not always ideal with compiled, distributed, scripted, or wrapped models; wrappers can affect names and execution. For backward hooks or gradients, in-place tensor operations introduce additional restrictions; consult the PyTorch hook documentation.

TensorFlow/Keras: build an intermediate-output model

Keras can return intermediate layer outputs by building a second model with the original input and selected layer outputs. This pattern is shown in the TensorFlow Sequential-model guide. The example selects convolutional layers from a loaded model; replace the preprocessing section with the exact pipeline used in training.

import numpy as np
import tensorflow as tf
from tensorflow import keras

model = keras.models.load_model("model.keras")
conv_layers = [
    layer for layer in model.layers
    if isinstance(layer, keras.layers.Conv2D)
]

if not model.built:
    raise ValueError("Build the model with an input before reading layer outputs.")

activation_model = keras.Model(
    inputs=model.input,
    outputs=[layer.output for layer in conv_layers],
)

image = tf.keras.utils.load_img(
    "example.jpg",
    target_size=(224, 224),
    color_mode="rgb",
)
image_array = tf.keras.utils.img_to_array(image)
image_batch = np.expand_dims(image_array, axis=0)

# Apply the same scaling/normalization used during training here.
activations = activation_model.predict(image_batch, verbose=0)

for layer, activation in zip(conv_layers, activations):
    print(layer.name, activation.shape)

For a Functional or subclassed model, the input and outputs available for an intermediate model depend on how it was built. If model.input or a layer output is unavailable, build/call the model with a representative input first, or define an explicit intermediate-output path in the model. Layer names and output structure are model-specific.

Keras commonly uses channels-last tensors shaped (B, H, W, C), so one feature map is activation[0, :, :, channel], not PyTorch’s activation[0, channel].

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
import matplotlib.pyplot as plt

def plot_keras_feature_maps(activation, max_channels=32, cols=8, cmap="viridis"):
    activation = np.asarray(activation)
    if activation.ndim != 4 or activation.shape[0] != 1:
        raise ValueError(f"Expected one image in (1,H,W,C), got {activation.shape}")

    maps = activation[0]
    channels = min(maps.shape[-1], max_channels)
    rows = int(np.ceil(channels / cols))
    fig, axes = plt.subplots(
        rows, cols, figsize=(cols * 2, rows * 2), squeeze=False
    )
    axes = axes.ravel()

    for channel in range(channels):
        feature_map = maps[:, :, channel]
        low, high = feature_map.min(), feature_map.max()
        if high > low:
            feature_map = (feature_map - low) / (high - low)
        else:
            feature_map = np.zeros_like(feature_map)
        axes[channel].imshow(feature_map, cmap=cmap)
        axes[channel].set_title(f"Channel {channel}")
        axes[channel].axis("off")

    for axis in axes[channels:]:
        axis.axis("off")
    plt.tight_layout()
    plt.show()
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Interpret the maps as diagnostics, not explanations

A common pattern is for early layers to respond to edges, orientation, color contrast, or other simple local structure, while deeper layers represent larger receptive-field patterns that may be more task-specific. Downsampling usually reduces map dimensions. This is a tendency, not a fixed progression: appearance depends on architecture, training, input preparation, activation and normalization layers, and the particular image.

A bright patch means the channel had a high response under the displayed scale. It does not establish that the model classified that region as the target, that the channel has one human-readable meaning, or that the region caused the prediction. A channel may respond to unrelated patterns, and a concept may be spread across several channels. Use several inputs—including correct and incorrect predictions—and inspect activation ranges as well as the plot.

For a spatial explanation tied to a chosen class, use a class-specific technique. The Keras Grad-CAM example illustrates combining final convolutional activations with gradients for a target class. Grad-CAM answers a different question from a grid of raw channel outputs.

Troubleshoot common problems

No graph node found

The requested name does not exist in that model or graph. Print the model, then use its exact module or node names. Names vary by architecture, framework version, and wrapper; do not assume a ResNet name works in another CNN.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

The output is not a two-dimensional map per channel

A dense layer, global-average-pooling layer, or logits output commonly has shape (B, features), not a four-dimensional image tensor. Select a convolutional output before flattening or pooling. Do not reshape an arbitrary vector into a square image.

The plot is blank or nearly constant

Check the input preprocessing and inspect the values before concluding the channel is inactive:

print(activation.min(), activation.max(), activation.mean())

Possible causes include an untrained model, an inactive channel, very small values, a fixed display range that hides variation, or an input unlike the training data. Try per-channel normalization for visual inspection, and verify that the model received the intended image and preprocessing.

Maps look identical

Print each captured module name and output shape. Confirm that the selected module really is a convolutional feature output, clear stored activations before another pass, and check whether a shared module runs more than once. A hook on a reused module may fire repeatedly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Device mismatch or memory pressure

The input and model must be on the same device. The PyTorch example obtains the model’s device with next(model.parameters()).device; if a model has no parameters, choose its device explicitly. For large early-layer tensors, capture fewer layers, process one image, detach outputs, transfer them to CPU, and limit the displayed channel count.

Unexpected channels or sizes

Check the image’s color mode and batch dimension. Convert RGBA images to RGB when the model expects three channels, and supply grayscale images in the channel format used during training. Variable-size inputs may be resized or padded according to the model’s requirements. Detection and segmentation models can return multiple feature tensors, while grouped or depthwise convolutions may have different channel counts than expected; inspect actual shapes rather than assuming a fixed layout.

Choosing an approach

Approach Best suited to Trade-off
create_feature_extractor() Traceable TorchVision graphs with known node names Explicit outputs without persistent hook state; symbolic tracing and correct node names are required.
Forward hooks Custom PyTorch modules and quick inspection Minimal model changes, but handles and captured tensors need deliberate cleanup.
Keras intermediate model TensorFlow/Keras models with accessible layer outputs Clean way to return several outputs, provided the model is built and layers are identifiable.
Grad-CAM Spatial evidence related to a selected class Class-specific gradient method, not a raw feature-map viewer.
TensorBoard or experiment tracking Repeated activation monitoring during training Useful across batches and time, but requires more setup than a one-image inspection.

For reproducible comparisons, record the model and framework versions, input preprocessing, layer names, and display scaling. PyTorch and TorchVision APIs evolve; the cited TorchVision guide documents the 0.20 feature-extraction path, while current hook behavior is documented in the PyTorch Module API. Check the documentation matching your installed releases.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.