Start with the outlined panel: the input image as the network sees it.
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.
Compare the maps: different kernels pick out different strokes of the same image, which is what the next layer combines.
1Callout 1: The input image.
2Callout 2: A map: bright where the kernel's pattern is.
3Callout 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
# CNN feature maps — Codesplash Chart Lab (recipe "cnn-feature-maps")# controls: scale=each, values=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
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 px.colors.qualitative.Plotly
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))
scale = [[0, SEQ[0]], [1, SEQ[-1]]]
titles = ["<b>input</b>" if str(p).lower() == "input" else f"{p} · max {np.nanmax(grids[p]):.2f}" for p in panels]
fig = make_subplots(rows=lines, cols=per_row, subplot_titles=titles, horizontal_spacing=0.03, vertical_spacing=0.1)
for i, name in enumerate(panels):
g = grids[name]
lo, hi = limits(name)
show = VALUES and g.size <= 49
fig.add_heatmap(z=g, zmin=lo, zmax=hi, colorscale=scale, showscale=i == 0, colorbar=dict(title=VALUE),
text=np.round(g, 2) if show else None, texttemplate="%{text}" if show else None,
row=i // per_row + 1, col=i % per_row + 1)
fig.update_yaxes(autorange="reversed", showticklabels=False, scaleanchor="x")
fig.update_xaxes(showticklabels=False)
fig.show()
Needs pandas, numpy, plotly · reads cnn-feature-maps-demo.csv · app theme from the optional codesplash helper
# CNN feature maps — Codesplash Chart Lab (recipe "cnn-feature-maps")# controls: scale=each, values=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("cnn-feature-maps-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["panel"]] <- factor(df[["panel"]], levels = c("input", "map 1", "map 2", "map 3", "map 4", "map 5", "map 6", "map 7", "map 8"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
panel_col <- "panel"
row_col <- "row"
col_col <- "col"
value_col <- "activation"
shared <- FALSE; show_values <- FALSE # one colour scale for all panels; values in small grids
d <- data.frame(panel = factor(as.character(df[[panel_col]]), levels = levels_of(df[[panel_col]])),
r = df[[row_col]], c = df[[col_col]], v = df[[value_col]])
is_input <- tolower(as.character(d$panel)) == "input"
top <- max(d$v[!is_input], na.rm = TRUE)
d$fill <- ave(d$v, d$panel, FUN = function(x) (x - min(0, x, na.rm = TRUE)) / max(x, na.rm = TRUE)) # each panel 0 → its peak
if (shared) d$fill[!is_input] <- d$v[!is_input] / top
p <- ggplot(d, aes(c, r, fill = fill)) + geom_tile(colour = "white", linewidth = 0.2) +
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[length(seq_ramp)], limits = c(0, 1), name = paste(value_col, "(÷ max)")) +
scale_y_reverse() + coord_equal() + facet_wrap(~panel) +
labs(x = NULL, y = NULL) + theme_cs + theme(axis.text = element_blank(), panel.grid = element_blank())
if (show_values && max(d$r) * max(d$c) <= 49) p <- p + geom_text(aes(label = sprintf("%.2f", v), colour = abs(fill) > 0.55), size = 2) + scale_colour_manual(values = c(`FALSE` = "black", `TRUE` = "white"), guide = "none")
p <- p + geom_rect(data = unique(d[is_input, "panel", drop = FALSE]), aes(xmin = 0.5, xmax = max(d$c) + 0.5, ymin = 0.5, ymax = max(d$r) + 0.5), inherit.aes = FALSE, fill = NA, colour = ref_col, linewidth = 0.8) # the input image
print(p)
Needs ggplot2 · reads cnn-feature-maps-demo.csv · app theme from the optional codesplashr helper