Package 'tidycate'

Title: Causal Meta-Learners for 'tidymodels'
Description: Builds causal meta-learners from any 'tidymodels' workflow, so a model you would normally use for prediction, such as a boosted tree or random forest, can instead estimate how the effect of a binary treatment varies across individuals: the conditional average treatment effect (CATE). Implements the S-, T-, and X-learners described by Künzel et al. (2019) <doi:10.1073/pnas.1804597116>, the R-learner of Nie and Wager (2021) <doi:10.1093/biomet/asaa076>, and the doubly robust learner (DR-learner) of Kennedy (2023) <doi:10.1214/23-EJS2157>, for numeric and binary outcomes. The R- and DR-learners cross-fit their models automatically. Uplift metrics in the style of 'yardstick', such as the Qini coefficient described by Gutierrez and Gérardy (2017) <https://proceedings.mlr.press/v67/gutierrez17a.html>, check how well the estimated effects rank units on held-out data from a randomized experiment.
Authors: Jonah Rosenberg [aut, cre, cph]
Maintainer: Jonah Rosenberg <[email protected]>
License: MIT + file LICENSE
Version: 0.1.1
Built: 2026-12-04 19:58:23 UTC
Source: https://github.com/jonahrosenberg/tidycate

Help Index


Add estimated effects to data

Description

Returns new_data with each unit's estimated effect added as the first column, .pred_cate, ready for the uplift metrics such as qini_coef(). Works for every learner's fit.

Usage

## S3 method for class 'cate_fit'
augment(x, new_data, ...)

Arguments

x

A fitted learner, from fit() on any of s_learner(), t_learner(), x_learner(), r_learner(), or dr_learner().

new_data

A data frame with the predictors the learner needs (see its predict() method). It doesn't need the treatment column, but keep it, along with the outcome, to score the estimates.

...

Not currently used.

Value

A tibble: .pred_cate, followed by the columns of new_data.

See Also

Other uplift metrics: cate_cal_table(), qini_coef(), qini_curve(), uplift_at_k()

Examples

# A randomized email campaign: the email raises spending more for customers
# who bought recently
set.seed(1)
n <- 2000
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)
train <- emails[1:1000, ]
test <- emails[1001:2000, ]

wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())
fitted <- t_learner(wf) |>
  fit(data = train, treatment = emailed)

# Score the estimated effects on customers the learner wasn't fit on
scored <- augment(fitted, new_data = test)

qini_coef(scored, truth = spend, estimate = .pred_cate, treatment = emailed)
uplift_at_k(scored, truth = spend, estimate = .pred_cate, treatment = emailed)

# Both metrics at once
uplift_metrics <- yardstick::metric_set(qini_coef, uplift_at_k)
uplift_metrics(scored, truth = spend, estimate = .pred_cate, treatment = emailed)

# The curve, and whether the estimates match the observed effects
qini_curve(scored, truth = spend, estimate = .pred_cate, treatment = emailed)
cate_cal_table(scored, truth = spend, estimate = .pred_cate, treatment = emailed,
               bins = 5)

Calibration table for estimated effects

Description

Splits units into bins by their estimated effect and compares each bin's mean estimate with its observed effect, the difference between the mean outcomes of its treated and control units. If the estimates are well calibrated, the two are close in every bin. The Qini coefficient (qini_coef()) only checks the order of the estimates; this table also checks their size, which matters when a decision depends on how large an effect is (e.g., whether it is worth the cost of treating).

Usage

cate_cal_table(data, ...)

## S3 method for class 'data.frame'
cate_cal_table(
  data,
  truth,
  estimate,
  treatment,
  treated_level = NULL,
  event_level = "first",
  bins = 10,
  na_rm = TRUE,
  case_weights = NULL,
  ...
)

Arguments

data

A data frame with the observed outcome, the estimated effect, and the treatment, such as the output of augment() on a test set. For a grouped data frame, there is one result per group.

...

Not currently used.

truth

The observed outcome column, unquoted: numeric, or a factor with two levels for a binary outcome. For qini_coef_vec(), a vector.

estimate

The estimated effect column, unquoted, such as .pred_cate. For qini_coef_vec(), a numeric vector.

treatment

The treatment column, unquoted (e.g., treatment = emailed), coded as in fit(): numeric 0/1, logical, or a factor or character column with exactly two values. For qini_coef_vec(), a vector.

treated_level

For a factor or character treatment, the value that means treated. Required for those treatments and not allowed for 0/1 or TRUE/FALSE treatments, where 1 or TRUE means treated.

event_level

For a binary outcome, whether the "first" (default) or "second" level of truth is the event, following the yardstick convention. Effects are then differences in the share of units with the event. Ignored for numeric outcomes.

bins

The number of bins, a whole number (default 10). Bin 1 holds the smallest estimates.

na_rm

If TRUE (default), rows with a missing value in any of the three columns are dropped. If FALSE, missing values are an error.

case_weights

Not supported yet; must be NULL.

Details

Units are split into bins bins of equal size by their estimate, as dplyr::ntile() does. Units with the same estimate are then kept in the same bin (the lowest bin any of them landed in), so with ties some bins are larger than others, and there can be fewer bins than asked for: constant estimates give a single bin.

The standard error of a bin's observed effect is that of a difference in two means, sqrt(var(treated) / n_treated + var(control) / n_control). The observed effect is NA when a bin has no treated or no control units, and the standard error is NA when either group has fewer than two.

It makes the same assumptions as qini_coef(): a completely randomized experiment in which every unit had the same chance of being treated, scored on units the learner wasn't fit on. With small bins the observed effects are noisy, so compare the gaps with the standard errors.

Value

A tibble with one row per bin (for grouped data, the grouping columns come first):

  • .bin: the bin number, from 1 (smallest estimates) up.

  • .n_treated, .n_control: the number of treated and control units in the bin.

  • .mean_estimate: the bin's mean estimated effect.

  • .observed: the bin's observed effect, the treated units' mean outcome minus the control units'.

  • .std_error: the standard error of .observed.

See Also

Other uplift metrics: augment.cate_fit(), qini_coef(), qini_curve(), uplift_at_k()

Examples

# A randomized email campaign: the email raises spending more for customers
# who bought recently
set.seed(1)
n <- 2000
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)
train <- emails[1:1000, ]
test <- emails[1001:2000, ]

wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())
fitted <- t_learner(wf) |>
  fit(data = train, treatment = emailed)

# Score the estimated effects on customers the learner wasn't fit on
scored <- augment(fitted, new_data = test)

qini_coef(scored, truth = spend, estimate = .pred_cate, treatment = emailed)
uplift_at_k(scored, truth = spend, estimate = .pred_cate, treatment = emailed)

