svgvalidation-curve
Validation curve
How does one hyperparameter trade underfitting for overfitting?
How to read it
- Compare training and validation scores across one hyperparameter.
- Where validation peaks: the best trade-off.
- Where the lines part: more complexity only fits noise.
- Callout 1: Validation peaks at this value.
- Callout 2: Training keeps climbing.
- Callout 3: Low values: both low, so the model is too simple.
Watch out
- The peak was chosen on validation data, so its score is optimistic.
Defaults
- Log scale
- Off
- Log x axis (automatic when the values span 100× or more).
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.
- Every value is re-fit on the same folds; bands are mean ± 1 SD across folds. Training scores are each fold's model scored on its own training rows.
# Validation curve — Codesplash Chart Lab (recipe "validation-curve")
# controls: logX=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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("validation-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["set"] = pd.Categorical(df["set"].astype("string"), categories=["Training", "Validation"])
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)))
X = "max depth"
S = "ROC AUC"
K = "set"
LO = "lower"
HI = "upper"
numeric = pd.api.types.is_numeric_dtype(df[X])
settings = levels_of(df[X]) if not numeric else None
fig, ax = plt.subplots(figsize=(7, 4.5))
for i, k in enumerate(levels_of(df[K])):
g = df[df[K].astype(str) == str(k)].dropna(subset=[S]).copy()
g["_x"] = g[X].astype(float) if numeric else g[X].astype(str).map({s: j for j, s in enumerate(settings)})
g, col = g.sort_values("_x"), PALETTE[i % len(PALETTE)]
ax.plot(g["_x"], g[S], marker="o", color=col, label=str(k))
if LO and HI:
ax.fill_between(g["_x"], g[LO], g[HI], color=col, alpha=0.18)
if not numeric:
ax.set_xticks(range(len(settings)), settings)
ax.set_xlabel(X)
ax.set_ylabel(S)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads validation-curve-demo.csv · app theme from the optional codesplash helper
# Validation curve — Codesplash Chart Lab (recipe "validation-curve")
# controls: logX=false
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("validation-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["set"] = pd.Categorical(df["set"].astype("string"), categories=["Training", "Validation"])
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)))
X = "max depth"
S = "ROC AUC"
K = "set"
LO = "lower"
HI = "upper"
fig = go.Figure()
for i, k in enumerate(levels_of(df[K])):
g = df[df[K].astype(str) == str(k)].dropna(subset=[S])
if pd.api.types.is_numeric_dtype(g[X]):
g = g.sort_values(X)
col = PALETTE[i % len(PALETTE)]
err = dict(type="data", array=g[HI] - g[S], arrayminus=g[S] - g[LO]) if LO and HI else None
fig.add_scatter(x=g[X], y=g[S], mode="lines+markers", name=str(k), line=dict(color=col), error_y=err)
fig.update_layout(xaxis_title=X, yaxis_title=S)
fig.show()Needs pandas, numpy, plotly · reads validation-curve-demo.csv · app theme from the optional codesplash helper
# Validation curve — Codesplash Chart Lab (recipe "validation-curve")
# controls: logX=false
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("validation-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["set"]] <- factor(df[["set"]], levels = c("Training", "Validation"))
X <- "max depth"
S <- "ROC AUC"
K <- "set"
LO <- "lower"
HI <- "upper"
d <- data.frame(x = df[[X]], y = df[[S]], set = as.character(df[[K]]))
if (!is.null(LO) && !is.null(HI)) { d$lo <- df[[LO]]; d$hi <- df[[HI]] }
d <- d[is.finite(d$y), ]
p <- ggplot(d, aes(x, y, colour = set, group = set)) +
(if (!is.null(LO) && !is.null(HI)) geom_ribbon(aes(ymin = lo, ymax = hi, fill = set), colour = NA, alpha = 0.18)) +
geom_line() + geom_point() +
scale_colour_manual(values = cs_cat, name = NULL) + scale_fill_manual(values = cs_cat, guide = "none") +
labs(x = X, y = S) + theme_cs
print(p)Needs ggplot2 · reads validation-curve-demo.csv · app theme from the optional codesplashr helper