Uplift Modeling in Python: T-Learner and Qini Curve

Find the customers a campaign actually persuades: build T-, S- and class-transformation uplift models with scikit-learn and evaluate them with a Qini curve.

Uplift modeling predicts how much a treatment changes each customer's chance of acting. The simplest version, a T-learner, fits one classifier on treated customers and another on untreated ones, then subtracts their predict_proba() results. You evaluate the ranking with a Qini curve. This post uses only scikit-learn 1.9, NumPy and Matplotlib.

Quick Example

A shop emails a coupon to a random half of 40,000 customers. We want to know who buys because of the email.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(167)

# Sample data from a randomized email campaign
n = 40_000
df = pd.DataFrame({
    "recency": rng.integers(1, 366, n),       # days since last order
    "orders": rng.poisson(3, n),              # orders last year
    "discount_share": rng.beta(2, 5, n).round(3),  # share bought on sale
    "app_user": rng.binomial(1, 0.4, n),
})
df["emailed"] = rng.binomial(1, 0.5, n)       # random assignment

# Hidden truth: the email pushes bargain hunters and lapsing customers to buy,
# and puts off some recently active app users
base = -2.0 + 0.22 * df.orders - 0.004 * df.recency + 0.4 * df.app_user
lift = (2.2 * df.discount_share - 0.45
        - 0.5 * (df.app_user & (df.recency < 60))
        + 0.5 * df.recency.between(91, 239))
p0 = 1 / (1 + np.exp(-base))
p1 = 1 / (1 + np.exp(-(base + lift)))
true_uplift = p1 - p0
df["bought"] = rng.binomial(1, np.where(df.emailed, p1, p0))

features = ["recency", "orders", "discount_share", "app_user"]
train, test = train_test_split(df, test_size=0.5, random_state=0,
                               stratify=df[["emailed", "bought"]])

def model():
    return HistGradientBoostingClassifier(
        max_depth=3, learning_rate=0.03, max_iter=150,
        min_samples_leaf=200, random_state=0)

# T-learner: one model per group
treated = train[train.emailed == 1]
control = train[train.emailed == 0]
m1 = model().fit(treated[features], treated.bought)
m0 = model().fit(control[features], control.bought)
uplift = (m1.predict_proba(test[features])[:, 1]
          - m0.predict_proba(test[features])[:, 1])

def qini_curve(bought, emailed, score):
    """Incremental purchases when targeting customers from the top score down."""
    order = np.argsort(-score, kind="stable")
    y, t = np.asarray(bought)[order], np.asarray(emailed)[order]
    n_t, n_c = t.cumsum(), (1 - t).cumsum()
    y_t, y_c = (y * t).cumsum(), (y * (1 - t)).cumsum()
    ratio = np.divide(n_t, n_c, out=np.zeros(len(y)), where=n_c > 0)
    return np.r_[0, y_t - y_c * ratio]

curve = qini_curve(test.bought, test.emailed, uplift)
share = np.linspace(0, 100, len(curve))

fig, ax = plt.subplots(figsize=(8, 4.8))
ax.plot(share, curve, color="#c2571a", lw=2, label="T-learner ranking")
ax.plot([0, 100], [0, curve[-1]], color="#888888", ls="--", label="Random order")
ax.set_xlabel("Customers emailed (% of test set, best first)")
ax.set_ylabel("Extra purchases caused by the email")
ax.set_title("Qini curve")
ax.legend(loc="lower right")
plt.show()

Qini curve rising well above the random targeting line, peaking before everyone is emailed and then falling

Emailing the top 30% of the list produces about 397 extra purchases, 77% of the 519 you'd get by emailing all 20,000 test customers. The curve peaks near 90% at about 575 and then falls, because the last customers are less likely to buy if emailed.

How do I read a Qini curve?

  • The x-axis is how far down the ranked list you email.
  • The y-axis is the number of purchases that wouldn't have happened without the email, among those customers. It compares emailed and unemailed customers within the same top slice, scaling the control count to the treated count.
  • The dashed line is what random targeting gets. Higher above it is better.
  • Where the curve falls, you're emailing people the coupon puts off.

Why not just target likely buyers?

A response model predicts who will buy after being emailed. Many of those people would have bought anyway. The two other common uplift methods are:

  • S-learner: one model with emailed as a feature. Predict with it set to 1, then to 0, and subtract.
  • Class transformation: with a 50/50 split, predict z = 1 when a customer was emailed and bought, or wasn't emailed and didn't. Uplift is 2 * P(z) - 1.
X_test = test[features]

s_model = model().fit(train[features + ["emailed"]], train.bought)
s_score = (s_model.predict_proba(X_test.assign(emailed=1))[:, 1]
           - s_model.predict_proba(X_test.assign(emailed=0))[:, 1])

z = (train.bought == train.emailed).astype(int)
z_score = 2 * model().fit(train[features], z).predict_proba(X_test)[:, 1] - 1

scores = {
    "T-learner": uplift,
    "Class transformation": z_score,
    "S-learner": s_score,
    "Response model": m1.predict_proba(X_test)[:, 1],
}
colors = ["#c2571a", "#3a7d44", "#6a4c93", "#2b6f9e"]

fig, ax = plt.subplots(figsize=(8, 4.8))
for (name, score), color in zip(scores.items(), colors):
    ax.plot(share, qini_curve(test.bought, test.emailed, score),
            label=name, color=color, lw=1.8)