# Both metrics at once
uplift_metrics <- yardstick::metric_set(qini_coef, uplift_at_k)
uplift_metrics(scored, truth = spend, estimate = .pred_cate, treatment = emailed)

# The curve, and whether the estimates match the observed effects
qini_curve(scored, truth = spend, estimate = .pred_cate, treatment = emailed)
cate_cal_table(scored, truth = spend, estimate = .pred_cate, treatment = emailed,
               bins = 5)

Create a DR-learner

Description

The DR-learner (Kennedy, 2023), or doubly robust learner, estimates the conditional average treatment effect (CATE) in three steps:

Usage

dr_learner(outcome_model, effect_model = NULL, propensity)

Arguments

outcome_model

An unfitted workflows::workflow() that predicts the outcome from the features, without the treatment column. It is fit separately on the treated and the control units. Its model can be a regression (numeric outcome) or a classification with two classes (binary outcome).

effect_model

A parsnip model specification for the effect model, such as parsnip::linear_reg(), or NULL (default) to reuse outcome_model's model, with a warning. The effect model uses outcome_model's formula or recipe, so give only the model, not a workflow; the predictors are encoded the way the effect model expects (see fit.dr_learner()). Effects are numbers, so this must be a regression model; a specification with no mode set is set to regression, with a warning. Required when the outcome is binary.

propensity

Each unit's chance of being treated: a single number strictly between 0 and 1 when it is known (e.g., 0.5 in a 50/50 randomized experiment), or an unfitted classification workflows::workflow() that predicts the treatment column. There is no default.

Details

  1. Cross-fit the outcome model separately in each treatment group, so every unit gets two predicted outcomes, one if treated and one if control, and cross-fit the propensity, each unit's chance of being treated. Each unit's predictions come from models fit without it.

  2. Compute each unit's pseudo-outcome: the difference between its two predicted outcomes, plus a correction from its observed outcome, its residual from its own group's model divided by its chance of being in that group.

  3. Fit an effect model to the pseudo-outcomes.

The pseudo-outcome is doubly robust: averaged over units with the same features, it equals the true effect if either the outcome models or the propensity is correct. With a known propensity, as in a randomized experiment, the pseudo-outcomes are centered on the true effects however well the outcome models fit; better outcome models make them less noisy. They are still noisy, so a simpler effect model than the outcome model often works better.

Value

An unfitted dr_learner object, to be passed to fit().

References

Kennedy, E. H. (2023). Towards optimal doubly robust estimation of heterogeneous causal effects. Electronic Journal of Statistics, 17(2), 3008-3049. doi:10.1214/23-EJS2157

See Also

fit.dr_learner(), predict.dr_learner_fit(), r_learner(), t_learner()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The outcome model predicts spending without the treatment; it is fit
# separately on the emailed and the not-emailed customers
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

# The email was a 50/50 coin flip, so the propensity is known. fit() makes
# random cross-fitting folds, so set the seed for reproducible results.
set.seed(2)
fitted <- dr_learner(wf, effect_model = parsnip::linear_reg(), propensity = 0.5) |>
  fit(data = emails, treatment = emailed)
predict(fitted, new_data = head(emails))

# Or estimate the propensity with a classification workflow
propensity_wf <- workflows::workflow(emailed ~ recency, parsnip::logistic_reg())
set.seed(2)
estimated <- dr_learner(
  wf,
  effect_model = parsnip::linear_reg(),
  propensity = propensity_wf
) |>
  fit(data = emails, treatment = emailed)
predict(estimated, new_data = head(emails))

Fit a DR-learner

Description

Checks the treatment column and the workflows, cross-fits the outcome model in each treatment group and (if it is a workflow) the propensity, computes each unit's pseudo-outcome, and fits the effect model.

Usage

## S3 method for class 'dr_learner'
fit(
  object,
  data,
  treatment,
  treated_level = NULL,
  event_level = c("first", "second"),
  folds = 5,
  ...
)

Arguments

object

A dr_learner object from dr_learner().

data

A data frame with the outcome, the predictors, and the treatment.

treatment

The treatment column, unquoted (e.g., treatment = emailed). It can be numeric 0/1, logical, or a factor or character column with exactly two values.

treated_level

For a factor or character treatment, the value that means treated. Required for those treatments and not allowed for 0/1 or TRUE/FALSE treatments, where 1 or TRUE means treated.

event_level

For a binary outcome, whether the "first" (default) or "second" level of the outcome is the event whose probability the effect is about, following the yardstick convention. Ignored for numeric outcomes.

folds

The cross-fitting folds: a whole number of folds (default 5), made with rsample::vfold_cv() so that each fold has a similar share of treated units, or an rsample object built from data that holds out every row exactly once, such as one from rsample::vfold_cv() or rsample::group_vfold_cv(). Making folds uses the random number generator, so call set.seed() first for reproducible results.

...

Not currently used.

Details

Before any model is fit, fit() checks that the treatment doesn't reach the outcome model, as for fit.t_learner(): the outcome model is fit separately in each treatment group, where the treatment is the same for every unit. It also checks that a propensity workflow's outcome is the treatment column, that folds is valid, and that every fold's training rows (the other folds) include both treated and control units.

Cross-fitting: for each fold, the outcome model is fit on the other folds twice, once on their treated units and once on their control units, and both fits predict every unit in the fold. A propensity workflow is fit on the other folds too. A known propensity is used as is.

Each unit's pseudo-outcome is its predicted outcome if treated minus its predicted outcome if control, plus its residual from its own group's outcome model, divided by its propensity (treated units) or by 1 minus its propensity (control units). The effect model is fit to all units' pseudo-outcomes at once, without weights, so any engine can be used. (Kennedy, 2023, instead fits the effect model on a separate sample from the outcome and propensity models, optionally swapping the samples and averaging the two estimates.) fit() warns when any propensity is below 0.01 or above 0.99, since those units' pseudo-outcomes can be extreme, and stops if any is exactly 0 or 1. Propensities are never clipped.

The effect model uses the outcome model's formula or recipe, estimated on all of data with the effect model in place of the outcome model. A formula therefore encodes the predictors the way the effect model expects: dummy variables for a linear model or xgboost, factors left as they are for a random forest. New data is run through the same fitted preprocessing before the effect model predicts.

Each unit's pseudo-outcome is matched to its own row, so preprocessing that removes rows (such as recipes::step_naomit()) isn't supported: remove those rows from data first. Recipe steps on the outcome should use skip = TRUE, as recipes recommends. Avoid outcome steps that learn from the data, such as normalizing the outcome: they would be estimated within each fold for the predicted outcomes but on all of data for the observed outcomes.

