Skip to content
svgthreshold-metrics

Metrics across thresholds

Where should the decision threshold sit, and what does each choice trade off?

Demo data · seed 20261101 · 196 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read each curve as one metric as the threshold moves.
  2. Find the marker: the threshold chosen now.
  3. Pick the threshold from your error costs, not from where the lines cross.
  1. Callout 1: The chosen threshold.
  2. Callout 2: Each metric's value at it.
  3. 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