svgthreshold-metrics
Metrics across thresholds
Where should the decision threshold sit, and what does each choice trade off?
How to read it
- Read each curve as one metric as the threshold moves.
- Find the marker: the threshold chosen now.
- Pick the threshold from your error costs, not from where the lines cross.
- Callout 1: The chosen threshold.
- Callout 2: Each metric's value at it.
- Callout 3: Low threshold: high recall, lower precision.
Watch out
- The best threshold on validation data will look a little worse on new data.
Defaults
- Chosen threshold
- 0.5
- The decision threshold to mark on the chart.
- Range -1,000,000 to 1,000,000, step 0.01
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.
- A case is predicted positive when its score is at or above the threshold (scikit-learn's convention).
- The marker is the run's chosen threshold (F-β, Youden or minimum cost, as the evaluation says) — 0.5 when none was chosen.
# Metrics across thresholds — Codesplash Chart Lab (recipe "threshold-metrics")
# controls: marker=0.5
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("threshold-metrics-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["metric"] = pd.Categorical(df["metric"].astype("string"), categories=["precision", "recall", "F1", "specificity"])
_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)))
T = "probability threshold"
V = "value"
M = "metric"
MARKER = 0.5 # the chosen threshold
groups = levels_of(df[M]) if M else [None]
series = []
for name in groups:
d = df if name is None else df[df[M].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values([T], kind="mergesort")))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axvline(MARKER, color=REF, linestyle="--", linewidth=1)
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
many = len(series) > 1 # several metrics: a dash and a marker shape each, as in the app
ax.plot(d[T], d[V], color=col, linewidth=2, linestyle=SERIES_DASHES[i % 8] if many else "-", label=name or V)
at = float(np.interp(MARKER, d[T], d[V])) # value at the chosen threshold
ax.scatter([MARKER], [at], color=col, marker=SERIES_MARKERS[i % 8] if many else "o", zorder=3)
ax.annotate(f"{at:.2f}", (MARKER, at), xytext=(5, 2), textcoords="offset points", fontsize=8, color=col)
ax.set_xlabel(T)
ax.set_ylabel(V)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads threshold-metrics-demo.csv · app theme from the optional codesplash helper
# Metrics across thresholds — Codesplash Chart Lab (recipe "threshold-metrics")
# controls: marker=0.5
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("threshold-metrics-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["metric"] = pd.Categorical(df["metric"].astype("string"), categories=["precision", "recall", "F1", "specificity"])
_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)))
T = "probability threshold"
V = "value"
M = "metric"
MARKER = 0.5
groups = levels_of(df[M]) if M else [None]
series = []
for name in groups:
d = df if name is None else df[df[M].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values([T], kind="mergesort")))
fig = go.Figure()
fig.add_vline(x=MARKER, line=dict(color=REF, dash="dash", width=1))
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
at = float(np.interp(MARKER, d[T], d[V]))
many = len(series) > 1 # several metrics: a dash and a marker shape each, as in the app
fig.add_scatter(x=d[T], y=d[V], mode="lines", name=f"{name or V} ({at:.2f})", line=dict(color=col, width=2, dash=SERIES_DASHES[i % 8] if many else "solid"))
fig.add_scatter(x=[MARKER], y=[at], mode="markers", marker=dict(color=col, size=8, symbol=SERIES_MARKERS[i % 8] if many else "circle"), showlegend=False)
fig.update_layout(xaxis_title=T, yaxis_title=V)
fig.show()Needs pandas, numpy, plotly · reads threshold-metrics-demo.csv · app theme from the optional codesplash helper
# Metrics across thresholds — Codesplash Chart Lab (recipe "threshold-metrics")
# controls: marker=0.5
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("threshold-metrics-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["metric"]] <- factor(df[["metric"]], levels = c("precision", "recall", "F1", "specificity"))
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)]))
t_col <- "probability threshold"
v_col <- "value"
m_col <- "metric"
marker <- 0.5 # the chosen threshold
d <- data.frame(t = df[[t_col]], v = df[[v_col]], m = if (is.null(m_col)) v_col else factor(as.character(df[[m_col]]), levels = levels_of(df[[m_col]])))
d <- d[!is.na(d$t) & !is.na(d$v), ]
d <- d[order(d$m, d$t), ]
at <- do.call(rbind, lapply(split(d, d$m, drop = TRUE), function(s) data.frame(m = s$m[1], t = marker, v = stats::approx(s$t, s$v, xout = marker, rule = 2, ties = mean)$y)))
p <- ggplot(d, aes(t, v, colour = m)) + geom_vline(xintercept = marker, linetype = "dashed", colour = ref_col) +
geom_line(aes(linetype = m), linewidth = 0.9) + geom_point(data = at, aes(shape = m), size = 2.4) + # dash and marker per metric, as in the app
geom_text(data = at, aes(label = sprintf("%.2f", v)), hjust = -0.25, size = 3, show.legend = FALSE) +
scale_colour_manual(values = cs_cat) + scale_linetype_manual(values = cs_linetypes) + scale_shape_manual(values = cs_shapes) +
labs(x = t_col, y = v_col, colour = NULL, linetype = NULL, shape = NULL) + theme_cs
print(p)Needs ggplot2 · reads threshold-metrics-demo.csv · app theme from the optional codesplashr helper