An introduction to tidycate

tidycate estimates how the effect of a treatment varies from one individual to the next. It does this with causal meta-learners, which build an effect estimate out of ordinary prediction models. tidycate takes those prediction models as tidymodels workflows, so any parsnip model, with any formula or recipe, can be a base learner, and trying a different base learner means changing one argument.

This vignette starts with the ideas: what is being estimated, how each of tidycate’s five learners estimates it, and how to check the estimates. It then puts them to work on two simulated email campaigns, fitting an S-learner to a simple one and an R-learner to a richer one, each with two sets of base models, and ends by scoring all four fits.

library(tidycate)
library(tidymodels)

The problem: effects we never see

Throughout, the example is an online store that emails a random half of its customers and records how much each one spends. For customer \(i\), let \(W_i\) be 1 if they were emailed and 0 if not, \(X_i\) their features (such as the months since their last purchase), and \(Y_i\) their spending.

Each customer has two potential outcomes: \(Y_i(1)\), what they would spend if emailed, and \(Y_i(0)\), what they would spend if not. The email’s effect on them is \(Y_i(1) - Y_i(0)\). But only one of the two is ever observed, \(Y_i = Y_i(W_i)\), so no customer’s own effect can be seen, and it can’t be used as the target of a prediction model.

What can be estimated is the conditional average treatment effect (CATE), the average effect among customers with the same features:

\[\tau(x) = E\big[Y(1) - Y(0) \mid X = x\big].\]

Unlike the average treatment effect, \(E[Y(1) - Y(0)]\), which is one number for everyone, \(\tau(x)\) is a function of the features, and estimating it shows who benefits most.

Estimating \(\tau(x)\) rests on three assumptions:

  • No unmeasured confounding: given \(X\), whether a customer was emailed is unrelated to their potential outcomes.
  • Overlap: every kind of customer could have been emailed or not. The propensity, \(e(x) = P(W = 1 \mid X = x)\), each customer’s chance of being emailed, is strictly between 0 and 1.
  • Consistency: a customer’s observed outcome is the potential outcome for the treatment they got, and one customer’s email doesn’t change another’s spending.

A randomized experiment guarantees the first two by design, and its propensity is known: here, \(e(x) = 0.5\) for everyone. No learner can make up for a violation of these assumptions.

The learners combine a few ordinary prediction problems. Write \(\mu_1(x)\) and \(\mu_0(x)\) for the mean outcome of emailed and of not-emailed customers with features \(x\), and \(m(x)\) for the mean outcome of all customers with features \(x\), emailed or not. Under the assumptions, \(\tau(x) = \mu_1(x) - \mu_0(x)\). A hat marks a fitted model or an estimate, as in \(\hat\mu_1\) or \(\hat\tau\).

The five learners

Each learner turns the problem into regressions that any base model can fit. In tidycate, outcome_model is a workflow for the outcome; the X-, R-, and DR-learners also take an effect_model, a parsnip model specification for the effect, and a propensity, either a known number or a classification workflow that estimates \(e(x)\).

S-learner (s_learner(); Künzel et al., 2019). A single model, with the treatment as one more feature, \(\hat\mu(x, w)\). The estimate is the difference between its predictions with the treatment switched on and off:

\[\hat\tau(x) = \hat\mu(x, 1) - \hat\mu(x, 0).\]

It’s the simplest learner, but the model decides how much the treatment matters, and a model that rarely uses it (one that is heavily regularized, or a tree that seldom splits on it) pulls the estimates toward zero.

T-learner (t_learner(); Künzel et al., 2019). The same outcome model, fit twice: once to the treated customers and once to the control customers.

\[\hat\tau(x) = \hat\mu_1(x) - \hat\mu_0(x).\]

The effects can vary freely, but each model sees only part of the data, so the estimates are noisy when one group is small.

