Lift Chart and Cumulative Gains Chart in Python

Draw cumulative gains, lift, and decile lift charts in Python with NumPy, pandas, and Matplotlib, then use them to decide how many customers to contact.

To make a cumulative gains chart in Python, sort the test rows by predicted score, take a running total of the positives with np.cumsum, and plot the share of positives reached against the share of rows. Divide the first share into the second to get lift: lift = gains / contacted. scikit-learn 1.9 has no built-in lift or gains display, but the calculation is a few lines of NumPy.

Quick Example

A marketing team wants to know which customers are likely to respond to an offer. This example makes up 20,000 customers, fits a logistic regression on half of them, and draws both charts for the other half.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.ticker import PercentFormatter
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(31)
n = 20_000
X = pd.DataFrame({
    "tenure_months": rng.integers(1, 72, n),
    "orders_last_year": rng.poisson(3, n),
    "days_since_order": rng.exponential(60, n).round(),
    "email_open_rate": rng.beta(2, 5, n),
})
logit = (-3.9 + 0.35 * X.orders_last_year - 0.018 * X.days_since_order
         + 3.5 * X.email_open_rate + 0.005 * X.tenure_months)
y = rng.binomial(1, 1 / (1 + np.exp(-logit)))

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.5, stratify=y, random_state=31)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
scores = model.predict_proba(X_test)[:, 1]


def gains_curve(y_true, y_score):
    """Share of rows contacted and share of positives reached, best scores first."""
    order = np.argsort(-y_score, kind="stable")
    hits = np.cumsum(np.asarray(y_true)[order])
    contacted = np.arange(1, len(hits) + 1) / len(hits)
    return contacted, hits / hits[-1]


contacted, gains = gains_curve(y_test, scores)
lift = gains / contacted

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4.5), layout="constrained")

ax1.plot(contacted, gains, color="#0e7490", lw=2.5, label="Model")
ax1.plot([0, 1], [0, 1], color="#94a3b8", ls="--", label="Random order")
ax1.set(title="Cumulative gains", xlabel="Customers contacted",
        ylabel="Responders reached", xlim=(0, 1), ylim=(0, 1.02))
ax1.xaxis.set_major_formatter(PercentFormatter(1))
ax1.yaxis.set_major_formatter(PercentFormatter(1))
ax1.legend(loc="lower right")

# Skip the first 1% of rows, where a handful of customers make lift jumpy.
start = len(lift) // 100
ax2.plot(contacted[start:], lift[start:], color="#c2410c", lw=2.5, label="Model")
ax2.axhline(1, color="#94a3b8", ls="--", label="Random order")
ax2.set(title="Cumulative lift", xlabel="Customers contacted",
        ylabel="Lift over random", xlim=(0, 1), ylim=(0, None))
ax2.xaxis.set_major_formatter(PercentFormatter(1))
ax2.legend(loc="upper right")
plt.show()

Cumulative gains chart rising well above the random diagonal, next to a cumulative lift chart falling from about 6 to 1 as more customers are contacted

Contacting the top 10% of customers by score reaches 34% of everyone who would respond, a lift of 3.4. The top 30% reaches 65%, a lift of 2.2.

How to Read Lift and Gains Charts

Both charts start from the same ranked list, with the highest score first. At any point along the x-axis:

  • Cumulative gains is the share of all responders found in the rows contacted so far.
  • Cumulative lift is the response rate among those rows divided by the overall response rate. It equals gains divided by the share contacted.

A model that ranks at random follows the diagonal on the gains chart and stays near 1 on the lift chart. Every curve ends at the same point, 100% of responders and a lift of 1, because contacting everyone leaves nothing for the model to choose.

Add the Perfect Model to a Cumulative Gains Chart

A perfect model puts every responder first. With a response rate of 9.8%, it reaches all of them after contacting 9.8% of customers. Plotting that line shows how much room the model has left.

base_rate = y_test.mean()

fig, ax = plt.subplots(figsize=(7, 5), layout="constrained")
ax.plot(contacted, gains, color="#0e7490", lw=2.5, label="Model")
ax.plot([0, base_rate, 1], [0, 1, 1], color="#15803d", ls=":", lw=2,
        label="Perfect model")