A propensity workflow is a classification model, so it is fit with the treatment converted to a factor (as factor() would convert it). If it uses a recipe, create the recipe from data where the treatment is already a factor.

Value

A fitted dr_learner_fit object, to be passed to predict().

See Also

dr_learner(), predict.dr_learner_fit()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The outcome model predicts spending without the treatment; it is fit
# separately on the emailed and the not-emailed customers
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

# The email was a 50/50 coin flip, so the propensity is known. fit() makes
# random cross-fitting folds, so set the seed for reproducible results.
set.seed(2)
fitted <- dr_learner(wf, effect_model = parsnip::linear_reg(), propensity = 0.5) |>
  fit(data = emails, treatment = emailed)
predict(fitted, new_data = head(emails))

# Or estimate the propensity with a classification workflow
propensity_wf <- workflows::workflow(emailed ~ recency, parsnip::logistic_reg())
set.seed(2)
estimated <- dr_learner(
  wf,
  effect_model = parsnip::linear_reg(),
  propensity = propensity_wf
) |>
  fit(data = emails, treatment = emailed)
predict(estimated, new_data = head(emails))

Fit an R-learner

Description

Checks the treatment column and the workflows, cross-fits the outcome model and (if it is a workflow) the propensity, computes each unit's pseudo-outcome and weight, and fits the effect model.

Usage

## S3 method for class 'r_learner'
fit(
  object,
  data,
  treatment,
  treated_level = NULL,
  event_level = c("first", "second"),
  folds = 5,
  ...
)

Arguments

object

An r_learner object from r_learner().

data

A data frame with the outcome, the predictors, and the treatment.

treatment

The treatment column, unquoted (e.g., treatment = emailed). It can be numeric 0/1, logical, or a factor or character column with exactly two values.

treated_level

For a factor or character treatment, the value that means treated. Required for those treatments and not allowed for 0/1 or TRUE/FALSE treatments, where 1 or TRUE means treated.

event_level

For a binary outcome, whether the "first" (default) or "second" level of the outcome is the event whose probability the effect is about, following the yardstick convention. Ignored for numeric outcomes.

folds

The cross-fitting folds: a whole number of folds (default 5), made with rsample::vfold_cv() so that each fold has a similar share of treated units, or an rsample object built from data that holds out every row exactly once, such as one from rsample::vfold_cv() or rsample::group_vfold_cv(). Making folds uses the random number generator, so call set.seed() first for reproducible results.

...

Not currently used.

Details

Before any model is fit, fit() checks that the treatment doesn't reach the outcome model, as for fit.t_learner(): the outcome model predicts the outcome from the features alone, so that the treatment's effect is left in the residuals. It also checks that a propensity workflow's outcome is the treatment column, that the effect model's engine accepts case weights when they are needed, and that folds is valid.

Cross-fitting: for each fold, the outcome model (and a propensity workflow) is fit on the other folds and predicts the units in that fold. A known propensity is used as is.

Each unit's pseudo-outcome is its outcome residual divided by its treatment residual, and its weight is the squared treatment residual, rescaled so the weights average 1. With a propensity of 0.5 every weight is equal, so the effect model is fit without weights and any engine can be used; otherwise its engine must accept case weights. fit() warns when any propensity is below 0.01 or above 0.99, since those units' pseudo-outcomes can be extreme, and stops if any is exactly 0 or 1. Propensities are never clipped.

The effect model uses the outcome model's formula or recipe, estimated on all of data with the effect model in place of the outcome model. A formula therefore encodes the predictors the way the effect model expects: dummy variables for a linear model or xgboost, factors left as they are for a random forest. New data is run through the same fitted preprocessing before the effect model predicts.

Each unit's residual is matched to its own row, so preprocessing that removes rows (such as recipes::step_naomit()) isn't supported: remove those rows from data first. Recipe steps on the outcome should use skip = TRUE, as recipes recommends. Avoid outcome steps that learn from the data, such as normalizing the outcome: they would be estimated within each fold for the predicted outcomes but on all of data for the observed outcomes.

A propensity workflow is a classification model, so it is fit with the treatment converted to a factor (as factor() would convert it). If it uses a recipe, create the recipe from data where the treatment is already a factor.

Value

A fitted r_learner_fit object, to be passed to predict().

See Also

r_learner(), predict.r_learner_fit()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The outcome model predicts spending without the treatment
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

# The email was a 50/50 coin flip, so the propensity is known. fit() makes
# random cross-fitting folds, so set the seed for reproducible results.
set.seed(2)
fitted <- r_learner(wf, effect_model = parsnip::linear_reg(), propensity = 0.5) |>
  fit(data = emails, treatment = emailed)
predict(fitted, new_data = head(emails))

# Or estimate the propensity with a classification workflow
propensity_wf <- workflows::workflow(emailed ~ recency, parsnip::logistic_reg())
set.seed(2)
estimated <- r_learner(
  wf,
  effect_model = parsnip::linear_reg(),
  propensity = propensity_wf
) |>
  fit(data = emails, treatment = emailed)
predict(estimated, new_data = head(emails))

Fit an S-learner

Description

Checks the treatment column, checks that the outcome model uses the treatment as a predictor, and fits the outcome model on data.

Usage

## S3 method for class 's_learner'
fit(
  object,
  data,
  treatment,
  treated_level = NULL,
  event_level = c("first", "second"),
  ...
)

Arguments

object

An s_learner object from s_learner().

data

A data frame with the outcome, the predictors, and the treatment.

treatment

The treatment column, unquoted (e.g., treatment = emailed). It can be numeric 0/1, logical, or a factor or character column with exactly two values.

treated_level

For a factor or character treatment, the value that means treated. Required for those treatments and not allowed for 0/1 or TRUE/FALSE treatments, where 1 or TRUE means treated.

event_level

For a binary outcome, whether the "first" (default) or "second" level of the outcome is the event whose probability the effect is about, following the yardstick convention. Ignored for numeric outcomes.

...

Not currently used.

Details

Before the outcome model is fit, only the workflow's preprocessing (its formula or recipe) is run, and fit() stops if the treatment is not among the predictors or if preprocessing removed it. To check the second, the preprocessing is run on up to 1,000 rows twice, once with everyone treated and once with everyone in control: if the processed predictors are the same, the treatment was removed. This way a mistake is caught before a possibly slow model fit.

After fitting, a warning is given if flipping the treatment does not change any prediction on the training data. This means the model is ignoring the treatment (for example, a tree that never splits on it), so every estimated effect would be zero. To keep this cheap on large data, the first 1,000 rows are checked first, and the rest only if none of their predictions change, so every row is still checked before a warning is given.

Value

A fitted s_learner_fit object, to be passed to predict().

See Also