X-learner (x_learner(); Künzel et al., 2019). It starts as a T-learner, then uses each group’s model to estimate every customer’s own effect: \(D_i = Y_i - \hat\mu_0(X_i)\) for treated customers and \(D_i = \hat\mu_1(X_i) - Y_i\) for control customers. An effect model is fit to these in each group, giving \(\hat\tau_1(x)\) and \(\hat\tau_0(x)\), and the two are combined with the propensity:

\[\hat\tau(x) = e(x)\,\hat\tau_0(x) + \big(1 - e(x)\big)\,\hat\tau_1(x).\]

When few customers are treated, \(\hat\tau_0\) relies on the noisy \(\hat\mu_1\), but \(e(x)\) is small, so it gets little weight.

R-learner (r_learner(); Nie and Wager, 2021). It works with residuals. Robinson’s decomposition (Robinson, 1988) says

\[Y - m(X) = \big(W - e(X)\big)\,\tau(X) + \varepsilon,\]

where \(\varepsilon\) averages to zero for any \(X\) and \(W\): once the part of the outcome that the features predict is removed, what’s left is the part of the treatment that the features don’t predict, times the effect, plus noise. The R-learner fits \(\hat m\) and \(\hat e\) and then chooses the effect model that minimizes

\[\sum_i \Big[\big(Y_i - \hat m(X_i)\big) - \big(W_i - \hat e(X_i)\big)\,\tau(X_i)\Big]^2,\]

which is the same as regressing the pseudo-outcome \(\big(Y_i - \hat m(X_i)\big) / \big(W_i - \hat e(X_i)\big)\) on \(X_i\), weighting each customer by \(\big(W_i - \hat e(X_i)\big)^2\). When the propensity is 0.5 for everyone, the weights are all equal.

DR-learner (dr_learner(); Kennedy, 2023). It starts from the T-learner’s difference and corrects it with each customer’s residual from their own group’s model, divided by their chance of being in that group:

\[\hat\varphi_i = \hat\mu_1(X_i) - \hat\mu_0(X_i) + \frac{W_i\,\big(Y_i - \hat\mu_1(X_i)\big)}{\hat e(X_i)} - \frac{(1 - W_i)\,\big(Y_i - \hat\mu_0(X_i)\big)}{1 - \hat e(X_i)},\]

then regresses the pseudo-outcome \(\hat\varphi_i\) on \(X_i\). It is doubly robust: its average is right if either the outcome models or the propensity is right, and in a randomized experiment the propensity is known.

Cross-fitting. The R- and DR-learners’ pseudo-outcomes need \(\hat m(X_i)\), \(\hat\mu_1(X_i)\), \(\hat\mu_0(X_i)\), and \(\hat e(X_i)\) for the same customers the models learn from. A flexible model that is fit and evaluated on the same customers partly memorizes their outcomes, effect included, which shrinks the residuals and, with them, the estimated effects. So these learners cross-fit: they split the data into \(K\) folds (folds = 5 by default) and predict each fold from models fit to the other folds, so every customer’s predictions come from models that never saw them.

Checking the estimates

Real data never reveals \(\tau\), so estimates are checked on held-out customers from a randomized experiment, using only their observed outcomes. Rank the test customers by \(\hat\tau\), highest first, and take the top share \(s\) of the list. Let \(\bar Y_T(s)\) and \(\bar Y_C(s)\) be the mean outcomes of the emailed and the not-emailed customers in that top group. Because the email was assigned at random, their difference estimates the average effect in the top group.

  • Uplift at \(k\) (uplift_at_k()) is that difference for the top share \(k\) (by default, 30%), the average effect among the customers the estimates rank highest:

    \[\text{uplift}(k) = \bar Y_T(k) - \bar Y_C(k).\]

  • The Qini curve (qini_curve()) is \(g(s) = \big(\bar Y_T(s) - \bar Y_C(s)\big)\, s\), the gain per customer on the whole list from emailing only its top share \(s\). At \(s = 1\), everyone is emailed, and \(g(1)\) is the overall difference in means. A random ranking gives the straight line \(s\, g(1)\).

  • The Qini coefficient (qini_coef()) is the area between the curve and that line:

    \[Q = \int_0^1 \big(g(s) - s\, g(1)\big)\, ds,\]

    in dollars per customer. A positive value means the ranking beats a random one. Its best possible value depends on how much the true effects vary, so compare learners only on the same data. It measures the order of the estimates, not their size.

  • The calibration table (cate_cal_table()) splits the customers into bins by \(\hat\tau\) and compares each bin’s mean estimate with its observed effect, \(\bar Y_T - \bar Y_C\), whose standard error is \(\sqrt{\hat\sigma_T^2 / n_T + \hat\sigma_C^2 / n_C}\) (\(\hat\sigma^2\) is a group’s outcome variance in the bin and \(n\) its size). This checks the size of the estimates as well as their order.

