# Quick Start Guide: Optimal Policy Trees with Categorical Treatment

In this guide we will give a demonstration of how to use Optimal Policy Trees with categoric treatment options. For this example, we will use the Credit Approval dataset, where the task is to predict the approval outcome of credit card application. Because the features have been anonymized for confidentiality reasons, we will arbitrarily select one of the categoric variables `A1`

to be the treatment.

*Note: this case is not intended to serve as a practical application of policy trees, but rather to serve as an illustration of the training and evaluation process.*

First we load in the data and drop 37 rows with missing values:

```
using CSV, DataFrames
df = CSV.read("crx.data", DataFrame, header=string.("A", 1:16),
missingstring="?", pool=true)
dropmissing!(df)
```

```
653×16 DataFrame
Row │ A1 A2 A3 A4 A5 A6 A7 A8 A9 ⋯
│ String Float64 Float64 String String String String Float64 Stri ⋯
─────┼──────────────────────────────────────────────────────────────────────────
1 │ b 30.83 0.0 u g w v 1.25 t ⋯
2 │ a 58.67 4.46 u g q h 3.04 t
3 │ a 24.5 0.5 u g q h 1.5 t
4 │ b 27.83 1.54 u g w v 3.75 t
5 │ b 20.17 5.625 u g w v 1.71 t ⋯
6 │ b 32.08 4.0 u g m v 2.5 t
7 │ b 33.17 1.04 u g r h 6.5 t
8 │ a 22.92 11.585 u g cc v 0.04 t
⋮ │ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋱
647 │ b 36.42 0.75 y p d v 0.585 f ⋯
648 │ b 40.58 3.29 u g m v 3.5 f
649 │ b 21.08 10.085 y p e h 1.25 f
650 │ a 22.67 0.75 u g c v 2.0 f
651 │ a 25.25 13.5 y p ff ff 2.0 f ⋯
652 │ b 17.92 0.205 u g aa v 0.04 f
653 │ b 35.0 3.375 u g c h 8.29 f
8 columns and 638 rows omitted
```

Policy trees are trained using a features matrix/dataframe `X`

as usual and a rewards matrix that has one column for each potential treatment that contains the outcome for each sample under that treatment.

There are two ways to get this rewards matrix:

- in rare cases, the problem may have full information about the outcome associated with each treatment for each sample
- more commonly, we have observational data, and use this partial data to train models to estimate the outcome associated with each treatment

Refer to the documentation on data preparation for more information on the data format.

In this case, the dataset is observational, and so we will use RewardEstimation to estimate our rewards matrix.

## Reward Estimation

First, we split into training and testing:

```
X = select(df, Not([:A16, :A1]))
treatments = df.A1
outcomes = df.A16 .== "+"
(train_X, train_treatments, train_outcomes), (test_X, test_treatments, test_outcomes) =
IAI.split_data(:policy_maximize, X, treatments, outcomes, seed=123, train_proportion=0.5)
```

Note that we have used a training/test split of 50%/50%, so that we save more data for testing to ensure high-quality reward estimation on the test set.

The treatment, `A1`

, is a categoric variable, so we follow the process for estimating rewards with categorical treatments.

Our outcome is binary, so we use a `CategoricalClassificationRewardEstimator`

to estimate the approval outcome under each option with a doubly-robust reward estimation method, using random forests to estimate both propensity scores and outcomes:

```
reward_lnr = IAI.CategoricalClassificationRewardEstimator(
propensity_estimator=IAI.RandomForestClassifier(),
outcome_estimator=IAI.RandomForestClassifier(),
reward_estimator=:doubly_robust,
random_seed=123,
)
train_predictions, train_reward_score = IAI.fit_predict!(
reward_lnr, train_X, train_treatments, train_outcomes,
propensity_score_criterion=:auc, outcome_score_criterion=:auc)
train_rewards = train_predictions[:reward]
```

```
326×2 DataFrame
Row │ a b
│ Float64 Float64
─────┼─────────────────────────
1 │ 1.15976 0.98
2 │ 0.5 1.00344
3 │ 0.4 1.2675
4 │ 0.6 1.06756
5 │ 1.26167 0.78
6 │ 0.3 1.07548
7 │ 0.7 1.04999
8 │ 0.03 1.1795
⋮ │ ⋮ ⋮
320 │ 0.15 -0.0558113
321 │ -0.0890725 0.2
322 │ -0.0535708 0.062
323 │ 0.07 -0.0463153
324 │ 0.25 -0.12907
325 │ 0.17 -0.144786
326 │ -2.00795 0.26
311 rows omitted
```

`train_reward_score`

```
Dict{Symbol, Any} with 2 entries:
:propensity => 0.606593
:outcome => Dict("b"=>0.923372, "a"=>0.956213)
```

We can see that the internal outcome estimation models have AUCs of 0.92 and 0.96, which gives us confidence that the reward estimates are of decent quality, and good to base our training on. The AUC for the propensity model is lower at 0.61, which is not particularly high, and suggests difficulty in reliably estimating the propensity. The doubly-robust estimation method should help to alleviate this problem, as it is designed to deliver good results if either propensity scores or outcomes are estimated well. However, we should always pay attention to these scores and proceed with caution if the estimation quality is low.

## Optimal Policy Trees

Now that we have a complete rewards matrix, we can train a tree to learn an optimal prescription policy that maximizes credit approval outcome. We will use a `GridSearch`

to fit an `OptimalTreePolicyMaximizer`

(note that if we were trying to minimize the outcomes, we would use `OptimalTreePolicyMinimizer`

):