s_learner(), predict.s_learner_fit()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The interaction lets the estimated effect vary with recency
wf <- workflows::workflow(spend ~ recency * emailed, parsnip::linear_reg())

fitted <- s_learner(wf) |>
  fit(data = emails, treatment = emailed)

predict(fitted, new_data = head(emails))
predict(fitted, new_data = head(emails), type = "potential_outcomes")

Fit a T-learner

Description

Checks the treatment column, checks that the outcome model doesn't use the treatment as a predictor, and fits the outcome model separately on the treated and the control units.

Usage

## S3 method for class 't_learner'
fit(
  object,
  data,
  treatment,
  treated_level = NULL,
  event_level = c("first", "second"),
  ...
)

Arguments

object

A t_learner object from t_learner().

data

A data frame with the outcome, the predictors, and the treatment.

treatment

The treatment column, unquoted (e.g., treatment = emailed). It can be numeric 0/1, logical, or a factor or character column with exactly two values.

treated_level

For a factor or character treatment, the value that means treated. Required for those treatments and not allowed for 0/1 or TRUE/FALSE treatments, where 1 or TRUE means treated.

event_level

For a binary outcome, whether the "first" (default) or "second" level of the outcome is the event whose probability the effect is about, following the yardstick convention. Ignored for numeric outcomes.

...

Not currently used.

Details

Before any model is fit, only the workflow's preprocessing (its formula or recipe) is run, and fit() stops if the treatment would reach the model. To check, the preprocessing is run on up to 1,000 rows twice, once with everyone treated and once with everyone in control: if the processed predictors differ, the model would be using the treatment. Leave it out with a formula such as spend ~ . - emailed or a recipe step such as recipes::step_rm(emailed).

Value

A fitted t_learner_fit object, to be passed to predict().

See Also

t_learner(), predict.t_learner_fit()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The formula leaves out the treatment: fit() splits the data by it
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

fitted <- t_learner(wf) |>
  fit(data = emails, treatment = emailed)

predict(fitted, new_data = head(emails))
predict(fitted, new_data = head(emails), type = "potential_outcomes")

Fit an X-learner

Description

Checks the treatment column and the workflows, fits the outcome model in each treatment group, estimates each unit's effect, fits the effect model in each group, and fits the propensity workflow if one was given.

Usage

## S3 method for class 'x_learner'
fit(
  object,
  data,
  treatment,
  treated_level = NULL,
  event_level = c("first", "second"),
  ...
)

Arguments

object

An x_learner object from x_learner().

data

A data frame with the outcome, the predictors, and the treatment.

treatment

The treatment column, unquoted (e.g., treatment = emailed). It can be numeric 0/1, logical, or a factor or character column with exactly two values.

treated_level

For a factor or character treatment, the value that means treated. Required for those treatments and not allowed for 0/1 or TRUE/FALSE treatments, where 1 or TRUE means treated.

event_level

For a binary outcome, whether the "first" (default) or "second" level of the outcome is the event whose probability the effect is about, following the yardstick convention. Ignored for numeric outcomes.

...

Not currently used.

Details

Before any model is fit, fit() checks that the treatment doesn't reach the outcome model, as for fit.t_learner(), and that a propensity workflow's outcome is the treatment column.

The effect models use the outcome model's formula or recipe, estimated on each group's data with the effect model in place of the outcome model. A formula therefore encodes the predictors the way the effect model expects: dummy variables for a linear model or xgboost, factors left as they are for a random forest. So, for example, a random forest outcome model can be paired with an xgboost effect model. New data is run through the same fitted preprocessing before the effect models predict. The outcome column is never changed, so recipe steps on the outcome are safe. Because each unit's estimated effect is matched to its own row, preprocessing that removes rows (such as recipes::step_naomit()) isn't supported: remove those rows from data first.

A propensity workflow is a classification model, so it is fit with the treatment converted to a factor (as factor() would convert it). If it uses a recipe, create the recipe from data where the treatment is already a factor.

Value

A fitted x_learner_fit object, to be passed to predict().

See Also

x_learner(), predict.x_learner_fit()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The formula leaves out the treatment: fit() splits the data by it
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

# The email was a 50/50 coin flip, so the propensity is known
fitted <- x_learner(wf, effect_model = parsnip::linear_reg(), propensity = 0.5) |>
  fit(data = emails, treatment = emailed)
predict(fitted, new_data = head(emails))

# Or estimate the propensity with a classification workflow
propensity_wf <- workflows::workflow(emailed ~ recency, parsnip::logistic_reg())
estimated <- x_learner(
  wf,
  effect_model = parsnip::linear_reg(),
  propensity = propensity_wf
) |>
  fit(data = emails, treatment = emailed)
predict(estimated, new_data = head(emails))

Predict effects from a fitted DR-learner

Description

Predicts each unit's effect from the effect model. new_data needs only the outcome model's predictors: not the treatment column, and not the propensity workflow's predictors.

Usage

## S3 method for class 'dr_learner_fit'
predict(object, new_data, type = "cate", ...)

Arguments

object

A fitted dr_learner_fit object from fit().

new_data

A data frame of units to predict for. It does not need to contain the treatment column.

type

Only "cate" (default), the estimated effect. The DR-learner's effect model is fit directly to pseudo-outcomes, so it has no potential outcomes to return.

...

Not currently used.

Value

A tibble with one row per row of new_data and one column, .pred_cate. For a binary outcome, it is a difference in probabilities of the event level.

See Also

dr_learner(), fit.dr_learner()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The outcome model predicts spending without the treatment; it is fit
# separately on the emailed and the not-emailed customers
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

# The email was a 50/50 coin flip, so the propensity is known. fit() makes
# random cross-fitting folds, so set the seed for reproducible results.
set.seed(2)
fitted <- dr_learner(wf, effect_model = parsnip::linear_reg(), propensity = 0.5) |>
  fit(data = emails, treatment = emailed)
predict(fitted, new_data = head(emails))

# Or estimate the propensity with a classification workflow
propensity_wf <- workflows::workflow(emailed ~ recency, parsnip::logistic_reg())
set.seed(2)
estimated <- dr_learner(
  wf,
  effect_model = parsnip::linear_reg(),
  propensity = propensity_wf
) |>
  fit(data = emails, treatment = emailed)
predict(estimated, new_data = head(emails))

Predict effects from a fitted R-learner

Description

Predicts each unit's effect from the effect model. new_data needs only the outcome model's predictors: not the treatment column, and not the propensity workflow's predictors.

Usage

## S3 method for class 'r_learner_fit'
predict(object, new_data, type = "cate", ...)

Arguments

object

A fitted r_learner_fit object from fit().

new_data