Each score comes from a finite test set, so it is noisy: even with thousands of test customers, the difference between two learners’ scores can be smaller than the scores’ own sampling error. To see how much a score varies, compute it on bootstrap samples of the test set, for example with rsample::bootstraps().

In a simulation, the true effects are known, so the estimates can be checked against them directly. The PEHE (precision in estimating heterogeneous effects) is the root mean squared error of the estimates,

\[\text{PEHE} = \sqrt{\frac{1}{n}\sum_i \big(\hat\tau(X_i) - \tau(X_i)\big)^2},\]

It needs \(\tau\), so it is only available in simulations.

An S-learner on a simple campaign

The first campaign has 40,000 customers and three features: the months since their last purchase (recency), their spending over the past year (history), and whether they are new customers (newbie). The email helps recent customers most: the true effect falls in a straight line from $9.25 at one month to $1 at twelve.

set.seed(1)
n <- 40000
simple <- tibble(
  recency = sample(1:12, n, replace = TRUE),  # months since last purchase
  history = runif(n, 0, 500),                 # past-year spending
  newbie  = rbinom(n, 1, 0.3),                # 1 = new customer
  emailed = rbinom(n, 1, 0.5),                # the treatment: a coin flip
  tau     = 10 - 0.75 * recency,              # the true effect
  spend   = 20 + 0.1 * history - recency + 5 * newbie + emailed * tau +
    rnorm(n, sd = 5)
)

Real data has no tau column, so it is dropped from the training set. The test set keeps it for checking later.

set.seed(2)
simple_split <- initial_split(simple, strata = emailed)
simple_train <- training(simple_split) |> select(-tau)
simple_test  <- testing(simple_split)

The S-learner fits a single model with the treatment as a predictor. For a linear model, that means interactions with the treatment; without them, every customer would get the same estimated effect. A random forest finds interactions on its own. Define each base model first:

s_lm_model <- workflow(
  spend ~ (recency + history + newbie) * emailed,
  linear_reg()
)
s_rf_model <- workflow(
  spend ~ recency + history + newbie + emailed,
  rand_forest(mode = "regression", trees = 500)
)

Then fit the S-learner, naming the treatment column:

s_lm_fit <- s_learner(s_lm_model) |>
  fit(data = simple_train, treatment = emailed)

Swapping in the random forest changes only the workflow passed to s_learner():

set.seed(3)
s_rf_fit <- s_learner(s_rf_model) |>
  fit(data = simple_train, treatment = emailed)

predict() returns one estimated effect per customer, and for the S-learner it can also return both potential outcomes:

predict(s_lm_fit, new_data = head(simple_test))
#> # A tibble: 6 × 1
#>   .pred_cate
#>        <dbl>
#> 1       3.06
#> 2       9.28
#> 3       6.36
#> 4       6.34
#> 5       2.40
#> 6       5.55
predict(s_lm_fit, new_data = head(simple_test), type = "potential_outcomes")
#> # A tibble: 6 × 2
#>   .pred_control .pred_treated
#>           <dbl>         <dbl>
#> 1          24.2          27.3
#> 2          52.6          61.8
#> 3          57.4          63.8
#> 4          53.0          59.4
#> 5          46.2          48.6
#> 6          47.0          52.5

