Most production classifiers answer "who is likely to convert?" Marketing, retention, and pricing teams actually need a different question answered: "whose behavior will change if we intervene?" A customer who would renew anyway does not need a discount; one who will churn regardless is wasted spend. Uplift modeling (heterogeneous treatment effect estimation) targets the difference an action makes. This tutorial builds uplift models in Keras 3 on TensorFlow and, more importantly, shows how to evaluate them honestly.
The setup: potential outcomes
For each user we imagine two outcomes: Y(1) if treated and Y(0) if not. The quantity we want is the conditional average treatment effect:
uplift(x) = P(Y=1 | x, treated) - P(Y=1 | x, control)
We never observe both outcomes for one person, so the model must be trained from data where treatment was randomized. This is the most important prerequisite: with observational data, confounding will make a naive model learn who was selected for treatment, not who benefits. If you cannot run a randomized holdout, plan for one before anything else.
Data layout
You need features X, a binary treatment flag t, and a binary outcome y. Split into train/validation/test stratified on both t and y so each split keeps the treatment ratio.
import numpy as np
import keras
from keras import layers
# X: float32 [n, d], t: {0,1}, y: {0,1}
Approach 1: the T-learner
Train two separate outcome models, one on treated rows and one on control rows, and subtract their predictions.
def make_outcome_model(d):
inp = keras.Input((d,))
h = layers.Dense(64, activation="relu")(inp)
h = layers.Dropout(0.2)(h)
h = layers.Dense(32, activation="relu")(h)
out = layers.Dense(1, activation="sigmoid")(h)
return keras.Model(inp, out)
m_t = make_outcome_model(X.shape[1])
m_c = make_outcome_model(X.shape[1])
for m in (m_t, m_c):
m.compile("adam", "binary_crossentropy")
m_t.fit(X_tr[t_tr == 1], y_tr[t_tr == 1], epochs=20, batch_size=512,
validation_split=0.1, verbose=0)
m_c.fit(X_tr[t_tr == 0], y_tr[t_tr == 0], epochs=20, batch_size=512,
validation_split=0.1, verbose=0)
uplift = m_t.predict(X_te).ravel() - m_c.predict(X_te).ravel()
It is simple and a strong baseline. Its weakness: each model sees only part of the data, and errors in the two models do not cancel, so the difference can be noisy when the true effect is small relative to the base rate.
Approach 2: a shared trunk with two heads
A shared representation lets both arms learn features jointly (a TARNet-style architecture). Each example only updates the head matching its arm.
inp = keras.Input((X.shape[1],))
trunk = layers.Dense(128, activation="relu")(inp)
trunk = layers.Dense(64, activation="relu")(trunk)
p0 = layers.Dense(1, activation="sigmoid", name="control")(trunk)
p1 = layers.Dense(1, activation="sigmoid", name="treated")(trunk)
t_in = keras.Input((1,), name="t")
# pick the observed arm's prediction for the loss
observed = layers.Lambda(lambda a: a[2] * a[1] + (1 - a[2]) * a[0])([p0, p1, t_in])
train_model = keras.Model([inp, t_in], observed)
train_model.compile("adam", "binary_crossentropy")
train_model.fit([X_tr, t_tr[:, None].astype("float32")], y_tr,
epochs=20, batch_size=512, validation_split=0.1, verbose=0)
heads = keras.Model(inp, [p0, p1]) # shares trained weights
c, tr = heads.predict(X_te)
uplift = (tr - c).ravel()
A practical note: if the treated/control split is imbalanced, weight samples by inverse arm frequency so the smaller arm still shapes the trunk.
Evaluating: accuracy metrics will mislead you
AUC on y tells you nothing here, because we never observe the true uplift per person. Evaluate by ranking: sort the test set by predicted uplift, then compare treated and control outcome rates as you move down the list. This gives the uplift curve and its normalized cousin, the Qini curve.
def qini_curve(uplift, t, y):
order = np.argsort(-uplift)
t, y = t[order], y[order]
cum_t = np.cumsum(t)
cum_c = np.cumsum(1 - t)
yt = np.cumsum(y * t)
yc = np.cumsum(y * (1 - t))
# incremental responders, rescaling control to treated group size
gain = yt - yc * np.divide(cum_t, np.maximum(cum_c, 1))
return gain
gain = qini_curve(uplift, t_te, y_te)
random_line = np.linspace(0, gain[-1], len(gain))
qini_coeff = (gain - random_line).mean() / len(gain)
Compare against the straight line from zero to the final gain, which is what random targeting achieves. A good model bows above that line: the top deciles contain people who respond to the treatment. Report the curve with confidence intervals from bootstrapping the test set; uplift estimates are noisy and a single curve overstates certainty.
Turning scores into decisions
Uplift is only useful with a cost model. Treat user i when uplift_i * value_per_conversion > cost_per_treatment. Choose the threshold on validation data, then confirm the realized lift on a fresh randomized holdout in production, because that is the only unbiased check.
Pitfalls we see in client projects
- Non-randomized treatment. The most common failure. Check covariate balance between arms before modeling.
- Leakage of post-treatment features. Anything measured after the intervention biases the effect toward zero or worse.
- Overfitting small effects. Uplift signal is weak; use early stopping, strong regularization, and compare to a simple baseline such as a single logistic regression with treatment interaction terms.
- Optimizing the wrong metric. Tune on validation Qini, not log-loss.
- Drift. Effects change as campaigns and audiences change. Keep a small permanent control group and re-evaluate regularly.
When to bring in help
Uplift projects succeed or fail on experimental design more than model architecture. If you are planning a randomized rollout, or have an existing model whose lift you cannot verify, our TensorFlow consultants can review the design and the evaluation pipeline with your team. Get in touch through the contact page.