A data frame of units to predict for. It does not need to contain the treatment column.

type

Only "cate" (default), the estimated effect. The R-learner's effect model is fit directly to pseudo-outcomes, so it has no potential outcomes to return.

...

Not currently used.

Value

A tibble with one row per row of new_data and one column, .pred_cate. For a binary outcome, it is a difference in probabilities of the event level.

See Also

r_learner(), fit.r_learner()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The outcome model predicts spending without the treatment
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

# The email was a 50/50 coin flip, so the propensity is known. fit() makes
# random cross-fitting folds, so set the seed for reproducible results.
set.seed(2)
fitted <- r_learner(wf, effect_model = parsnip::linear_reg(), propensity = 0.5) |>
  fit(data = emails, treatment = emailed)
predict(fitted, new_data = head(emails))

# Or estimate the propensity with a classification workflow
propensity_wf <- workflows::workflow(emailed ~ recency, parsnip::logistic_reg())
set.seed(2)
estimated <- r_learner(
  wf,
  effect_model = parsnip::linear_reg(),
  propensity = propensity_wf
) |>
  fit(data = emails, treatment = emailed)
predict(estimated, new_data = head(emails))

Predict effects from a fitted S-learner

Description

Predict effects from a fitted S-learner

Usage

## S3 method for class 's_learner_fit'
predict(object, new_data, type = c("cate", "potential_outcomes"), ...)

Arguments

object

A fitted s_learner_fit object from fit().

new_data

A data frame of units to predict for. It does not need to contain the treatment column.

type

"cate" (default) for the estimated effect, or "potential_outcomes" for the predicted outcome under control and under treatment.

...

Not currently used.

Value

A tibble with one row per row of new_data: a .pred_cate column for type = "cate", or .pred_control and .pred_treated columns for type = "potential_outcomes". For binary outcomes these are probabilities of the event level, so .pred_cate is a difference in probabilities.

See Also

s_learner(), fit.s_learner()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The interaction lets the estimated effect vary with recency
wf <- workflows::workflow(spend ~ recency * emailed, parsnip::linear_reg())

fitted <- s_learner(wf) |>
  fit(data = emails, treatment = emailed)

predict(fitted, new_data = head(emails))
predict(fitted, new_data = head(emails), type = "potential_outcomes")

Predict effects from a fitted T-learner

Description

Each unit's outcome is predicted by both treatment groups' models, so new_data doesn't need the treatment column.

Usage

## S3 method for class 't_learner_fit'
predict(object, new_data, type = c("cate", "potential_outcomes"), ...)

Arguments

object

A fitted t_learner_fit object from fit().

new_data

A data frame of units to predict for. It does not need to contain the treatment column.

type

"cate" (default) for the estimated effect, or "potential_outcomes" for the predicted outcome under control and under treatment.

...

Not currently used.

Value

A tibble with one row per row of new_data: a .pred_cate column for type = "cate", or .pred_control and .pred_treated columns for type = "potential_outcomes". For binary outcomes these are probabilities of the event level, so .pred_cate is a difference in probabilities.

See Also

t_learner(), fit.t_learner()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The formula leaves out the treatment: fit() splits the data by it
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

fitted <- t_learner(wf) |>
  fit(data = emails, treatment = emailed)

predict(fitted, new_data = head(emails))
predict(fitted, new_data = head(emails), type = "potential_outcomes")

Predict effects from a fitted X-learner

Description

Combines the two treatment groups' effect models, weighting the control group's by the propensity. new_data doesn't need the treatment column, but it needs the propensity workflow's predictors if the propensity was estimated.

Usage

## S3 method for class 'x_learner_fit'
predict(object, new_data, type = "cate", ...)

Arguments

object

A fitted x_learner_fit object from fit().

new_data

A data frame of units to predict for. It does not need to contain the treatment column.

type

Only "cate" (default), the estimated effect. The X-learner's estimate combines two effect models rather than subtracting two predicted outcomes, so it has no potential outcomes to return.

...

Not currently used.

Value

A tibble with one row per row of new_data and one column, .pred_cate. For a binary outcome, it is a difference in probabilities of the event level.

See Also

x_learner(), fit.x_learner()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The formula leaves out the treatment: fit() splits the data by it
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

# The email was a 50/50 coin flip, so the propensity is known
fitted <- x_learner(wf, effect_model = parsnip::linear_reg(), propensity = 0.5) |>
  fit(data = emails, treatment = emailed)
predict(fitted, new_data = head(emails))

# Or estimate the propensity with a classification workflow
propensity_wf <- workflows::workflow(emailed ~ recency, parsnip::logistic_reg())
estimated <- x_learner(
  wf,
  effect_model = parsnip::linear_reg(),
  propensity = propensity_wf
) |>
  fit(data = emails, treatment = emailed)
predict(estimated, new_data = head(emails))

Qini coefficient

Description

The Qini coefficient measures how well estimated effects rank units: do the units with the highest estimated effects really gain the most from treatment? It is the area between the Qini curve (qini_curve()) and the line a random ranking would give. It needs only the observed outcomes, not the true effects, so it works on real data.

Usage

qini_coef(data, ...)

## S3 method for class 'data.frame'
qini_coef(
  data,
  truth,
  estimate,
  treatment,
  treated_level = NULL,
  event_level = "first",
  na_rm = TRUE,
  case_weights = NULL,
  ...
)

qini_coef_vec(
  truth,
  estimate,
  treatment,
  treated_level = NULL,
  event_level = "first",
  na_rm = TRUE,
  case_weights = NULL,
  ...
)

Arguments

data

A data frame with the observed outcome, the estimated effect, and the treatment, such as the output of augment() on a test set. For a grouped data frame, there is one result per group.

...

Not currently used.

truth

The observed outcome column, unquoted: numeric, or a factor with two levels for a binary outcome. For qini_coef_vec(), a vector.

estimate

The estimated effect column, unquoted, such as .pred_cate. For qini_coef_vec(), a numeric vector.

treatment

The treatment column, unquoted (e.g., treatment = emailed), coded as in fit(): numeric 0/1, logical, or a factor or character column with exactly two values. For qini_coef_vec(), a vector.

treated_level

For a factor or character treatment, the value that means treated. Required for those treatments and not allowed for 0/1 or TRUE/FALSE treatments, where 1 or TRUE means treated.

event_level

For a binary outcome, whether the "first" (default) or "second" level of truth is the event, following the yardstick convention. Effects are then differences in the share of units with the event. Ignored for numeric outcomes.

na_rm

If TRUE (default), rows with a missing value in any of the three columns are dropped. If FALSE, missing values make the result NA.

case_weights

Not supported yet; must be NULL.

Details