An R-learner on a richer campaign

The second campaign also has 40,000 customers, but 20 features: the same three, two categorical ones (how each customer shops and where they live), and 15 that affect nothing. The true effect is no longer a straight line. It peaks for customers who last bought six or seven months ago, jumps by about $4 for customers who spent more than about $250 last year, and is $2 higher for customers who shop through several channels. Each customer’s own effect (ite) also varies randomly around \(\tau(x)\), which no learner can predict.

set.seed(1)
n <- 40000
rich <- tibble(
  recency  = sample(1:12, n, replace = TRUE),
  history  = runif(n, 0, 500),
  newbie   = rbinom(n, 1, 0.3),
  channel  = sample(c("web", "phone", "multichannel"), n,
                    replace = TRUE, prob = c(0.45, 0.45, 0.10)),
  zip_area = sample(c("urban", "suburban", "rural"), n,
                    replace = TRUE, prob = c(0.40, 0.45, 0.15))
)

# 15 features that affect nothing
noise <- matrix(rnorm(n * 15), nrow = n,
                dimnames = list(NULL, paste0("noise_", 1:15)))

rich <- rich |>
  bind_cols(as_tibble(noise)) |>
  mutate(
    channel  = factor(channel, levels = c("web", "phone", "multichannel")),
    zip_area = factor(zip_area, levels = c("urban", "suburban", "rural")),
    emailed  = rbinom(n, 1, 0.5),
    tau = 8 - 1.5 * abs(recency - 6.5) +           # a peak in recency
      4 / (1 + exp(-(history - 250) / 25)) +        # a jump in past spending
      2 * (channel == "multichannel"),
    ite = tau + rnorm(n, sd = 2),                   # each customer's own effect
    spend = 20 + 25 * log1p(history / 100) - recency + 5 * newbie +
      case_when(channel == "phone" ~ -3,
                channel == "multichannel" ~ 5, .default = 0) +
      case_when(zip_area == "urban" ~ 2,
                zip_area == "rural" ~ -2, .default = 0) +
      emailed * ite + rnorm(n, sd = 5)
  )

set.seed(2)
rich_split <- initial_split(rich, strata = emailed)
rich_train <- training(rich_split) |> select(-tau, -ite)
rich_test  <- testing(rich_split)

The R-learner takes three base models: an outcome model for \(m(x)\), which leaves out the treatment; an effect model; and a propensity. The first combination pairs boosted trees for the outcome with an elastic net for the effect, and uses the known propensity of 0.5. The effect model reuses the outcome model’s recipe, so the natural splines on recency and history are what let a linear effect model follow a curved effect, and the elastic net can shrink the 15 useless features toward zero. The penalty is fixed here rather than tuned.

rich_recipe <- recipe(spend ~ ., data = rich_train) |>
  step_rm(emailed) |>
  step_ns(recency, history, deg_free = 4) |>
  step_dummy(all_nominal_predictors())

outcome_a <- workflow(
  rich_recipe,
  boost_tree(mode = "regression", trees = 500, tree_depth = 3,
             learn_rate = 0.05)
)
effect_a <- linear_reg(penalty = 0.05, mixture = 0.5) |>
  set_engine("glmnet")

set.seed(3)
r_fit_a <- r_learner(outcome_a, effect_model = effect_a, propensity = 0.5) |>
  fit(data = rich_train, treatment = emailed)

The second combination swaps every base model: MARS for the outcome, boosted trees for the effect, and a propensity estimated by logistic regression, all with a plain formula. The estimated propensities aren’t all exactly 0.5, so the R-learner now fits the effect model with unequal weights, \((W_i - \hat e(X_i))^2\). The call to r_learner() stays the same:

outcome_b <- workflow(spend ~ . - emailed, mars(mode = "regression"))
effect_b <- boost_tree(mode = "regression", trees = 300, tree_depth = 2,
                       learn_rate = 0.05)
