svgcnn-confusion
Confusion matrix (out of fold)
Which classes does the model mix up, and how often is each class recognised?
How to read it
- Read each row as the rows whose actual class is that label, and each column as what the model predicted for them.
- Read the outlined diagonal as correct predictions; the recall on the right is the diagonal's share of its row.
- Find the largest numbers off the diagonal: those are the pairs the model mixes up, named under the matrix.
- Callout 1: Outlined diagonal: correct predictions.
- Callout 2: Off-diagonal count: a mix-up.
- 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
# 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 plotly.express as px
import plotly.graph_objects as go
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-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)"
text = [[f"{v:g}" if (VALUES and (v > 0 or i == j)) else "" for j, v in enumerate(row)] for i, row in enumerate(M)]
fig = go.Figure(go.Heatmap(z=Z, x=classes, y=ylabels, zmin=0, zmax=1, colorscale=[[0, SEQ[0]], [1, SEQ[-1]]],
text=text, texttemplate="%{text}", customdata=M, hovertemplate="actual %{y}<br>predicted %{x}<br>%{customdata:g} rows<extra></extra>",
colorbar=dict(title="row share" if BY_ROW else "rows ÷ max")))
for i in range(k): # outline the diagonal (correct predictions)
fig.add_shape(type="rect", x0=i - 0.45, x1=i + 0.45, y0=i - 0.45, y1=i + 0.45, line=dict(color=REF, width=1.5))
fig.update_yaxes(autorange="reversed", title="actual (recall)", type="category")
fig.update_xaxes(side="top", title="predicted", type="category")
fig.update_layout(title=title)
fig.show()Needs pandas, numpy, plotly · reads cnn-confusion-demo.csv · app theme from the optional codesplash helper
# Confusion matrix (out of fold) — Codesplash Chart Lab (recipe "cnn-confusion")
# controls: normalize=row, 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-confusion-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["actual"]] <- factor(df[["actual"]], levels = c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"))
df[["predicted"]] <- factor(df[["predicted"]], levels = c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"))
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)]))
actual_col <- "actual"
predicted_col <- "predicted"
count_col <- "rows"
by_row <- TRUE; show_values <- TRUE # shade by the share of each actual class; print counts
classes <- unique(c(levels_of(df[[actual_col]]), levels_of(df[[predicted_col]])))
n <- if (is.null(count_col)) rep(1, nrow(df)) else df[[count_col]]
M <- matrix(0, length(classes), length(classes), dimnames = list(classes, classes)) # rows actual, columns predicted
for (i in seq_len(nrow(df))) {
a <- as.character(df[[actual_col]][i]); p <- as.character(df[[predicted_col]][i])
if (!is.na(a) && !is.na(p) && !is.na(n[i])) M[a, p] <- M[a, p] + n[i]
}
totals <- rowSums(M)
recall <- ifelse(totals > 0, diag(M) / totals, NA)
ylab <- ifelse(is.na(recall), classes, sprintf("%s (%.0f%%)", classes, 100 * recall))
d <- expand.grid(i = seq_along(classes), j = seq_along(classes))
d$count <- M[cbind(d$i, d$j)]
d$fill <- if (by_row) ifelse(totals[d$i] > 0, d$count / totals[d$i], 0) else d$count / max(M, 1)
d$actual <- factor(ylab[d$i], levels = rev(ylab))
d$predicted <- factor(classes[d$j], levels = classes)
p <- ggplot(d, aes(predicted, actual, fill = fill)) + geom_tile(colour = "white", linewidth = 0.3) +
geom_tile(data = d[d$i == d$j, ], fill = NA, colour = ref_col, linewidth = 0.7, width = 0.9, height = 0.9) + # correct predictions
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[length(seq_ramp)], limits = c(0, 1), name = if (by_row) "row share" else "rows ÷ max") +
scale_x_discrete(position = "top") + coord_equal() +
labs(x = "predicted", y = "actual (recall)", title = sprintf("accuracy %.1f%% of %g (diagonal outlined)", 100 * sum(diag(M)) / max(sum(M), 1), sum(M))) +
theme_cs + theme(panel.grid = element_blank())
if (show_values) p <- p + geom_text(data = d[d$count > 0 | d$i == d$j, ], aes(label = format(count), colour = fill > 0.55), size = 2.8) +
scale_colour_manual(values = c(`FALSE` = "black", `TRUE` = "white"), guide = "none") # readable on dark cells
print(p)Needs ggplot2 · reads cnn-confusion-demo.csv · app theme from the optional codesplashr helper