svgcnn-filters
CNN filters (first-layer kernels)
What local patterns did the first layer of a convolutional network learn to look for?
How to read it
- Read each small square as one kernel the first layer learned; the network slides it over every position of the image.
- Read the two ends of the colour scale as weights of opposite sign: a kernel lights up where the image looks like its positive cells and not its negative ones.
- Look for structure: a band of one sign beside a band of the other is an edge detector, a single strong centre is a spot detector, an even patch is a blur.
- Callout 1: One kernel: k × k weights.
- Callout 2: Opposite signs side by side: an edge detector.
- Callout 3: Colour scale centred on 0.
Watch out
- Kernels act on scaled pixels after training from random weights; a noisy-looking kernel can still be useful in combination with the others.
- With each filter on its own scale, a nearly-zero kernel looks as strong as a real one; switch to the shared scale to compare them.
Defaults
- Colour scale
- Shared by all filters
- Shared: one scale, so a pale filter really has small weights. Each: every filter uses its full range, to see weak patterns.
- Also: Each filter's own
- Weights in cells
- On
- Prints each weight 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.
- Rows and columns are the kernel's positions as torch stores them (row 1 at the top); the weights act on the image after it is divided by its largest training pixel.
- The diverging scale is centred on 0; with a shared scale its ends are ± the largest absolute weight of any filter.
# CNN filters (first-layer kernels) — Codesplash Chart Lab (recipe "cnn-filters")
# controls: scale=shared, values=true
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-filters-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=["filter 1", "filter 2", "filter 3", "filter 4", "filter 5", "filter 6", "filter 7", "filter 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 = "weight"
SHARED, VALUES = True, True # 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(np.abs(g)) for g in grids.values()) or 1.0 # ± the largest weight of any filter
def limits(name):
lim = top if SHARED else (np.nanmax(np.abs(grids[name])) or 1.0)
return -lim, lim
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("div", DIV)
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)
ax.set_title(str(name), fontsize=8)
fig.colorbar(im, ax=axes, shrink=0.6, label=VALUE)
plt.show()Needs pandas, numpy, matplotlib · reads cnn-filters-demo.csv · app theme from the optional codesplash helper
# CNN filters (first-layer kernels) — Codesplash Chart Lab (recipe "cnn-filters")
# controls: scale=shared, values=true
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-filters-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=["filter 1", "filter 2", "filter 3", "filter 4", "filter 5", "filter 6", "filter 7", "filter 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 = "weight"
SHARED, VALUES = True, True # 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(np.abs(g)) for g in grids.values()) or 1.0 # ± the largest weight of any filter
def limits(name):
lim = top if SHARED else (np.nanmax(np.abs(grids[name])) or 1.0)
return -lim, lim
n = len(panels)
per_row = max(1, int(np.ceil(np.sqrt(n * 1.6))))
lines = int(np.ceil(n / per_row))
scale = [[0, DIV[0]], [0.5, DIV[1]], [1, DIV[2]]]
titles = [str(p) 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-filters-demo.csv · app theme from the optional codesplash helper
# CNN filters (first-layer kernels) — Codesplash Chart Lab (recipe "cnn-filters")
# controls: scale=shared, values=true
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-filters-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("filter 1", "filter 2", "filter 3", "filter 4", "filter 5", "filter 6", "filter 7", "filter 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 <- "weight"
shared <- TRUE; show_values <- TRUE # 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]])
top <- max(abs(d$v), na.rm = TRUE) # ± the largest weight of any filter
d$fill <- if (shared) d$v / top else ave(d$v, d$panel, FUN = function(x) x / max(abs(x), na.rm = TRUE))
p <- ggplot(d, aes(c, r, fill = fill)) + geom_tile(colour = "white", linewidth = 0.2) +
scale_fill_gradient2(low = div_ramp[1], mid = div_ramp[2], high = div_ramp[3], midpoint = 0, limits = c(-1, 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")
print(p)Needs ggplot2 · reads cnn-filters-demo.csv · app theme from the optional codesplashr helper