propensity_b <- workflow(emailed ~ . - spend, logistic_reg())

set.seed(4)
r_fit_b <- r_learner(outcome_b, effect_model = effect_b,
                     propensity = propensity_b) |>
  fit(data = rich_train, treatment = emailed)

Each engine needs its package installed: ranger, xgboost, glmnet, and earth here. fit() cross-fits the outcome model, and the propensity when it is estimated, on 5 folds of the training data.

Scoring the fits

What a learner and a fit contain

Printing a learner before fitting shows its base models:

r_learner(outcome_b, effect_model = effect_b, propensity = propensity_b)
#> ══ R-learner [not fitted] ══════════════════════════════════════════════════════
#> Outcome model: mars (earth), cross-fitted
#>                spend ~ . - emailed
#> Effect model:  boost_tree (xgboost), weighted by (treatment - propensity)^2
#>                same formula as the outcome model
#> Propensity:    logistic_reg (glm), cross-fitted
#>                emailed ~ . - spend

Printing a fit also shows the outcome, the treatment’s coding, the training rows, and, for the R- and DR-learners, the folds and the range of any estimated propensities:

s_lm_fit
#> ══ S-learner [fitted] ══════════════════════════════════════════════════════════
#> Outcome:   spend (numeric)
#> Treatment: emailed (treated = 1, control = 0)
#> Training:  29,999 rows (14,943 treated, 15,056 control)
#> 
#> ── Models ──────────────────────────────────────────────────────────────────────
#> Outcome model: linear_reg (lm), with emailed as a predictor
#>                spend ~ (recency + history + newbie) * emailed
s_rf_fit
#> ══ S-learner [fitted] ══════════════════════════════════════════════════════════
#> Outcome:   spend (numeric)
#> Treatment: emailed (treated = 1, control = 0)
#> Training:  29,999 rows (14,943 treated, 15,056 control)
#> 
#> ── Models ──────────────────────────────────────────────────────────────────────
#> Outcome model: rand_forest (ranger), with emailed as a predictor
#>                spend ~ recency + history + newbie + emailed
r_fit_a
#> ══ R-learner [fitted] ══════════════════════════════════════════════════════════
#> Outcome:   spend (numeric)
#> Treatment: emailed (treated = 1, control = 0)
#> Training:  29,999 rows (15,074 treated, 14,925 control)
#> 
#> ── Models ──────────────────────────────────────────────────────────────────────
#> Outcome model: boost_tree (xgboost), cross-fitted
#>                recipe: step_rm(), step_ns(), step_dummy()
#> Effect model:  linear_reg (glmnet)
#>                same recipe as the outcome model
#> Propensity:    0.5 (known)
#> Folds:         5 from vfold_cv(), stratified by emailed
r_fit_b
#> ══ R-learner [fitted] ══════════════════════════════════════════════════════════
#> Outcome:   spend (numeric)
#> Treatment: emailed (treated = 1, control = 0)
#> Training:  29,999 rows (15,074 treated, 14,925 control)
#> 
#> ── Models ──────────────────────────────────────────────────────────────────────
#> Outcome model: mars (earth), cross-fitted
#>                spend ~ . - emailed
#> Effect model:  boost_tree (xgboost), weighted by (treatment - propensity)^2
#>                same formula as the outcome model
#> Propensity:    logistic_reg (glm), cross-fitted
#>                emailed ~ . - spend
#>                estimates 0.44 to 0.57
#> Folds:         5 from vfold_cv(), stratified by emailed

Scores on the test sets

augment() adds each fit’s estimated effects (.pred_cate) to its test set. Stacking each learner’s two fits, labeled by model and grouped, scores both at once. (ranger’s predictions use random numbers, so set a seed first.)

set.seed(4)
s_results <- bind_rows(
  lm = augment(s_lm_fit, new_data = simple_test),
  rf = augment(s_rf_fit, new_data = simple_test),
  .id = "model"
) |>
  group_by(model)