The Qini curve sorts units by their estimated effect, highest first. For each share of units at the top of that list, its height is the gain per unit on the whole list from treating only that top group: the difference between the mean outcome of the treated and the control units in the top group, times the share. The random line runs straight from the start of the curve, ⁠(0, 0)⁠, to its end, where everyone is treated and the height is the overall difference in means. The Qini coefficient is the area between the two, computed with the trapezoid rule, so it is in the outcome's units per unit (e.g., dollars per customer).

A positive value means the ranking beats a random one, and constant estimates give 0. The best possible value depends on the data, so compare learners on the same data and outcome only. Unlike some Python packages (causalml, scikit-uplift), the coefficient isn't divided by the area of a perfect ranking's curve, and the curve is the uplift curve of Gutierrez and Gérardy (2017), which is not affected by the share of units treated, so values won't match theirs.

The observed outcomes only reveal effects when the treatment was assigned at random: the Qini coefficient assumes a completely randomized experiment in which every unit had the same chance of being treated (any chance, e.g., 50%). Score units the learner wasn't fit on, such as a test set.

The coefficient is noisy: with a few hundred units, its sampling error can be larger than the differences between learners, and even a random ranking can score well. Standard errors aren't available yet; to see how much the coefficient varies, compute it on bootstrap samples of the test set (e.g., with rsample::bootstraps()).

qini_coef() and uplift_at_k() are yardstick metrics, so they can be combined with yardstick::metric_set(), which passes treatment and treated_level on to them. Other metrics in the same set, such as yardstick::rmse(), ignore the treatment.

A group of grouped data that lacks treated or control units gets NA, with a warning.

Value

For qini_coef(), a tibble with columns .metric, .estimator, and .estimate, and one row (one per group for grouped data). For qini_coef_vec(), a single number.

References

Gutierrez, P., & Gérardy, J.-Y. (2017). Causal inference and uplift modelling: A review of the literature. Proceedings of Machine Learning Research, 67, 1-13. https://proceedings.mlr.press/v67/gutierrez17a.html

Radcliffe, N. J., & Surry, P. D. (2011). Real-world uplift modelling with significance-based uplift trees (White paper TR-2011-1). Stochastic Solutions.

See Also

Other uplift metrics: augment.cate_fit(), cate_cal_table(), qini_curve(), uplift_at_k()

Examples

# A randomized email campaign: the email raises spending more for customers
# who bought recently
set.seed(1)
n <- 2000
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)
train <- emails[1:1000, ]
test <- emails[1001:2000, ]

wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())
fitted <- t_learner(wf) |>
  fit(data = train, treatment = emailed)

# Score the estimated effects on customers the learner wasn't fit on
scored <- augment(fitted, new_data = test)

qini_coef(scored, truth = spend, estimate = .pred_cate, treatment = emailed)
uplift_at_k(scored, truth = spend, estimate = .pred_cate, treatment = emailed)

# Both metrics at once
uplift_metrics <- yardstick::metric_set(qini_coef, uplift_at_k)
uplift_metrics(scored, truth = spend, estimate = .pred_cate, treatment = emailed)

# The curve, and whether the estimates match the observed effects
qini_curve(scored, truth = spend, estimate = .pred_cate, treatment = emailed)
cate_cal_table(scored, truth = spend, estimate = .pred_cate, treatment = emailed,
               bins = 5)

Qini curve

Description

The Qini curve shows, for each share of units treated in order of their estimated effects (highest first), the estimated gain per unit on the whole list. The area between it and a random ranking's line is the Qini coefficient (qini_coef()).

Usage

qini_curve(data, ...)

## S3 method for class 'data.frame'
qini_curve(
  data,
  truth,
  estimate,
  treatment,
  treated_level = NULL,
  event_level = "first",
  na_rm = TRUE,
  case_weights = NULL,
  ...
)

Arguments

data

A data frame with the observed outcome, the estimated effect, and the treatment, such as the output of augment() on a test set. For a grouped data frame, there is one result per group.

...

Not currently used.

truth

The observed outcome column, unquoted: numeric, or a factor with two levels for a binary outcome. For qini_coef_vec(), a vector.

estimate

The estimated effect column, unquoted, such as .pred_cate. For qini_coef_vec(), a numeric vector.

treatment

The treatment column, unquoted (e.g., treatment = emailed), coded as in fit(): numeric 0/1, logical, or a factor or character column with exactly two values. For qini_coef_vec(), a vector.

treated_level

For a factor or character treatment, the value that means treated. Required for those treatments and not allowed for 0/1 or TRUE/FALSE treatments, where 1 or TRUE means treated.

event_level

For a binary outcome, whether the "first" (default) or "second" level of truth is the event, following the yardstick convention. Effects are then differences in the share of units with the event. Ignored for numeric outcomes.

na_rm

If TRUE (default), rows with a missing value in any of the three columns are dropped. If FALSE, missing values are an error.

case_weights

Not supported yet; must be NULL.

Details

Units with the same estimate enter the curve together, so there is one point per distinct estimate. A point where the top group lacks treated or control units has no observed difference, so it is left out. See qini_coef() for how the curve is defined and what it assumes.

A random ranking's line is .share times the curve's last .gain, the overall difference in means.

Value

A tibble of class qini_df, with one row per point, from the start of the curve to its end (for grouped data, the grouping columns come first):

  • .threshold: the lowest estimate in the top group (Inf at the start, where no unit is treated).

  • .n_treated, .n_control: the number of treated and control units in the top group.

  • .share: the share of all units in the top group.

  • .gain: the gain per unit on the whole list from treating the top group: the difference between the treated and control units' mean outcomes in the top group, times .share.

See Also

Other uplift metrics: augment.cate_fit(), cate_cal_table(), qini_coef(), uplift_at_k()

Examples

# A randomized email campaign: the email raises spending more for customers
# who bought recently
set.seed(1)
n <- 2000
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)
train <- emails[1:1000, ]
test <- emails[1001:2000, ]

wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())
fitted <- t_learner(wf) |>
  fit(data = train, treatment = emailed)

# Score the estimated effects on customers the learner wasn't fit on
scored <- augment(fitted, new_data = test)

qini_coef(scored, truth = spend, estimate = .pred_cate, treatment = emailed)
uplift_at_k(scored, truth = spend, estimate = .pred_cate, treatment = emailed)

# Both metrics at once
uplift_metrics <- yardstick::metric_set(qini_coef, uplift_at_k)
uplift_metrics(scored, truth = spend, estimate = .pred_cate, treatment = emailed)

# The curve, and whether the estimates match the observed effects
qini_curve(scored, truth = spend, estimate = .pred_cate, treatment = emailed)
cate_cal_table(scored, truth = spend, estimate = .pred_cate, treatment = emailed,
               bins = 5)