```
grid = IAI.GridSearch(
IAI.OptimalTreePolicyMaximizer(
random_seed=121,
max_categoric_levels_before_warning=20,
),
max_depth=1:5,
)
IAI.fit!(grid, train_X, train_rewards)
```

```
Fitted OptimalTreePolicyMaximizer:
1) Split: A6 in [d,e,ff,i,k,m,q,r]
2) Split: A11 < 3.5
3) Prescribe: b, 128 points, error 5.442
4) Prescribe: a, 37 points, error 4.912
5) Split: A8 < 1.438
6) Prescribe: a, 83 points, error 5.259
7) Prescribe: b, 78 points, error 5.048
```

The resulting tree recommends different values for `A1`

based on other characteristics: namely, the values of `A6`

, `A8`

, and `A11`

. The intensity of the color in each leaf shows the difference in quality between the best and second-best values. We can see that both `a`

and `b`

values are prescribed by the tree, implying each treatment is better suited to certain subgroups.

We can make treatment prescriptions using `predict`

:

`IAI.predict(grid, train_X)`

```
326-element Vector{String}:
"a"
"b"
"b"
"b"
"a"
"b"
"b"
"b"
"b"
"b"
⋮
"a"
"b"
"b"
"b"
"a"
"b"
"b"
"b"
"b"
```

If we want more information about the relative performance of treatments for these points, we can predict the full treatment ranking with `predict_treatment_rank`

:

`IAI.predict_treatment_rank(grid, train_X)`

```
326×2 Matrix{String}:
"a" "b"
"b" "a"
"b" "a"
"b" "a"
"a" "b"
"b" "a"
"b" "a"
"b" "a"
"b" "a"
"b" "a"
⋮
"a" "b"
"b" "a"
"b" "a"
"b" "a"
"a" "b"
"b" "a"
"b" "a"
"b" "a"
"b" "a"
```

To quantify the difference in performance behind the treatment rankings, we can use `predict_treatment_outcome`

to extract the estimated quality of each treatment for each point:

`IAI.predict_treatment_outcome(grid, train_X)`

```
326×2 DataFrame
Row │ a b
│ Float64 Float64
─────┼────────────────────
1 │ 0.903571 0.760042
2 │ 0.484817 0.767339
3 │ 0.110538 0.373867
4 │ 0.110538 0.373867
5 │ 0.557217 0.320379
6 │ 0.110538 0.373867
7 │ 0.484817 0.767339
8 │ 0.484817 0.767339
⋮ │ ⋮ ⋮
320 │ 0.110538 0.373867
321 │ 0.110538 0.373867
322 │ 0.557217 0.320379
323 │ 0.110538 0.373867
324 │ 0.110538 0.373867
325 │ 0.110538 0.373867
326 │ 0.484817 0.767339
311 rows omitted
```

## Evaluating Optimal Policy Trees

It is critical for a fair evaluation that we do not evaluate the quality of the policy using rewards from our existing reward estimator trained on the training set. This is to avoid any information from the training set leaking through to the out-of-sample evaluation.

Instead, what we need to do is to estimate a new set of rewards using only the test set, and evaluate the policy against these rewards:

```
test_predictions, test_reward_score = IAI.fit_predict!(
reward_lnr, test_X, test_treatments, test_outcomes,
propensity_score_criterion=:auc, outcome_score_criterion=:auc)
test_rewards = test_predictions[:reward]
```

```
327×2 DataFrame
Row │ a b
│ Float64 Float64
─────┼────────────────────────
1 │ 0.598 1.17681
2 │ 1.19976 0.706667
3 │ 0.74 1.15996
4 │ 0.82 1.0655
5 │ 0.71 1.06225
6 │ 0.62 1.18302
7 │ 0.82 1.01578
8 │ 0.7 1.30378
⋮ │ ⋮ ⋮
321 │ -0.114177 0.37
322 │ 0.03 -0.00396172
323 │ 0.04 -0.0341455
324 │ 0.1375 -0.00987617
325 │ -1.07301 0.1
326 │ 0.1 -0.166343
327 │ 0.266667 -0.162051
312 rows omitted
```

`test_reward_score`

```
Dict{Symbol, Any} with 2 entries:
:propensity => 0.617077
:outcome => Dict("b"=>0.92533, "a"=>0.91986)
```

We see the scores are similar to those on the training set, giving us confidence that the estimated rewards are a fair reflection of reality, and will serve as a good basis for evaluation. The AUC for the propensity model is again on the low side, but should be compensated for by means of the doubly-robust estimator.

We can now evaluate the quality using these new estimated rewards. First, we will calculate the average predicted credit approval probability under the treatments prescribed by the tree for the test set. To do this, we use `predict_outcomes`

which uses the model to make prescriptions and looks up the predicted outcomes under these prescriptions:

`policy_outcomes = IAI.predict_outcomes(grid, test_X, test_rewards)`

```
327-element Vector{Float64}:
0.5979999999999999
0.7066666666666666
1.1599571427471242
1.0654951133408965
0.71
1.1830212598121639
1.015778090555864
0.7
0.5662857142857143
0.645
⋮
-0.4522712090174599
-1.6362557691964326
-0.11417721518987323
-0.003961721525363782
-0.03414548409514584
-0.009876174794966719
0.10000000000000009
0.10000000000000009
-0.16205109554170605
```

We can then get the average estimated approval probability under our treatments:

```
using Statistics
mean(policy_outcomes)
```

`0.40771578174823`

We can compare this number to the average approval probability under the treatment assignments that were actually observed:

`mean([test_rewards[i, test_treatments[i]] for i in 1:length(test_treatments)])`

`0.40820588831952`

We see this policy is about the same as the real treatments.