# \donttest{
# Train a causal forest to estimate a CATE based priority ranking
n <- 1500
p <- 5
X <- matrix(rnorm(n * p), n, p)
W <- rbinom(n, 1, 0.5)
event.prob <- 1 / (1 + exp(2*(pmax(2*X[, 1], 0) * W - X[, 2])))
Y <- rbinom(n, 1, event.prob)
train <- sample(1:n, n / 2)
cf.priority <- causal_forest(X[train, ], Y[train], W[train])
# Compute a prioritization based on estimated treatment effects.
# -1: in this example the treatment should reduce the risk of an event occuring.
priority.cate <- -1 * predict(cf.priority, X[-train, ])$predictions
# Train a separate CATE estimator for the evaluation set.
Y.forest.eval <- regression_forest(X[-train, ], Y[-train], num.trees = 500)
Y.hat.eval <- predict(Y.forest.eval)$predictions
W.forest.eval <- regression_forest(X[-train, ], W[-train], num.trees = 500)
W.hat.eval <- predict(W.forest.eval)$predictions
cf.eval <- causal_forest(X[-train, ], Y[-train], W[-train],
Y.hat = Y.hat.eval,
W.hat = W.hat.eval)
# Compute doubly robust scores corresponding to a binary treatment (AIPW).
tau.hat.eval <- predict(cf.eval)$predictions
debiasing.weights.eval <- (W[-train] - W.hat.eval) / (W.hat.eval * (1 - W.hat.eval))
Y.residual.eval <- Y[-train] - (Y.hat.eval + tau.hat.eval * (W[-train] - W.hat.eval))
DR.scores <- tau.hat.eval + debiasing.weights.eval * Y.residual.eval
# Could equivalently be obtained by
# DR.scores <- get_scores(cf.eval)
# Estimate AUTOC.
rate <- rank_average_treatment_effect.fit(DR.scores, priority.cate)
# Same as
rank_average_treatment_effect(cf.eval, priority.cate)
# }
Run the code above in your browser using DataLab