ax.plot([0, 1], [0, 1], color="#94a3b8", ls="--", label="Random order")

for share in (0.1, 0.3):
    value = np.interp(share, contacted, gains)
    ax.plot(share, value, "o", color="#0e7490")
    ax.annotate(f"{share:.0%} contacted\n{value:.0%} reached", (share, value),
                xytext=(18, -26), textcoords="offset points")

ax.set(title="Cumulative gains chart", xlabel="Customers contacted",
       ylabel="Responders reached", xlim=(0, 1), ylim=(0, 1.02))
ax.xaxis.set_major_formatter(PercentFormatter(1))
ax.yaxis.set_major_formatter(PercentFormatter(1))
ax.legend(loc="lower right")
plt.show()

Cumulative gains chart with the model curve between a random diagonal and a perfect model line, marked at 34% of responders for 10% contacted and 65% for 30% contacted

The highest possible lift is 1 / base_rate, about 10 here. A lift of 3 is a third of the maximum on this data, and would be the maximum on data where a third of rows are positive.

Make a Decile Lift Chart and Table

A decile chart splits the ranked list into ten equal groups and shows each group's own lift. It answers a different question from the cumulative curve: is this particular slice of customers still better than average?

ranked = pd.DataFrame({"score": scores, "responded": y_test})
ranked = ranked.sort_values("score", ascending=False, kind="stable")
ranked["decile"] = np.arange(len(ranked)) * 10 // len(ranked) + 1

table = ranked.groupby("decile")["responded"].agg(customers="size", responders="sum")
table["response_rate"] = table.responders / table.customers
table["lift"] = table.response_rate / ranked.responded.mean()
table["cum_gains"] = table.responders.cumsum() / table.responders.sum()
table["cum_lift"] = table.cum_gains / (table.customers.cumsum() / len(ranked))
print(table.round(3))

fig, ax = plt.subplots(figsize=(7, 4.5), layout="constrained")
colors = np.where(table.lift >= 1, "#c2410c", "#cbd5e1")
bars = ax.bar(table.index, table.lift, color=colors)
ax.bar_label(bars, fmt="{:.2f}", padding=3,
             bbox={"facecolor": "white", "edgecolor": "none", "pad": 1})
ax.axhline(1, color="#334155", ls="--", lw=1)
ax.set(title="Lift by decile", xlabel="Score decile (1 = highest scores)",
       ylabel="Response rate / average rate", xticks=table.index)
ax.margins(y=0.1)
plt.show()

Decile lift bar chart falling from 3.36 in the first decile to 0.04 in the tenth, with only the first three deciles above 1

Decile Customers Responders Response rate Lift Cumulative gains
1 1,000 328 32.8% 3.36 33.6%
2 1,000 177 17.7% 1.81 51.7%
3 1,000 126 12.6% 1.29 64.7%
4 1,000 92 9.2% 0.94 74.1%
5 1,000 79 7.9% 0.81 82.2%
6 1,000 79 7.9% 0.81 90.3%
7 1,000 45 4.5% 0.46 94.9%
8 1,000 31 3.1% 0.32 98.1%
9 1,000 15 1.5% 0.15 99.6%
10 1,000 4 0.4% 0.04 100%

Only the first three deciles respond more often than average. The code assigns deciles by rank position, so each group has the same size even when many rows share a score. pd.qcut on the raw scores can fail with duplicate bin edges in that case.

Compare Two Models on One Gains Chart

Call gains_curve once per model and draw the results on the same axes. Both models must be scored on the same test rows.

from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score

boost = HistGradientBoostingClassifier(random_state=31).fit(X_train, y_train)
models = {"Logistic regression": (model, "#0e7490"),
          "Gradient boosting": (boost, "#a21caf")}

fig, ax = plt.subplots(figsize=(7, 5), layout="constrained")
for name, (clf, color) in models.items():
    p = clf.predict_proba(X_test)[:, 1]
    x, g = gains_curve(y_test, p)
    ax.plot(x, g, color=color, lw=2, label=name)
    print(name, "AUC", round(roc_auc_score(y_test, p), 3),
          "top 10%:", round(np.interp(0.1, x, g), 3))