Create an R-learner

Description

The R-learner (Nie and Wager, 2021) estimates the conditional average treatment effect (CATE) from residuals, in three steps:

Usage

r_learner(outcome_model, effect_model = NULL, propensity)

Arguments

outcome_model

An unfitted workflows::workflow() that predicts the outcome from the features, without the treatment column. Its model can be a regression (numeric outcome) or a classification with two classes (binary outcome).

effect_model

A parsnip model specification for the effect model, such as parsnip::linear_reg(), or NULL (default) to reuse outcome_model's model, with a warning. The effect model uses outcome_model's formula or recipe, so give only the model, not a workflow; the predictors are encoded the way the effect model expects (see fit.r_learner()). Effects are numbers, so this must be a regression model; a specification with no mode set is set to regression, with a warning. Required when the outcome is binary. Its engine must accept case weights unless propensity is 0.5.

propensity

Each unit's chance of being treated: a single number strictly between 0 and 1 when it is known (e.g., 0.5 in a 50/50 randomized experiment), or an unfitted classification workflows::workflow() that predicts the treatment column. There is no default.

Details

  1. Cross-fit two models: the outcome model, which predicts the outcome from the features alone (without the treatment), and the propensity, each unit's chance of being treated. Each unit's predictions come from models fit without it.

  2. Compute each unit's residuals: its outcome minus the predicted outcome, and its treatment (1 or 0) minus its propensity. Their ratio, the pseudo-outcome, is the unit's effect plus noise.

  3. Fit an effect model to the pseudo-outcomes, weighting each unit by its squared treatment residual. This minimizes the R-loss, the squared error of predicting the outcome residual from the effect times the treatment residual.

Subtracting the predicted outcome removes the part of the outcome that doesn't depend on the treatment, which makes the pseudo-outcomes much less noisy, and working with residuals makes the estimated effects less sensitive to errors in the outcome and propensity models. The pseudo-outcomes are still noisy, so a simpler effect model than the outcome model often works better.

Value

An unfitted r_learner object, to be passed to fit().

References

Nie, X., & Wager, S. (2021). Quasi-oracle estimation of heterogeneous treatment effects. Biometrika, 108(2), 299-319. doi:10.1093/biomet/asaa076

See Also

fit.r_learner(), predict.r_learner_fit(), x_learner(), dr_learner()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The outcome model predicts spending without the treatment
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

# The email was a 50/50 coin flip, so the propensity is known. fit() makes
# random cross-fitting folds, so set the seed for reproducible results.
set.seed(2)
fitted <- r_learner(wf, effect_model = parsnip::linear_reg(), propensity = 0.5) |>
  fit(data = emails, treatment = emailed)
predict(fitted, new_data = head(emails))

# Or estimate the propensity with a classification workflow
propensity_wf <- workflows::workflow(emailed ~ recency, parsnip::logistic_reg())
set.seed(2)
estimated <- r_learner(
  wf,
  effect_model = parsnip::linear_reg(),
  propensity = propensity_wf
) |>
  fit(data = emails, treatment = emailed)
predict(estimated, new_data = head(emails))

Create an S-learner

Description

The S-learner ("single" learner) estimates the conditional average treatment effect (CATE) with one outcome model that uses the treatment as a predictor. Each unit's outcome is predicted twice, once as treated and once as control, and the difference is the estimated effect.

Usage

s_learner(outcome_model)

Arguments

outcome_model

An unfitted workflows::workflow() whose predictors include the treatment column. Its model can be a regression (numeric outcome) or a classification with two classes (binary outcome).

Details

Because the treatment is just one predictor, the estimated effects can only vary across units if the outcome model lets the treatment interact with other predictors. A linear model needs explicit interaction terms (e.g., spend ~ (recency + history) * emailed); tree-based models can find interactions on their own but may rarely split on the treatment, which pulls the estimated effects toward zero.

Value

An unfitted s_learner object, to be passed to fit().

References

Künzel, S. R., Sekhon, J. S., Bickel, P. J., & Yu, B. (2019). Metalearners for estimating heterogeneous treatment effects using machine learning. Proceedings of the National Academy of Sciences, 116(10), 4156-4165. doi:10.1073/pnas.1804597116

See Also

fit.s_learner(), predict.s_learner_fit(), x_learner()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The interaction lets the estimated effect vary with recency
wf <- workflows::workflow(spend ~ recency * emailed, parsnip::linear_reg())

fitted <- s_learner(wf) |>
  fit(data = emails, treatment = emailed)

predict(fitted, new_data = head(emails))
predict(fitted, new_data = head(emails), type = "potential_outcomes")

Create a T-learner

Description

The T-learner ("two" learners) estimates the conditional average treatment effect (CATE) by fitting the same outcome model twice: once on the treated units and once on the control units. Each unit's outcome is predicted by both models, and the difference is the estimated effect.

Usage

t_learner(outcome_model)

Arguments

outcome_model

An unfitted workflows::workflow() whose predictors don't include the treatment column. Its model can be a regression (numeric outcome) or a classification with two classes (binary outcome).

Details

Each model is fit within one treatment group, where the treatment is the same for every row, so the outcome model must not use the treatment as a predictor. Because the two models are separate, every part of the model can differ between the groups, and the estimated effects can vary across units without any interaction terms. The trade-off is that each model only sees part of the data, so the estimates can be noisy when one group is small.

Value

An unfitted t_learner object, to be passed to fit().

References

Künzel, S. R., Sekhon, J. S., Bickel, P. J., & Yu, B. (2019). Metalearners for estimating heterogeneous treatment effects using machine learning. Proceedings of the National Academy of Sciences, 116(10), 4156-4165. doi:10.1073/pnas.1804597116

See Also

fit.t_learner(), predict.t_learner_fit(), s_learner(), x_learner()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The formula leaves out the treatment: fit() splits the data by it
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

fitted <- t_learner(wf) |>
  fit(data = emails, treatment = emailed)

predict(fitted, new_data = head(emails))
predict(fitted, new_data = head(emails), type = "potential_outcomes")

Uplift at k

Description

Uplift at k is the observed effect among the units with the highest estimated effects: the difference between the mean outcomes of the treated and the control units in the top share k (by default, the top 30%). It answers "if we treated only the top 30%, how much would treatment raise their outcome, on average?" Like qini_coef(), it needs only the observed outcomes, so it works on real data.

Usage

uplift_at_k(data, ...)

## S3 method for class 'data.frame'
uplift_at_k(
  data,
  truth,
  estimate,
  treatment,
  k = 0.3,
  treated_level = NULL,
  event_level = "first",
  na_rm = TRUE,
  case_weights = NULL,
  ...
)

