Skip to content
svgcnn-confusion

Confusion matrix (out of fold)

Which classes does the model mix up, and how often is each class recognised?

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

How to read it

  1. Read each row as the rows whose actual class is that label, and each column as what the model predicted for them.
  2. Read the outlined diagonal as correct predictions; the recall on the right is the diagonal's share of its row.
  3. Find the largest numbers off the diagonal: those are the pairs the model mixes up, named under the matrix.
  1. Callout 1: Outlined diagonal: correct predictions.
  2. Callout 2: Off-diagonal count: a mix-up.
  3. Callout 3: Recall per actual class.

Watch out

  • Shading by the share of each actual class hides how many rows a class has; switch to count to see where most rows are.
  • These are out-of-fold predictions on the training data; the locked test set is scored separately in the run's metrics.

Defaults

Shade by
Share of the actual class (recall)
Share of the actual class makes rare classes as visible as common ones; count shows where most of the rows are.
Also: Count
Counts in cells
On
Prints the count in every non-empty cell (and on the diagonal) when the cells are large enough.

Pinned in the code

  • Draws the numbers the network published (kernel weights, activations, out-of-fold counts); the chart computes nothing statistical.
  • Counts pool the out-of-fold predictions of every cross-validation fold (each row is predicted by a model that never saw it); the locked test rows are not included.
  • The predicted class is the most probable one (for two classes, probability ≥ 0.5 for the positive class), as in the run's accuracy.
  • Recall is the diagonal count over its row total; classes keep the target's level order.
# Confusion matrix (out of fold) — Codesplash Chart Lab (recipe "cnn-confusion")
# controls: normalize=row, 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-confusion-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["actual"] = pd.Categorical(df["actual"].astype("string"), categories=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])
df["predicted"] = pd.Categorical(df["predicted"].astype("string"), categories=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])

_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)))
A = "actual"
P = "predicted"
N = "rows"
BY_ROW, VALUES = True, True  # shade by the share of each actual class; print counts
classes = list(dict.fromkeys(levels_of(df[A]) + levels_of(df[P])))
idx = {cl: i for i, cl in enumerate(classes)}
k = len(classes)
M = np.zeros((k, k))  # rows actual, columns predicted
for a, p, n in zip(df[A], df[P], df[N] if N else np.ones(len(df))):
    if pd.notna(a) and pd.notna(p) and pd.notna(n):
        M[idx[str(a)], idx[str(p)]] += n
totals = M.sum(axis=1)
share = np.divide(M, totals[:, None], out=np.zeros_like(M), where=totals[:, None] > 0)
Z = share if BY_ROW else M / max(M.max(), 1)
recall = np.divide(np.diag(M), totals, out=np.full(k, np.nan), where=totals > 0)
ylabels = [f"{cl}  ({r:.0%})" if not np.isnan(r) else cl for cl, r in zip(classes, recall)]
title = f"accuracy {np.trace(M) / max(M.sum(), 1):.1%} of {M.sum():g} (diagonal outlined; recall in brackets)"
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
fig, ax = plt.subplots(figsize=(6.5, 5.6))
ax.imshow(Z, cmap=cmap, vmin=0, vmax=1)
for i in range(k):
    ax.add_patch(plt.Rectangle((i - 0.45, i - 0.45), 0.9, 0.9, fill=False, edgecolor=REF, linewidth=1.4))  # correct predictions
    for j in range(k):
        if VALUES and (M[i, j] > 0 or i == j):
            ax.text(j, i, f"{M[i, j]:g}", ha="center", va="center", fontsize=8, fontweight="bold" if i == j else "normal", color="white" if Z[i, j] > 0.55 else "black")
ax.set_xticks(range(k), classes)
ax.set_yticks(range(k), ylabels)
ax.xaxis.tick_top()
ax.xaxis.set_label_position("top")
ax.set_xlabel("predicted")
ax.set_ylabel("actual (recall)")
ax.set_title(title, fontsize=9, pad=28)
plt.show()

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