Skip to content
svgcnn-feature-maps

CNN feature maps

Which parts of an image does each first-layer filter respond to?

Demo data · seed 20261101 · 576 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Start with the outlined panel: the input image as the network sees it.
  2. Read each other panel as the image filtered by one kernel, after the ReLU: bright cells are where that kernel's pattern is found, dark cells where it is absent.
  3. Compare the maps: different kernels pick out different strokes of the same image, which is what the next layer combines.
  1. Callout 1: The input image.
  2. Callout 2: A map: bright where the kernel's pattern is.
  3. Callout 3: Caption: the map's largest activation.

Watch out

  • This is one image; maps of other images, or of other classes, can look quite different.
  • Each map uses its own scale by default, so a faint map can look bright; read its caption or switch to the shared scale.

Defaults

Colour scale
Each map's own
Each: every map runs from 0 to its own peak, to see where it fires. Shared: one scale, to compare how strongly the filters fire.
Also: Shared by all maps
Values in cells
Off
Prints each activation in its cell when the cells are large enough (about 22 px).

Pinned in the code

  • Draws the numbers the network published (kernel weights, activations, out-of-fold counts); the chart computes nothing statistical.
  • The panel named input is the image as the network sees it (divided by the largest training pixel); the others are the first convolution block's outputs after the ReLU, before pooling, at full size.
  • Each map's caption gives its largest activation, so strength is readable without the colour scale.
# CNN feature maps — Codesplash Chart Lab (recipe "cnn-feature-maps")
# controls: scale=each, values=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("cnn-feature-maps-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["panel"] = pd.Categorical(df["panel"].astype("string"), categories=["input", "map 1", "map 2", "map 3", "map 4", "map 5", "map 6", "map 7", "map 8"])

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def levels_of(s):
    """Declared level order (categoricals), else order of first appearance."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [v for v in s.cat.categories if (s == v).any()]
    return list(dict.fromkeys(s.dropna().astype(str)))
PANEL = "panel"
ROW = "row"
COL = "col"
VALUE = "activation"
SHARED, VALUES = False, False  # one colour scale for all panels; print values in small grids
panels = levels_of(df[PANEL])
grids = {}
for name in panels:  # rows and columns count from 1, row 1 at the top
    d = df[df[PANEL].astype(str) == str(name)]
    g = np.full((int(d[ROW].max()), int(d[COL].max())), np.nan)
    g[d[ROW].astype(int) - 1, d[COL].astype(int) - 1] = d[VALUE]
    grids[name] = g
top = max([np.nanmax(g) for n, g in grids.items() if str(n).lower() != "input"] or [1.0]) or 1.0
def limits(name):  # the input keeps its own range; maps run from 0
    g = grids[name]
    if str(name).lower() == "input" or not SHARED:
        return min(0.0, np.nanmin(g)), (np.nanmax(g) or 1.0)
    return 0.0, top
n = len(panels)
per_row = max(1, int(np.ceil(np.sqrt(n * 1.6))))
lines = int(np.ceil(n / per_row))
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
fig, axes = plt.subplots(lines, per_row, figsize=(1.7 * per_row, 1.9 * lines), squeeze=False)
for ax in axes.flat:
    ax.axis("off")
for ax, name in zip(axes.flat, panels):
    g = grids[name]
    lo, hi = limits(name)
    im = ax.imshow(g, cmap=cmap, vmin=lo, vmax=hi)
    if VALUES and g.size <= 49:
        for (i, j), v in np.ndenumerate(g):
            if not np.isnan(v):
                ax.text(j, i, f"{v:.2f}", ha="center", va="center", fontsize=6)
    is_input = str(name).lower() == "input"
    ax.set_title("input" if is_input else f"{name} · max {np.nanmax(g):.2f}", fontsize=8, fontweight="bold" if is_input else "normal")
    if is_input:
        ax.axis("on"); ax.set_xticks([]); ax.set_yticks([])  # the input keeps a full frame
        for side in ax.spines.values():
            side.set_visible(True); side.set_linewidth(1.4)
fig.colorbar(im, ax=axes, shrink=0.6, label=VALUE)
plt.show()

Needs pandas, numpy, matplotlib · reads cnn-feature-maps-demo.csv · app theme from the optional codesplash helper