svglift-gain
Cumulative gain and lift
If we act on the top-scored share of cases, what share of the positives do we reach?
How to read it
- Read the x axis as how much of the list you act on, top-scored first.
- Read the y axis as the share of all positives reached.
- Compare with the diagonal: random targeting.
- Callout 1: Acting on the top 20% reaches this share of the positives.
- Callout 2: Diagonal: random targeting.
- Callout 3: Everything reached, eventually.
Watch out
- It ignores cost. Choose where to stop using the value of a hit and the cost of acting.
Defaults
- Show
- Cumulative gain
- Which view to draw.
- Also: Lift
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.
- Cases are ranked by predicted probability, highest first; gain at x is the share of all positives among the top x of cases (deciles or every case, as the run sends).
- Lift = gain ÷ share targeted; when the run sends no lift column the chart derives it from the two.
- The diagonal (gain) or the line at 1 (lift) is random targeting.
# Cumulative gain and lift — Codesplash Chart Lab (recipe "lift-gain")
# controls: mode=gain
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"]
df = pd.read_csv("lift-gain-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["model"] = pd.Categorical(df["model"].astype("string"), categories=["Gradient boosting", "Random forest"])
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)))
F = "share of customers contacted"
GAIN = "share of churners reached"
LIFT = None
CURVE = "model"
MODE = "gain" # "gain" (share of positives captured) or "lift" (× random)
groups = levels_of(df[CURVE]) if CURVE else [None]
series = []
for name in groups:
d = df if name is None else df[df[CURVE].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[F]).sort_values([F], kind="mergesort")))
fig, ax = plt.subplots(figsize=(7, 4.8))
if MODE == "gain":
ax.plot([0, 1], [0, 1], color="grey", linestyle="--", linewidth=1, label="random")
else:
ax.axhline(1, color="grey", linestyle="--", linewidth=1, label="random")
for i, (name, d) in enumerate(series):
if MODE == "gain":
y = d[GAIN]
else:
d = d[d[F] > 0]
y = d[LIFT] if LIFT else d[GAIN] / d[F]
ax.plot(d[F], y, color=PALETTE[i % len(PALETTE)], linewidth=2, marker="o", ms=3, label=name or GAIN)
ax.set_xlabel(F)
ax.set_ylabel(GAIN if MODE == "gain" else "lift (× random)")
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads lift-gain-demo.csv · app theme from the optional codesplash helper
# Cumulative gain and lift — Codesplash Chart Lab (recipe "lift-gain")
# controls: mode=gain
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
df = pd.read_csv("lift-gain-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["model"] = pd.Categorical(df["model"].astype("string"), categories=["Gradient boosting", "Random forest"])
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)))
F = "share of customers contacted"
GAIN = "share of churners reached"
LIFT = None
CURVE = "model"
MODE = "gain"
groups = levels_of(df[CURVE]) if CURVE else [None]
series = []
for name in groups:
d = df if name is None else df[df[CURVE].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[F]).sort_values([F], kind="mergesort")))
fig = go.Figure()
if MODE == "gain":
fig.add_scatter(x=[0, 1], y=[0, 1], mode="lines", line=dict(color="grey", dash="dash", width=1), name="random")
else:
fig.add_hline(y=1, line=dict(color="grey", dash="dash", width=1))
for i, (name, d) in enumerate(series):
if MODE == "gain":
y = d[GAIN]
else:
d = d[d[F] > 0]
y = d[LIFT] if LIFT else d[GAIN] / d[F]
fig.add_scatter(x=d[F], y=y, mode="lines+markers", name=name or GAIN, line=dict(color=PALETTE[i % len(PALETTE)], width=2), marker=dict(size=5))
fig.update_layout(xaxis_title=F, yaxis_title=GAIN if MODE == "gain" else "lift (× random)")
fig.show()Needs pandas, numpy, plotly · reads lift-gain-demo.csv · app theme from the optional codesplash helper
# Cumulative gain and lift — Codesplash Chart Lab (recipe "lift-gain")
# controls: mode=gain
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))
df <- read.csv("lift-gain-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["model"]] <- factor(df[["model"]], levels = c("Gradient boosting", "Random forest"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
f_col <- "share of customers contacted"
gain_col <- "share of churners reached"
lift_col <- NULL
curve_col <- "model"
mode <- "gain" # "gain" or "lift"
d <- data.frame(f = df[[f_col]], gain = df[[gain_col]], g = if (is.null(curve_col)) "" else factor(as.character(df[[curve_col]]), levels = levels_of(df[[curve_col]])))
d$lift <- if (is.null(lift_col)) ifelse(d$f > 0, d$gain / d$f, NA) else df[[lift_col]]
d <- d[!is.na(d$f), ]
d$y <- if (mode == "gain") d$gain else d$lift
d <- d[!is.na(d$y), ]
p <- ggplot(d[order(d$g, d$f), ], aes(f, y, colour = g)) +
{ if (mode == "gain") geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = "grey60") else geom_hline(yintercept = 1, linetype = "dashed", colour = "grey60") } +
geom_line(linewidth = 0.9) + geom_point(size = 1.2) +
scale_colour_manual(values = cs_cat, guide = if (is.null(curve_col)) "none" else "legend") +
labs(x = f_col, y = if (mode == "gain") gain_col else "lift (× random)", colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads lift-gain-demo.csv · app theme from the optional codesplashr helper