ax.plot([0, 1], [0, 1], color="#94a3b8", ls="--", label="Random order")
ax.set(title="Cumulative gains: two models", xlabel="Customers contacted",
       ylabel="Responders reached", xlim=(0, 1), ylim=(0, 1.02))
ax.xaxis.set_major_formatter(PercentFormatter(1))
ax.yaxis.set_major_formatter(PercentFormatter(1))
ax.legend(loc="lower right")
plt.show()

Cumulative gains curves for two models, with logistic regression above gradient boosting over most of the range

Logistic regression reaches 34% of responders in the top 10%, against 29% for gradient boosting with default settings, and its AUC is higher too (0.77 vs 0.74). That suits this data, which was generated from a logistic relationship. When two curves cross, pick the model that is higher at the share you plan to contact.

How Many Customers Should I Contact?

Turn the gains curve into money. Multiply the responders reached by what each one is worth, then subtract the cost of every contact. Here a contact costs $2 and a response earns $15.

cost_per_contact = 2.00
value_per_response = 15.00

n_contacted = np.arange(1, len(y_test) + 1)
responders = gains * y_test.sum()
profit = responders * value_per_response - n_contacted * cost_per_contact
best = profit.argmax()
print(f"best: contact {contacted[best]:.0%}, profit ${profit[best]:,.0f}")
print(f"contact everyone: ${profit[-1]:,.0f}")

fig, ax = plt.subplots(figsize=(7, 4.5), layout="constrained")
ax.plot(contacted, profit, color="#15803d", lw=2.5)
ax.axhline(0, color="#334155", lw=1)
ax.plot(contacted[best], profit[best], "o", color="#15803d")
ax.annotate(f"Contact {contacted[best]:.0%}: ${profit[best]:,.0f}",
            (contacted[best], profit[best]), xytext=(15, 5),
            textcoords="offset points")
ax.set(title="Campaign profit by share contacted", xlabel="Customers contacted",
       ylabel="Profit", xlim=(0, 1))
ax.margins(y=0.1)
ax.xaxis.set_major_formatter(PercentFormatter(1))
ax.yaxis.set_major_formatter(
    lambda v, _: f"{'-' if v < 0 else ''}${abs(v):,.0f}")
plt.show()

Campaign profit curve peaking at 3,708 dollars when 24% of customers are contacted and falling to a loss of 5,360 dollars when everyone is contacted

Profit peaks at $3,708 with 24% of customers contacted. Contacting everyone loses $5,360.

That peak was chosen using the test outcomes, so it is slightly optimistic. If the predicted probabilities are accurate, you can set the cutoff before seeing any outcomes: contact a customer when their probability is above cost_per_contact / value_per_response, here 0.133. On this test set that rule contacts 25% of customers and earns $3,654. Check the probabilities with a calibration curve before relying on it.

Gains Chart vs Lift Chart vs ROC Curve

Chart Y-axis X-axis Use it to
Cumulative gains Share of positives reached Share of rows contacted Show how many responders a budget captures
Cumulative lift Improvement over random Share of rows contacted Say "this list responds 3 times as often"
Decile lift Each tenth's own lift Score decile Find where a slice drops below average
ROC curve True positive rate False positive rate Compare ranking quality independent of class balance

The gains and ROC curves are closely related: they share a y-axis, but gains counts all rows on the x-axis while ROC counts only negatives. When positives are rare, the two look almost the same. For rare positives, a precision-recall curve is another useful view.

Practical Tips

  • Draw these charts from held-out data. Training rows make the lift look better than it will be.
  • Keep the real class balance in the test set. If you downsample negatives for training, don't downsample them for evaluation, because lift depends on the base rate.
  • Don't compare lift across datasets with different response rates. The maximum lift is 1 / base_rate.
  • Shuffle before ranking if your rows are sorted by outcome, because kind="stable" keeps tied scores in their original order. train_test_split shuffles by default, so this example is safe.
  • A response model finds people who are likely to buy, including those who would have bought anyway. To find people whose behavior the contact changes, use uplift modeling and a Qini curve.

Similar Topics