r_results <- bind_rows(
  xgb_enet = augment(r_fit_a, new_data = rich_test),
  mars_xgb = augment(r_fit_b, new_data = rich_test),
  .id = "model"
) |>
  group_by(model)

qini_coef() and uplift_at_k() are yardstick metrics, so metric_set() combines them and passes the treatment column on:

uplift_metrics <- metric_set(qini_coef, uplift_at_k)

s_results |>
  uplift_metrics(truth = spend, estimate = .pred_cate, treatment = emailed)
#> # A tibble: 4 × 4
#>   model .metric     .estimator .estimate
#>   <chr> <chr>       <chr>          <dbl>
#> 1 lm    qini_coef   standard       0.658
#> 2 rf    qini_coef   standard       0.645
#> 3 lm    uplift_at_k standard       7.72 
#> 4 rf    uplift_at_k standard       7.58
r_results |>
  uplift_metrics(truth = spend, estimate = .pred_cate, treatment = emailed)
#> # A tibble: 4 × 4
#>   model    .metric     .estimator .estimate
#>   <chr>    <chr>       <chr>          <dbl>
#> 1 mars_xgb qini_coef   standard       0.779
#> 2 xgb_enet qini_coef   standard       0.806
#> 3 mars_xgb uplift_at_k standard       9.25 
#> 4 xgb_enet uplift_at_k standard       9.30

qini_curve() returns one point per distinct estimate:

s_curve <- s_results |>
  qini_curve(truth = spend, estimate = .pred_cate, treatment = emailed)
s_curve
#> # A tibble: 19,715 × 6
#>    model .threshold .n_treated .n_control   .share   .gain
#>    <chr>      <dbl>      <int>      <int>    <dbl>   <dbl>
#>  1 lm        Inf             0          0 0        0      
#>  2 lm          9.46          1          2 0.000300 0.00151
#>  3 lm          9.46          2          2 0.000400 0.00332
#>  4 lm          9.46          2          3 0.000500 0.00531
#>  5 lm          9.46          2          4 0.000600 0.00694
#>  6 lm          9.46          2          5 0.000700 0.00894
#>  7 lm          9.46          2          6 0.000800 0.00884
#>  8 lm          9.46          3          6 0.000900 0.0100 
#>  9 lm          9.46          3          7 0.001000 0.0116 
#> 10 lm          9.46          3          8 0.00110  0.0128 
#> # ℹ 19,705 more rows

With thousands of points, it is easier to read at every tenth of the list, next to the random line:

curve_table <- function(curve) {
  curve |>
    group_by(model) |>
    reframe(
      share  = seq(0, 1, by = 0.1),
      gain   = approx(.share, .gain, xout = share)$y,
      random = share * last(.gain)
    ) |>
    pivot_wider(names_from = model, values_from = gain)
}

curve_table(s_curve)
#> # A tibble: 11 × 4
#>    share random    lm    rf
#>    <dbl>  <dbl> <dbl> <dbl>
#>  1   0    0     0     0    
#>  2   0.1  0.499 0.971 0.909
#>  3   0.2  0.998 1.68  1.51 
#>  4   0.3  1.50  2.32  2.27 
#>  5   0.4  2.00  2.98  2.85 
#>  6   0.5  2.49  3.57  3.45 
#>  7   0.6  2.99  3.96  3.89 
#>  8   0.7  3.49  4.30  4.28 
#>  9   0.8  3.99  4.59  4.63 
#> 10   0.9  4.49  4.82  4.89 
#> 11   1    4.99  4.99  4.99

r_results |>
  qini_curve(truth = spend, estimate = .pred_cate, treatment = emailed) |>
  curve_table()
#> # A tibble: 11 × 4
#>    share random mars_xgb xgb_enet
#>    <dbl>  <dbl>    <dbl>    <dbl>
#>  1   0    0         0        0   
#>  2   0.1  0.640     1.08     1.11
#>  3   0.2  1.28      1.95     1.98
#>  4   0.3  1.92      2.78     2.79
#>  5   0.4  2.56      3.68     3.78
#>  6   0.5  3.20      4.42     4.44
#>  7   0.6  3.84      4.99     5.00
#>  8   0.7  4.48      5.53     5.49
#>  9   0.8  5.12      5.85     5.84
#> 10   0.9  5.76      6.22     6.19
#> 11   1    6.40      6.40     6.40