uplift_at_k_vec(
  truth,
  estimate,
  treatment,
  k = 0.3,
  treated_level = NULL,
  event_level = "first",
  na_rm = TRUE,
  case_weights = NULL,
  ...
)

Arguments

data

A data frame with the observed outcome, the estimated effect, and the treatment, such as the output of augment() on a test set. For a grouped data frame, there is one result per group.

...

Not currently used.

truth

The observed outcome column, unquoted: numeric, or a factor with two levels for a binary outcome. For uplift_at_k_vec(), a vector.

estimate

The estimated effect column, unquoted, such as .pred_cate. For uplift_at_k_vec(), a numeric vector.

treatment

The treatment column, unquoted (e.g., treatment = emailed), coded as in fit(): numeric 0/1, logical, or a factor or character column with exactly two values. For uplift_at_k_vec(), a vector.

k

The share of units at the top of the ranking, a number above 0 and at most 1 (default 0.3, the top 30%).

treated_level

For a factor or character treatment, the value that means treated. Required for those treatments and not allowed for 0/1 or TRUE/FALSE treatments, where 1 or TRUE means treated.

event_level

For a binary outcome, whether the "first" (default) or "second" level of truth is the event, following the yardstick convention. Effects are then differences in the share of units with the event. Ignored for numeric outcomes.

na_rm

If TRUE (default), rows with a missing value in any of the three columns are dropped. If FALSE, missing values make the result NA.

case_weights

Not supported yet; must be NULL.

Details

The top group is the ceiling(k * n) units with the highest estimates, taken from all units at once (treated and control together), plus any units tied with the last one in, so it can be a little larger. If it has no treated or no control units, the result is NA, with a warning.

Uplift at k is an effect per unit in the top group. The Qini curve's height at share k (qini_curve()) is about the same effect times k: the gain spread over every unit on the list.

It makes the same assumptions as qini_coef() (a completely randomized experiment in which every unit had the same chance of being treated, scored on units the learner wasn't fit on) and is just as noisy on small test sets: the top 30% of 500 units is only 150 units. It can be combined with qini_coef() in yardstick::metric_set(); k is then passed on to it too.

Value

For uplift_at_k(), a tibble with columns .metric, .estimator, and .estimate, and one row (one per group for grouped data). For uplift_at_k_vec(), a single number.

See Also

Other uplift metrics: augment.cate_fit(), cate_cal_table(), qini_coef(), qini_curve()

Examples

# A randomized email campaign: the email raises spending more for customers
# who bought recently
set.seed(1)
n <- 2000
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)
train <- emails[1:1000, ]
test <- emails[1001:2000, ]

wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())
fitted <- t_learner(wf) |>
  fit(data = train, treatment = emailed)

# Score the estimated effects on customers the learner wasn't fit on
scored <- augment(fitted, new_data = test)

qini_coef(scored, truth = spend, estimate = .pred_cate, treatment = emailed)
uplift_at_k(scored, truth = spend, estimate = .pred_cate, treatment = emailed)

# Both metrics at once
uplift_metrics <- yardstick::metric_set(qini_coef, uplift_at_k)
uplift_metrics(scored, truth = spend, estimate = .pred_cate, treatment = emailed)

# The curve, and whether the estimates match the observed effects
qini_curve(scored, truth = spend, estimate = .pred_cate, treatment = emailed)
cate_cal_table(scored, truth = spend, estimate = .pred_cate, treatment = emailed,
               bins = 5)

Create an X-learner

Description

The X-learner estimates the conditional average treatment effect (CATE) in four steps:

Usage

x_learner(outcome_model, effect_model = NULL, propensity)

Arguments

outcome_model

An unfitted workflows::workflow() whose predictors don't include the treatment column. Its model can be a regression (numeric outcome) or a classification with two classes (binary outcome).

effect_model

A parsnip model specification for the effect models, such as parsnip::linear_reg(), or NULL (default) to reuse outcome_model's model, with a warning. The effect models use outcome_model's formula or recipe, so give only the model, not a workflow; the predictors are encoded the way the effect model expects (see fit.x_learner()). Estimated effects are numbers, so this must be a regression model; a specification with no mode set is set to regression, with a warning. Required when the outcome is binary.

propensity

Each unit's chance of being treated: a single number strictly between 0 and 1 when it is known (e.g., 0.5 in a 50/50 randomized experiment), or an unfitted classification workflows::workflow() that predicts the treatment column. There is no default.

Details

  1. Fit the outcome model separately on the treated and the control units, as in the T-learner.

  2. Estimate each unit's own effect from its observed outcome and the other group's prediction for it: observed minus predicted for treated units, and predicted minus observed for control units.

  3. Fit an effect model to those estimated effects, separately in each group.

  4. Combine the two effect models' predictions, weighting the control group's effect model by the propensity (each unit's chance of being treated) and the treated group's by one minus the propensity.

The control group's effect model is built from the treated group's outcome model, so when few units are treated, that outcome model is the noisy one and the propensity gives it little weight. The effect models can also be simpler than the outcome model, which helps when the effect is simpler than the outcome itself.

Value

An unfitted x_learner object, to be passed to fit().

References

Künzel, S. R., Sekhon, J. S., Bickel, P. J., & Yu, B. (2019). Metalearners for estimating heterogeneous treatment effects using machine learning. Proceedings of the National Academy of Sciences, 116(10), 4156-4165. doi:10.1073/pnas.1804597116

See Also

fit.x_learner(), predict.x_learner_fit(), t_learner(), r_learner(), dr_learner()

Examples

# A small randomized email campaign: the email raises spending more for
# customers who bought recently
set.seed(1)
n <- 200
recency <- sample(1:12, n, replace = TRUE)
emailed <- rbinom(n, size = 1, prob = 0.5)
spend <- 20 - recency + emailed * (10 - 0.75 * recency) + rnorm(n, sd = 5)
emails <- data.frame(recency, emailed, spend)

# The formula leaves out the treatment: fit() splits the data by it
wf <- workflows::workflow(spend ~ recency, parsnip::linear_reg())

# The email was a 50/50 coin flip, so the propensity is known
fitted <- x_learner(wf, effect_model = parsnip::linear_reg(), propensity = 0.5) |>
  fit(data = emails, treatment = emailed)
predict(fitted, new_data = head(emails))

# Or estimate the propensity with a classification workflow
propensity_wf <- workflows::workflow(emailed ~ recency, parsnip::logistic_reg())
estimated <- x_learner(
  wf,
  effect_model = parsnip::linear_reg(),
  propensity = propensity_wf
) |>
  fit(data = emails, treatment = emailed)
predict(estimated, new_data = head(emails))