svgsplit-strip
Validation fold strip
Which rows train, validate and test in each fold — and is anything leaking across time or groups?
How to read it
- Read each row as one fold of the plan, rows binned in order.
- Colours mark training, validation and test.
- Check for leaks: no validation or test bin should come before training in a time-ordered plan.
- Callout 1: The final fit.
- Callout 2: One fold's training rows.
- Callout 3: Test rows are held out of every fold.
Watch out
- A plan that looks tidy can still leak through duplicates, groups or features computed on all rows.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
- Bins come from the host's split plan summary (cs-ml SplitSummary: about 120 bins over row order, or time order when the plan is time-based); each bin is stacked by the share of its rows in each set.
- Time-series plans show validation always to the right of training; a gap appears as an empty band between them.
- The right margin repeats each fold's row counts.
# Validation fold strip — Codesplash Chart Lab (recipe "split-strip")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5) # stripes let the chart surface show through
df = pd.read_csv("split-strip-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["fold"] = pd.Categorical(df["fold"].astype("string"), categories=["Final", "Fold 1", "Fold 2", "Fold 3", "Fold 4"])
_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)))
ROW = "fold"
BIN = "rows in time order (binned)"
TR = "train"
VA = "validation"
TE = "test"
EX = "excluded"
d = df.dropna(subset=[ROW, BIN])
rows = levels_of(d[ROW])
parts = [(TR, PALETTE[0], "train"), (VA, PALETTE[1], "validation"), (TE, PALETTE[2], "test")] + ([(EX, GREY, "excluded")] if EX else [])
fig, ax = plt.subplots(figsize=(9, 0.5 * len(rows) + 1.4))
for r, name in enumerate(rows):
s = d[d[ROW].astype(str) == str(name)].sort_values(BIN)
total = sum(s[c].fillna(0) for c, _, _ in parts).replace(0, np.nan)
bottom = np.full(len(s), len(rows) - 1 - r - 0.4)
for col, colour, label in parts: # each bin's height is split by share
h = (s[col].fillna(0) / total).fillna(0).to_numpy() * 0.8
hatch = SERIES_HATCHES[1] if label == "test" else "" # the held-out test set is hatched, as in the app
ax.bar(s[BIN], h, bottom=bottom, width=1.0, color=colour, hatch=hatch, hatchcolor=HATCH_INK, linewidth=0, label=label if r == 0 else None)
bottom = bottom + h
ax.set_yticks(range(len(rows))[::-1], rows)
ax.set_xlabel(BIN)
ax.legend(fontsize=8, ncol=len(parts), loc="upper center", bbox_to_anchor=(0.5, -0.18))
plt.show()Needs pandas, numpy, matplotlib · reads split-strip-demo.csv · app theme from the optional codesplash helper
# Validation fold strip — Codesplash Chart Lab (recipe "split-strip")
# controls: defaults
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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,0.5)" # stripes let the chart surface show through
df = pd.read_csv("split-strip-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["fold"] = pd.Categorical(df["fold"].astype("string"), categories=["Final", "Fold 1", "Fold 2", "Fold 3", "Fold 4"])
_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)))
ROW = "fold"
BIN = "rows in time order (binned)"
TR = "train"
VA = "validation"
TE = "test"
EX = "excluded"
d = df.dropna(subset=[ROW, BIN])
rows = levels_of(d[ROW])
parts = [(TR, PALETTE[0], "train"), (VA, PALETTE[1], "validation"), (TE, PALETTE[2], "test")] + ([(EX, GREY, "excluded")] if EX else [])
fig = go.Figure()
for r, name in enumerate(rows):
s = d[d[ROW].astype(str) == str(name)].sort_values(BIN)
total = sum(s[c].fillna(0) for c, _, _ in parts).replace(0, np.nan)
bottom = np.full(len(s), len(rows) - 1 - r - 0.4)
for col, colour, label in parts:
h = (s[col].fillna(0) / total).fillna(0).to_numpy() * 0.8
pattern = dict(shape=SERIES_HATCHES[1] if label == "test" else "", fgcolor=HATCH_INK, fillmode="overlay") # the held-out test set is hatched
fig.add_bar(x=s[BIN], y=h, base=bottom, marker=dict(color=colour, line=dict(width=0), pattern=pattern), width=1.0, name=label, showlegend=r == 0, legendgroup=label)
bottom = bottom + h
fig.update_yaxes(tickvals=list(range(len(rows)))[::-1], ticktext=rows)
fig.update_layout(barmode="overlay", bargap=0, xaxis_title=BIN)
fig.show()Needs pandas, numpy, plotly · reads split-strip-demo.csv · app theme from the optional codesplash helper
# Validation fold strip — Codesplash Chart Lab (recipe "split-strip")
# controls: defaults
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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("split-strip-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["fold"]] <- factor(df[["fold"]], levels = c("Final", "Fold 1", "Fold 2", "Fold 3", "Fold 4"))
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)]))
row_col <- "fold"
bin_col <- "rows in time order (binned)"
tr_col <- "train"
va_col <- "validation"
te_col <- "test"
ex_col <- "excluded"
d <- df[!is.na(df[[row_col]]) & !is.na(df[[bin_col]]), ]
rows <- levels_of(d[[row_col]])
cols <- c(train = tr_col, validation = va_col, test = te_col, excluded = if (is.null(ex_col)) NA else ex_col)
cols <- cols[!is.na(cols)]
long <- do.call(rbind, lapply(names(cols), function(k) data.frame(row = as.character(d[[row_col]]), bin = d[[bin_col]], part = k, n = d[[cols[[k]]]])))
long$n[is.na(long$n)] <- 0
long$part <- factor(long$part, levels = rev(names(cols)))
long$row <- factor(long$row, levels = rows)
p <- ggplot(long, aes(bin, n, fill = part)) + geom_col(position = "fill", width = 1) + # each bin split by share
facet_grid(row ~ ., switch = "y") +
# the held-out test set is hatched (texture 2 of cs_textures), as in the app
scale_fill_manual(values = list(train = cs_cat[1], validation = cs_cat[2], test = cs_textures(list(cs_cat[3]), idx = 2)[[1]], excluded = grey_col), breaks = names(cols)) +
labs(x = bin_col, y = NULL, fill = NULL) + theme_cs +
theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(), strip.text.y.left = element_text(angle = 0), panel.spacing = unit(2, "pt"), legend.position = "bottom")
print(p)Needs ggplot2 · reads split-strip-demo.csv · app theme from the optional codesplashr helper