svgtraining-curves
Training curves
Is the network still learning, and when did it start to overfit?
How to read it
- Read each solid line as one network's training loss, epoch by epoch (or NGBoost's training score, round by round).
- Read the dashed line in the same colour as its loss on the held-back validation rows.
- Find the ring: the epoch with the lowest validation loss, whose weights early stopping keeps.
- Callout 1: Steep early fall: the network is learning the main pattern.
- Callout 2: Ring: the kept epoch.
- Callout 3: Dashed line rising while the solid one falls: overfitting.
Watch out
- Training loss is measured with dropout on and validation loss with it off, so a validation curve below the training curve is not a bug.
- A smooth fall on training rows says nothing about new data; read the run's cross-validated metrics.
Defaults
- Loss axis
- Linear
- A log axis spreads out the late epochs, where losses change little.
- Also: Log
- Validation loss
- On
- Show the dashed validation curves and the kept epoch.
Pinned in the code
- Draws the numbers the learner published (training history, member predictions, predicted densities); the chart computes nothing statistical.
- Training loss is the mean over the epoch's mini-batches (with dropout on); validation loss is computed once per epoch on the held-out slice with dropout off, so the two are not on quite the same footing.
- The ring marks the lowest validation loss — the weights early stopping keeps.
# Training curves — Codesplash Chart Lab (recipe "training-curves")
# controls: scale=linear, valid=true
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]
df = pd.read_csv("training-curves-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["network"] = pd.Categorical(df["network"].astype("string"), categories=["member 1", "member 2", "member 3"])
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 = "epoch"
Y = "training log loss"
S = "network"
V = "validation log loss"
SHOW_VALID = True
series = levels_of(df[S]) if S else [None]
fig, ax = plt.subplots(figsize=(7, 4.2))
for i, s in enumerate(series):
d = (df[df[S].astype(str) == s] if S else df).sort_values(X)
colour = PALETTE[i % len(PALETTE)]
many = len(series) > 1 # members share solid/dashed for train/validation, so a marker shape names each (as in the app)
every = max(1, round(len(d) / 8))
ax.plot(d[X], d[Y], color=colour, linewidth=1.6, marker=SERIES_MARKERS[i % 8] if many else None, markevery=((i * every) // len(series), every), markersize=4, label=s if s is not None else Y)
if V and SHOW_VALID:
dv = d.dropna(subset=[V])
if len(dv):
ax.plot(dv[X], dv[V], color=colour, linewidth=1.2, linestyle="--")
best = dv.loc[dv[V].idxmin()] # the epoch early stopping keeps
ax.plot([best[X]], [best[V]], SERIES_MARKERS[i % 8] if many else "o", markerfacecolor="white", markeredgecolor=colour, markersize=6)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.set_title("Training curves (dashed: validation)")
ax.legend(frameon=False, fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads training-curves-demo.csv · app theme from the optional codesplash helper
# Training curves — Codesplash Chart Lab (recipe "training-curves")
# controls: scale=linear, valid=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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
df = pd.read_csv("training-curves-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["network"] = pd.Categorical(df["network"].astype("string"), categories=["member 1", "member 2", "member 3"])
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 = "epoch"
Y = "training log loss"
S = "network"
V = "validation log loss"
SHOW_VALID = True
series = levels_of(df[S]) if S else [None]
fig = go.Figure()
for i, s in enumerate(series):
d = (df[df[S].astype(str) == s] if S else df).sort_values(X)
colour = PALETTE[i % len(PALETTE)]
name = s if s is not None else Y
many = len(series) > 1 # members share solid/dashed for train/validation, so a marker shape names each (as in the app)
every = max(1, round(len(d) / 8))
sizes = [7 if k % every == (i * every) // len(series) else 0 for k in range(len(d))] # about 8 markers per member, staggered
fig.add_trace(go.Scatter(x=d[X], y=d[Y], mode="lines+markers" if many else "lines", name=name, line=dict(color=colour, width=2), marker=dict(symbol=SERIES_MARKERS[i % 8], size=sizes, color=colour)))
if V and SHOW_VALID:
dv = d.dropna(subset=[V])
if len(dv):
fig.add_trace(go.Scatter(x=dv[X], y=dv[V], mode="lines", name=f"{name} (validation)", line=dict(color=colour, width=1.5, dash="dash"), showlegend=False))
best = dv.loc[dv[V].idxmin()]
fig.add_trace(go.Scatter(x=[best[X]], y=[best[V]], mode="markers", marker=dict(color="white", symbol=SERIES_MARKERS[i % 8] if many else "circle", line=dict(color=colour, width=2), size=9), showlegend=False, hovertext="best validation"))
fig.update_layout(title="Training curves (dashed: validation)", xaxis_title=X, yaxis_title=Y)
fig.show()Needs pandas, numpy, plotly · reads training-curves-demo.csv · app theme from the optional codesplash helper
# Training curves — Codesplash Chart Lab (recipe "training-curves")
# controls: scale=linear, valid=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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("training-curves-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["network"]] <- factor(df[["network"]], levels = c("member 1", "member 2", "member 3"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
X <- "epoch"
Y <- "training log loss"
S <- "network"
V <- "validation log loss"
show_valid <- TRUE
d <- data.frame(x = df[[X]], y = df[[Y]], s = if (is.null(S)) factor(Y) else factor(df[[S]], levels = levels_of(df[[S]])))
if (!is.null(V)) d$v <- df[[V]]
d <- d[order(d$s, d$x), ]
p <- ggplot(d, aes(x, y, colour = s)) + geom_line(linewidth = 0.6)
if (nlevels(d$s) > 1) { # members share solid/dashed for train/validation, so a marker shape names each (as in the app)
marks <- do.call(rbind, lapply(split(d, d$s, drop = TRUE), function(g) {
k <- max(1, round(nrow(g) / 8)); off <- ((as.integer(g$s[1]) - 1) * k) %/% nlevels(d$s)
g[(seq_len(nrow(g)) - 1) %% k == off, ] # about 8 markers per member, staggered
}))
p <- p + geom_point(data = marks, aes(shape = s), size = 1.8) + scale_shape_manual(values = cs_shapes, name = NULL)
}
if (!is.null(V) && show_valid) {
dv <- d[!is.na(d$v), ]
best <- do.call(rbind, lapply(split(dv, dv$s, drop = TRUE), function(g) g[which.min(g$v), ])) # the kept epoch
p <- p + geom_line(data = dv, aes(y = v), linetype = "dashed", linewidth = 0.45) +
geom_point(data = best, aes(y = v), shape = 21, fill = "white", size = 2.2, show.legend = FALSE) # the legend keeps each member's marker
}
p <- p + scale_colour_manual(values = rep(cs_cat, length.out = nlevels(d$s))) +
labs(x = X, y = Y, colour = NULL, title = "Training curves (dashed: validation)")
print(p)Needs ggplot2 · reads training-curves-demo.csv · app theme from the optional codesplashr helper