ax.plot([0, 100], [0, curve[-1]], color="#888888", ls="--", label="Random")
ax.set_xlabel("Customers emailed (%)")
ax.set_ylabel("Extra purchases")
ax.legend(loc="lower right")
plt.show()

Qini curves for T-learner, class transformation, S-learner and response model, with the T-learner highest and the response model lowest of the four

How do I compare uplift models with one number?

The Qini coefficient is the area between a model's curve and the random line. Here it is divided by the number of customers and scaled to 1,000, so it reads as the average gain over random targeting.

def qini_score(bought, emailed, score):
    q = qini_curve(bought, emailed, score)
    return (q.mean() - q[-1] / 2) / len(bought) * 1000

table = pd.Series({name: qini_score(test.bought, test.emailed, s)
                   for name, s in scores.items()})
table["True uplift (best possible ranking)"] = qini_score(
    test.bought, test.emailed, true_uplift[test.index].to_numpy())
print(table.round(1).to_string())
T-learner                              8.4
Class transformation                   7.6
S-learner                              6.9
Response model                         6.2
True uplift (best possible ranking)    9.2

The "true uplift" row is only available in a simulation. It isn't a hard upper limit either, since the score is computed from noisy outcomes.

These numbers are noisy. Resample the test set to see how much the gap between two models moves:

y, t = test.bought.to_numpy(), test.emailed.to_numpy()
boot = np.random.default_rng(0)
gaps = []
for _ in range(500):
    i = boot.integers(0, len(test), len(test))
    gaps.append(qini_score(y[i], t[i], uplift[i])
                - qini_score(y[i], t[i], scores["Response model"][i]))
low, high = np.percentile(gaps, [2.5, 97.5])
print(f"T-learner minus response model: {low:.1f} to {high:.1f}")
T-learner minus response model: 0.8 to 3.4

The interval stays above zero, so on this test set the T-learner ranks customers better than the response model. Gaps between the uplift methods are smaller, and it would be a stretch to declare one of them the winner in general.

How do I plot uplift by decile?

Sort the test set by predicted uplift, cut it into ten groups, and compare the buying rate of emailed and unemailed customers in each. This checks the predictions against what happened.

ranked = test.assign(score=uplift)
ranked["decile"] = pd.qcut(ranked.score.rank(method="first", ascending=False),
                           10, labels=range(1, 11))
rates = ranked.groupby(["decile", "emailed"], observed=True).bought.mean().unstack()
observed = (rates[1] - rates[0]) * 100
predicted = ranked.groupby("decile", observed=True).score.mean() * 100

fig, ax = plt.subplots(figsize=(8, 4.5))
x = np.arange(1, 11)
ax.bar(x, observed, color=np.where(observed > 0, "#c2571a", "#7a7a7a"),
       label="Observed (emailed minus control)")
ax.plot(x, predicted, "o-", color="#1d1d1d", label="Predicted")
ax.axhline(0, color="black", lw=0.8)
ax.set_xticks(x)
ax.set_xlabel("Decile of predicted uplift (1 = highest)")
ax.set_ylabel("Uplift (percentage points)")
ax.legend()
plt.show()

Bar chart of observed uplift by decile with a line of predicted uplift, falling from the first decile to the last

The top decile shows about 16 points of observed uplift and the bottom one about -5, so the model separates customers well at the ends. The middle is noisier (decile 7 dips below decile 8), which is normal with about 2,000 customers per bar.

Who is in each group?

Uplift modeling is often explained with four kinds of customer: persuadables buy only if emailed, sure things buy either way, lost causes don't buy either way, and sleeping dogs buy only if left alone. You can't observe which one a person is, because nobody is both emailed and not emailed. A model only estimates the difference in probabilities, so describe segments instead. Here the group with the highest predictions buys more on sale and includes more app users:

ranked["segment"] = pd.cut(ranked.score, [-1, 0, 0.05, 1],
                           labels=["Negative", "0 to 5 points", "Over 5 points"])
profile = ranked.groupby("segment", observed=True).agg(
    customers=("score", "size"), discount_share=("discount_share", "mean"),
    recency=("recency", "mean"), app_user=("app_user", "mean"))
print(profile.round(2).to_string())
               customers  discount_share  recency  app_user
segment                                                    
Negative            4657            0.16   172.42      0.34
0 to 5 points       7109            0.23   199.35      0.36
Over 5 points       8234            0.40   175.01      0.47

T-learner, S-learner or something else?

Method Strength Weakness
T-learner Simple, flexible Differences between two noisy models can be erratic, more so if one group is small
S-learner One model, smooth estimates The model may barely use the treatment feature and shrink uplift toward zero
Class transformation One model aimed directly at uplift The formula above needs a 50/50 split; otherwise weight the rows
Causal forest Confidence intervals, handles confounders Slower, needs EconML

Try more than one and compare them on held-out data. The order here is specific to this data set and these settings.

The packages scikit-uplift and causalml wrap these methods. In my environment (Python 3.14, scikit-learn 1.9), scikit-uplift 0.5.1 failed to import and causalml 0.18.0 had no prebuilt package for 3.14, so this post builds them directly.

Practical tips

  • Train on a randomized campaign. With observational data, the model can learn who was chosen instead of who responds.
  • Keep a random holdout in every campaign so you can train and check the next model.
  • Uplift is much harder to predict than response. Expect to need large samples and to see unstable results with small ones.
  • Evaluate on data the model never saw.
  • Email people whose predicted uplift is worth more than the cost of sending, including the coupon given to people who would have paid full price.

Similar Topics