svgtraining-components
Training loss and its parts
Is the network still learning, and which part of its loss moves?
How to read it
- Read each line as one part of the network's loss, averaged over an epoch's rows.
- Falling lines that level off mean training has settled; a line still falling at the right edge means more epochs could help.
- For a VAE, watch the KL line: near zero means the latent space carries no information. For a GAN, watch the Wasserstein estimate fall and flatten.
- Callout 1: Early epochs: the loss drops fast.
- Callout 2: Late epochs: the lines level off.
- Callout 3: A smaller part, such as the KL term.
Watch out
- A low training loss doesn't mean good output: judge generators by the synthetic-data scorecard and maps by trustworthiness.
- GAN losses aren't comparable across runs or with other models; only the trend within one run means anything.
Defaults
- Y axis
- Linear
- A log axis spreads out small late changes; it falls back to linear when any value is zero or negative.
- Also: Log
- Smoothing
- None
- Centered moving average over this many epochs; GAN losses are noisy, so smoothing shows the trend.
- Also: 5 epochs · 11 epochs · 21 epochs
Pinned in the code
- Draws the engine's numbers as given (codesplash ↔ codesplashr torch twins); the chart computes nothing statistical.
- Each value is the row-weighted mean over the epoch's batches (the GAN's critic values average its critic steps).
- Smoothing is a centered moving average that shrinks at the ends; the table shows the unsmoothed values.
# Training loss and its parts — Codesplash Chart Lab (recipe "training-components")
# controls: scale=linear, smooth=1
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_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]
df = pd.read_csv("training-components-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["part"] = pd.Categorical(df["part"].astype("string"), categories=["total", "reconstruction", "KL"])
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"
V = "loss per row"
C = "part"
SMOOTH, LOG = 1, False # centered moving average (1 = none); log y axis
d = df.dropna(subset=[X, V])
fig, ax = plt.subplots(figsize=(8, 4))
parts = levels_of(d[C])
many = len(parts) > 1 # several components: a dash each (and a marker shape when the points are few), as in the app
for i, name in enumerate(parts):
s = d[d[C].astype(str) == name].sort_values(X)
y = s[V].rolling(SMOOTH, center=True, min_periods=1).mean() if SMOOTH > 1 else s[V]
ax.plot(s[X], y, label=name, linewidth=1.6, linestyle=SERIES_DASHES[i % 8] if many else "-",
marker=(SERIES_MARKERS[i % 8] if many else "o") if len(s) <= 60 else None, markersize=3)
if LOG and (d[V] > 0).all():
ax.set_yscale("log")
elif d[V].min() < 0 < d[V].max():
ax.axhline(0, color="grey", linestyle=":", linewidth=1)
ax.set_xlabel(X)
ax.set_ylabel(V)
ax.legend(frameon=False)
plt.show()Needs pandas, numpy, matplotlib · reads training-components-demo.csv · app theme from the optional codesplash helper
# Training loss and its parts — Codesplash Chart Lab (recipe "training-components")
# controls: scale=linear, smooth=1
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_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
df = pd.read_csv("training-components-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["part"] = pd.Categorical(df["part"].astype("string"), categories=["total", "reconstruction", "KL"])
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"
V = "loss per row"
C = "part"
SMOOTH, LOG = 1, False # centered moving average (1 = none); log y axis
d = df.dropna(subset=[X, V])
fig = go.Figure()
parts = levels_of(d[C])
many = len(parts) > 1 # several components: a dash each (and a marker shape when the points are few), as in the app
for i, name in enumerate(parts):
s = d[d[C].astype(str) == name].sort_values(X)
y = s[V].rolling(SMOOTH, center=True, min_periods=1).mean() if SMOOTH > 1 else s[V]
fig.add_trace(go.Scatter(x=s[X], y=y, mode="lines+markers" if len(s) <= 60 else "lines", name=name,
line_dash=SERIES_DASHES[i % 8] if many else "solid", marker_symbol=SERIES_MARKERS[i % 8] if many else "circle"))
fig.update_layout(xaxis_title=X, yaxis_title=V, template="plotly_white")
if LOG and (d[V] > 0).all():
fig.update_yaxes(type="log")
fig.show()Needs pandas, numpy, plotly · reads training-components-demo.csv · app theme from the optional codesplash helper
# Training loss and its parts — Codesplash Chart Lab (recipe "training-components")
# controls: scale=linear, smooth=1
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_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("training-components-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["part"]] <- factor(df[["part"]], levels = c("total", "reconstruction", "KL"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
X <- "epoch"
V <- "loss per row"
C <- "part"
SMOOTH <- 1; LOG <- FALSE # centered moving average (1 = none); log y axis
d <- df[!is.na(df[[X]]) & !is.na(df[[V]]), ]
d$part <- factor(as.character(d[[C]]), levels = levels_of(d[[C]]))
d <- d[order(d$part, d[[X]]), ]
ma <- function(y, w) { h <- w %/% 2; vapply(seq_along(y), function(i) mean(y[max(1, i - h):min(length(y), i + h)]), numeric(1)) }
d$y <- if (SMOOTH > 1) ave(d[[V]], d$part, FUN = function(y) ma(y, SMOOTH)) else d[[V]]
# several components: a dash each (and a marker shape when the points are few), as in the app
p <- ggplot(d, aes(x = .data[[X]], y = y, colour = part, linetype = part)) + geom_line(linewidth = 0.7) +
{ if (any(table(d$part) <= 60)) geom_point(data = d[ave(d$y, d$part, FUN = length) <= 60, ], aes(shape = part), size = 1.4) } +
scale_linetype_manual(values = cs_linetypes) + scale_shape_manual(values = cs_shapes) +
labs(x = X, y = V, colour = NULL, linetype = NULL, shape = NULL) + theme_minimal()
if (LOG && all(d[[V]] > 0)) p <- p + scale_y_log10() else if (min(d[[V]]) < 0 && max(d[[V]]) > 0) p <- p + geom_hline(yintercept = 0, linetype = "dotted", colour = "grey50")
print(p)Needs ggplot2 · reads training-components-demo.csv · app theme from the optional codesplashr helper