svgregret-bands
Cumulative regret
Which bandit policy loses the least reward compared with always playing the best arm?
How to read it
- Read each line as how much reward a policy loses compared with always picking the best arm.
- A curve that flattens has stopped losing: it found the best arm.
- Read the band for replication spread.
- Callout 1: Thompson sampling flattens early.
- Callout 2: A fixed split keeps losing at the same rate.
- Callout 3: Band: the spread across runs.
Watch out
- Lower regret may trade against slower learning: decide what you need the result for.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
- Regret_t = Σ (μ* − μ of the arm played) up to round t; the band spans the replication quantiles the engine sends. Replications share the random stream, so Python and R simulations match.
# Cumulative regret — Codesplash Chart Lab (recipe "regret-bands")
# controls: defaults
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))]
df = pd.read_csv("regret-bands-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
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 = "round"
Y = "cumulative regret"
LO = "p10"
HI = "p90"
G = "policy"
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
d = df if name is None else df[df[G].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
if LO and HI:
ax.fill_between(d[X], d[LO], d[HI], color=col, alpha=0.15, lw=0)
ax.plot(d[X], d[Y], color=col, linewidth=2, label=name or Y, linestyle=SERIES_DASHES[i % 8]) # dash per group, as in the app
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G: ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads regret-bands-demo.csv · app theme from the optional codesplash helper
# Cumulative regret — Codesplash Chart Lab (recipe "regret-bands")
# 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_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"]
df = pd.read_csv("regret-bands-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
X = "round"
Y = "cumulative regret"
LO = "p10"
HI = "p90"
G = "policy"
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
d = df if name is None else df[df[G].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig = go.Figure()
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
shape = "linear"
if LO and HI:
fig.add_scatter(x=d[X], y=d[LO], mode="lines", line=dict(width=0, shape=shape), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[HI], mode="lines", line=dict(width=0, shape=shape), fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[Y], mode="lines", name=name or Y, line=dict(color=col, width=2, shape=shape, dash=SERIES_DASHES[i % 8])) # dash per group, as in the app
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()Needs pandas, numpy, plotly · reads regret-bands-demo.csv · app theme from the optional codesplash helper
# Cumulative regret — Codesplash Chart Lab (recipe "regret-bands")
# 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_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
df <- read.csv("regret-bands-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["policy"]] <- factor(df[["policy"]])
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
x_col <- "round"
y_col <- "cumulative regret"
lo_col <- "p10"
hi_col <- "p90"
g_col <- "policy"
d <- data.frame(x = df[[x_col]], y = df[[y_col]], g = if (is.null(g_col)) "" else factor(as.character(df[[g_col]]), levels = levels_of(df[[g_col]])))
d$lo <- if (is.null(lo_col)) NA_real_ else df[[lo_col]]
d$hi <- if (is.null(hi_col)) NA_real_ else df[[hi_col]]
d <- d[!is.na(d$x) & !is.na(d$y), ]
d <- d[order(d$g, d$x), ]
p <- ggplot(d, aes(x, y, colour = g, fill = g)) +
{ if (!all(is.na(d$lo))) geom_ribbon(aes(ymin = lo, ymax = hi), colour = NA, alpha = 0.15) } + geom_line(aes(linetype = g), linewidth = 0.9) +
scale_colour_manual(values = cs_cat, guide = if (is.null(g_col)) "none" else "legend") + scale_fill_manual(values = cs_cat, guide = "none") +
scale_linetype_manual(values = cs_linetypes, guide = if (is.null(g_col)) "none" else "legend") + # dash per group, as in the app
labs(x = x_col, y = y_col, colour = NULL, linetype = NULL) + theme_cs
print(p)Needs ggplot2 · reads regret-bands-demo.csv · app theme from the optional codesplashr helper