The calibration tables compare each bin’s mean estimate with its observed effect:

s_results |>
  cate_cal_table(truth = spend, estimate = .pred_cate, treatment = emailed,
                 bins = 5)
#> # A tibble: 10 × 7
#>    model  .bin .n_treated .n_control .mean_estimate .observed .std_error
#>    <chr> <int>      <int>      <int>          <dbl>     <dbl>      <dbl>
#>  1 lm        1        977       1024           1.46      1.58      0.688
#>  2 lm        2        972       1028           3.26      2.80      0.667
#>  3 lm        3       1014        986           5.14      4.96      0.697
#>  4 lm        4       1000       1000           6.96      6.39      0.656
#>  5 lm        5       1019        981           8.75      8.39      0.681
#>  6 rf        1        963       1038           1.34      1.41      0.685
#>  7 rf        2       1013        987           3.18      3.84      0.712
#>  8 rf        3        995       1005           5.16      5.14      0.693
#>  9 rf        4        968       1032           6.89      6.47      0.718
#> 10 rf        5       1043        957           8.71      7.53      0.683
r_results |>
  cate_cal_table(truth = spend, estimate = .pred_cate, treatment = emailed,
                 bins = 5)
#> # A tibble: 10 × 7
#>    model     .bin .n_treated .n_control .mean_estimate .observed .std_error
#>    <chr>    <int>      <int>      <int>          <dbl>     <dbl>      <dbl>
#>  1 mars_xgb     1        987       1014           1.38      2.21      0.547
#>  2 mars_xgb     2       1008        992           3.89      4.27      0.629
#>  3 mars_xgb     3       1010        990           5.90      6.53      0.634
#>  4 mars_xgb     4       1006        994           7.54      8.59      0.604
#>  5 mars_xgb     5       1014        986           9.97      9.75      0.400
#>  6 xgb_enet     1        994       1007           1.35      2.45      0.532
#>  7 xgb_enet     2        997       1003           3.88      4.04      0.638
#>  8 xgb_enet     3       1018        982           5.77      6.19      0.630
#>  9 xgb_enet     4       1000       1000           7.51      8.82      0.629
#> 10 xgb_enet     5       1016        984          10.2       9.92      0.401

Checking against the true effects

Because these campaigns are simulated, the estimates can also be compared with the true effects. The PEHE is yardstick’s rmse() with the true effect as the truth:

s_results |>
  rmse(truth = tau, estimate = .pred_cate)
#> # A tibble: 2 × 4
#>   model .metric .estimator .estimate
#>   <chr> <chr>   <chr>          <dbl>
#> 1 lm    rmse    standard      0.0951
#> 2 rf    rmse    standard      1.08
r_results |>
  rmse(truth = tau, estimate = .pred_cate)
#> # A tibble: 2 × 4
#>   model    .metric .estimator .estimate
#>   <chr>    <chr>   <chr>          <dbl>
#> 1 mars_xgb rmse    standard       0.510
#> 2 xgb_enet rmse    standard       0.393

What the scores say

On the simple campaign, the linear model wins clearly on PEHE. That is what the data calls for: the true effect is a straight line in recency, and the outcome is linear in all three features, so spend ~ (recency + history + newbie) * emailed is exactly the right model, while the random forest has to approximate it from the data. On the rich campaign, the boosted trees and elastic net combination comes closer to the true effects than the MARS and boosted trees one.

The Qini coefficients are much closer together than the PEHEs. They score only the order of the estimates, and even 10,000 test customers leave enough noise that small differences between them shouldn’t be over-read. Trying other base models is a one-argument change; telling them apart reliably takes a large test set.