Section 4 · Lesson 3

Ensembles and propensity scoring for ad targeting

Combine many trees with random forests and gradient boosting, then rank an audience by predicted propensity and decide who to target.

50 min 3 practice tasks
StatQuest: Random Forests Part 1 - Building, Using and Evaluating by StatQuest with Josh Starmer on YouTube

A single deep tree overfits, and a shallow one underfits. Ensembles get around this by combining many trees, so that their individual mistakes cancel out. They’re the default choice for tabular business data, and they’re the engine behind most propensity models.

Random forests: average many different trees

A random forest grows hundreds of deep trees, each one deliberately different:

  • each tree trains on a bootstrap sample (rows drawn with replacement)
  • each split considers only a random subset of features

Each tree overfits in its own way. Averaging their probabilities cancels much of that variance while keeping the trees’ ability to capture thresholds and interactions. Adding more trees doesn’t cause overfitting; it just costs time. min_samples_leaf and max_features are the main knobs.

Gradient boosting: trees that fix each other’s mistakes

Boosting builds shallow trees one after another. Each new tree is fit to the errors the ensemble is still making, and its contribution is scaled down by a learning_rate. Many small corrections add up to a strong model. Boosting usually edges out forests on tabular data, but it can overfit if you add too many trees or set the learning rate too high. Tune n_estimators, learning_rate and max_depth together with cross-validation. HistGradientBoostingClassifier is a much faster version for large data and handles missing values natively.

Model (behavior features) Test ROC-AUC
One unlimited tree 0.60
Random forest, 200 trees 0.80
Gradient boosting 0.81
Logistic regression with engineered features 0.83

Going from one tree to an ensemble is a huge jump. Notice the last row, though: the engineered logistic pipeline from earlier in this section beats boosting on raw features. Good features and a simple model are hard to beat, and they’re easier to explain.

Propensity scoring

A propensity score is a model’s predicted probability that someone will take an action, here converting. Ad targeting turns it into decisions:

  1. Score everyone in the audience with predict_proba.
  2. Rank them and cut the list into deciles (decile 1 = the top 10%).
  3. Check the lift. In our test audience, decile 1 converts at about 55%, compared with 15% overall: a lift of 3.6×. The bottom deciles convert at around 2%.
  4. Read the gains. The top 30% of visitors by propensity hold about 71% of all conversions.

Deciding how many to target

Suppose a conversion is worth $25 of margin and reaching one visitor costs $4. Add the next decile only while its conversion rate exceeds the break-even rate of 4 / 25 = 16%. Deciles 1–3 clear it (55%, 32%, 22%) and decile 4 (12%) doesn’t. Targeting the top 30% earns about $1,900 on this test audience, compared with about $1,775 for the top 40% and a loss for targeting everyone. The model’s job is the ranking; the economics choose the cut-off.

Propensity is not persuasion

A high score means “likely to buy”, not “likely to buy because of the ad”. Many people in the top decile would have bought anyway, so crediting the campaign with all their conversions overstates its value. To measure the ad’s real effect, keep a random holdout group from the targeted audience unexposed and compare conversion rates. That’s an A/B test, and the statistics course covers how to analyze one. Uplift models go further and predict the difference the ad makes for each person, so you spend on persuadable visitors rather than sure things.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Many trees beat one

On the usual split, fit three tree-based models and compute each one's test ROC-AUC, rounded to 4 decimals:

  • forest: RandomForestClassifier(n_estimators=200, min_samples_leaf=5, random_state=42)

→ forest_auc

  • boost: GradientBoostingClassifier(random_state=42) → boost_auc
  • an unlimited DecisionTreeClassifier(random_state=42) for comparison → single_tree_auc

The forest takes a second or two to train in the browser.

Need a hint?
  1. All three models share the same API, so a small helper like def test_auc(model): ... saves typing.
  2. Use predict_proba(X_test)[:, 1] for every AUC, not predict.
Python 3
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.metrics import roc_auc_score

audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
            "days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X_train, X_test, y_train, y_test = train_test_split(
    audience[features], audience["converted"], test_size=0.25, random_state=42,
    stratify=audience["converted"],
)

forest = None
boost = None
forest_auc = None
boost_auc = None
single_tree_auc = None
print(single_tree_auc, forest_auc, boost_auc)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
2

Score and rank the audience

Use the gradient boosting model (boost, fitted in the starter) to score the test visitors.

  • scored: a DataFrame with columns propensity (boost's test probabilities) and converted

(the values of y_test), plus a decile column built with pd.qcut(scored["propensity"].rank(method="first", ascending=False), 10, labels=range(1, 11)). Decile 1 is the 10% of visitors with the highest propensity.

  • decile_rates: the conversion rate in each decile, from

scored.groupby("decile", observed=True)["converted"].mean()

  • top_decile_lift: decile 1's conversion rate divided by the overall test conversion rate,

rounded to 2 decimals

Need a hint?
  1. Use y_test.to_numpy() for the converted column so it lines up row by row with the probabilities.
  2. decile_rates.loc[1] is the top decile's conversion rate; divide by scored["converted"].mean().
Python 3
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier

audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
            "days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X_train, X_test, y_train, y_test = train_test_split(
    audience[features], audience["converted"], test_size=0.25, random_state=42,
    stratify=audience["converted"],
)
boost = GradientBoostingClassifier(random_state=42).fit(X_train, y_train)

scored = None
decile_rates = None
top_decile_lift = None
print(decile_rates, top_decile_lift)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
3

How much of the audience to target?

Each conversion is worth $25 of margin, and showing the campaign to one visitor costs $4. You'll target the top d deciles, for some d from 1 to 10. The starter rebuilds scored with its decile column.

  • gain_30: the share of all test conversions that fall in deciles 1–3 (the top 30%), rounded

to 4 decimals

  • profit_by_decile: a pandas Series indexed 1 to 10, where entry d is the profit of

targeting deciles 1 to d: 25 * conversions - 4 * visitors in those deciles

  • best_deciles: the d with the highest profit, as an integer
  • best_profit: that profit
Need a hint?
  1. scored.groupby("decile", observed=True)["converted"].agg(["sum", "count"]) gives conversions and visitors per decile; .cumsum() turns them into running totals.
  2. Cumulative totals at decile 3 cover deciles 1, 2 and 3.
Python 3
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier

audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
            "days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X_train, X_test, y_train, y_test = train_test_split(
    audience[features], audience["converted"], test_size=0.25, random_state=42,
    stratify=audience["converted"],
)
boost = GradientBoostingClassifier(random_state=42).fit(X_train, y_train)
scored = pd.DataFrame({"propensity": boost.predict_proba(X_test)[:, 1], "converted": y_test.to_numpy()})
scored["decile"] = pd.qcut(scored["propensity"].rank(method="first", ascending=False), 10, labels=range(1, 11))

VALUE, COST = 25, 4

gain_30 = None
profit_by_decile = None
best_deciles = None
best_profit = None
print(gain_30, best_deciles, best_profit)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status