Skip to content
svgcnn-filters

CNN filters (first-layer kernels)

What local patterns did the first layer of a convolutional network learn to look for?

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

How to read it

  1. Read each small square as one kernel the first layer learned; the network slides it over every position of the image.
  2. 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.
  3. 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.
  1. Callout 1: One kernel: k × k weights.
  2. Callout 2: Opposite signs side by side: an edge detector.
  3. 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