---
title: "Introduction to the ale package"
author: "Chitu Okoli"
date: "October 24, 2023"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to the ale package}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---
 
```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

```

Accumulated Local Effects (ALE) were initially developed as a [model-agnostic approach for global explanations of the results of black-box machine learning algorithms](https://www.doi.org/10.1111/rssb.12377 "Apley, Daniel W., and Jingyu Zhu. 'Visualizing the effects of predictor variables in black box supervised learning models.' Journal of the Royal Statistical Society Series B: Statistical Methodology 82.4 (2020): 1059-1086"). ALE has at least two primary advantages over other approaches like partial dependency plots (PDP) and SHapley Additive exPlanations (SHAP): its values are not affected by the presence of interactions among variables in a model and its computation is relatively rapid. This package rewrites the original code from the [`{ALEPlot}` package](https://CRAN.r-project.org/package=ALEPlot) for calculating ALE data and it completely reimplements the plotting of ALE values. It also extends the original ALE concept to add bootstrap-based confidence intervals and ALE-based statistics that can be used for statistical inference.

For more details, see Okoli, Chitu. 2023. “Statistical Inference Using Machine Learning and Classical Techniques Based on Accumulated Local Effects (ALE).” arXiv. <https://doi.org/10.48550/arXiv.2310.09877>.

This vignette demonstrates the basic functionality of the `{ale}` package on standard large datasets used for machine learning. A separate vignette is devoted to its use on [small datasets](ale-small-datasets.html "ale package for small datasets"), as is often the case with statistical inference. (How small is small? That's a tough question, but as that vignette explains, most datasets of less than 2000 rows are probably "small" and even many datasets that are more than 2000 rows are nonetheless "small".) Other vignettes introduce [ALE-based statistics for statistical inference](ale-statistics.html), show how the `{ale}` package handles [various datatypes of input variables](ale-x-datatypes.html), and [compares the `{ale}` package with the reference `{ALEPlot}` package](https://tripartio.github.io/ale/articles/ale-ALEPlot.html).

We begin by loading the necessary libraries.

```{r load libraries}
library(ale)
library(dplyr)
```

## diamonds dataset

For this introduction, we use the `diamonds` dataset, included with the `{ggplot2}` graphics system. We cleaned the original version by [removing duplicates](https://lorentzen.ch/index.php/2021/04/16/a-curious-fact-on-the-diamonds-dataset/ "errors in the diamonds dataset") and invalid entries where the length (x), width (y), or depth (z) is 0.

```{r diamonds_print}
# Clean up some invalid entries
diamonds <- ggplot2::diamonds |> 
  filter(!(x == 0 | y == 0 | z == 0)) |> 
  # https://lorentzen.ch/index.php/2021/04/16/a-curious-fact-on-the-diamonds-dataset/
  distinct(
    price, carat, cut, color, clarity,
    .keep_all = TRUE
  ) |> 
  rename(
    x_length = x,
    y_width = y,
    z_depth = z,
    depth_pct = depth
  )

summary(diamonds)
```

Here is the description of the modified dataset.

| Variable  | Description                                                                                       |
|-----------------|-------------------------------------------------------|
| price     | price in US dollars (\$326--\$18,823)                                                             |
| carat     | weight of the diamond (0.2--5.01)                                                                 |
| cut       | quality of the cut (Fair, Good, Very Good, Premium, Ideal)                                        |
| color     | diamond color, from D (best) to J (worst)                                                         |
| clarity   | a measurement of how clear the diamond is (I1 (worst), SI2, SI1, VS2, VS1, VVS2, VVS1, IF (best)) |
| x_length  | length in mm (0--10.74)                                                                           |
| y_width   | width in mm (0--58.9)                                                                             |
| z_depth   | depth in mm (0--31.8)                                                                             |
| depth_pct | total depth percentage = z / mean(x, y) = 2 \* z / (x + y) (43--79)                               |
| table     | width of top of diamond relative to widest point (43--95)                                         |

```{r diamonds_str}
str(diamonds)
```

```{r diamonds_price}
summary(diamonds$price)
```

Interpretable machine learning (IML) techniques like ALE should be applied not on training subsets nor on test subsets but on a final deployment model after training and evaluation. This final deployment should be trained on the full dataset to give the best possible model for production deployment. (When a dataset is too small to feasibly split into training and test sets, then the ale package has tools to appropriately handle such [small datasets](ale-small-datasets.html "ale package for small datasets").

## Modelling with general additive models (GAM)

ALE is a model-agnostic IML approach, that is, it works with any kind of machine learning model. As such, `{ale}` works with any R model with the only condition that it can predict numeric outcomes (such as raw estimates for regression and probabilities or odds ratios for classification). For this demonstration, we will use general additive models (GAM), a relatively fast algorithm that models data more flexibly than ordinary least squares regression. It is beyond our scope here to explain how GAM works (you can learn more with [Noam Ross's excellent tutorial](https://noamross.github.io/gams-in-r-course/chapter1/ "Tutorial on GAM")), but the examples here will work with any machine learning algorithm.

We train a GAM model to predict diamond prices:

```{r train_gam}
# Create a GAM model with flexible curves to predict diamond prices.
# (In testing, mgcv::gam actually performed better than nnet.)
# Smooth all numeric variables and include all other variables.
gam_diamonds <- mgcv::gam(
  price ~ s(carat) + s(depth_pct) + s(table) + s(x_length) + s(y_width) + s(z_depth) +
    cut + color + clarity,
  data = diamonds
  )
summary(gam_diamonds)
```

## Enable progress bars

Before starting, we recommend that you enable progress bars to see how long procedures will take. Simply run the following code at the beginning of your R session:

```{r enable progressr, eval = FALSE}
# Run this in an R console; it will not work directly within an R Markdown or Quarto block
progressr::handlers(global = TRUE)
progressr::handlers('cli')
```

If you forget to do that, the `{ale}` package will do it automatically for you with a notification message.

## `ale()` function for generating ALE data and plots

The core function in the `{ale}` package is the `ale()` function. Consistent with tidyverse conventions, its first argument is a dataset. Its second argument is a model object--any R model object that can generate numeric predictions is acceptable. By default, it generates ALE data and plots on all the input variables used for the model. To change these options (e.g., to calculate ALE for only a subset of variables; to output the data only or the plots only rather than both; or to use a custom, non-standard predict function for the model), see details in the help file for the function: `help(ale)`.

The `ale()` function returns a list with various elements. The two main ones are `data`, containing the ALE x intervals and the y values for each interval, and `plots`, containing the ALE plots as individual `ggplot` objects. Each of these elements is a list with one element per input variable. The function also returns several details about the outcome (y) variable and important parameters that were used for the ALE calculation. Another important element is `stats`, containing ALE-based statistics, which we describe in [a separate vignette](ale-statistics.html "ALE-based statistics").

```{r ale_simple}
# Simple ALE without bootstrapping
ale_gam_diamonds <- ale(
  diamonds, gam_diamonds,
  parallel = 2  # CRAN limit (delete this line on your own computer)
)
```

By default, most core functions in the `{ale}` package use parallel processing. However, this requires explicit specification of the packages used to build the model, specified with the `model_packages` argument. (If parallelization is disabled with `parallel = 0`, then `model_packages` is not required.) See `help(ale)` for more details.

To access the plot for a specific variable, we can call it by its variable name as an element of the `plots` element. These are `ggplot` objects, so they are easy to manipulate. For example, to access and print the `carat` ALE plot, we simply call `ale_gam_diamonds$plots$carat` :

```{r print-carat, fig.width=3.5, fig.width=4}
# Print a plot by entering its reference
ale_gam_diamonds$plots$carat
```

To iterate the list and plot all the ALE plots, we provide here some demonstration code using the `patchwork` package for arranging multiple plots in a common plot grid using `patchwork::wrap_plots()`. We need to pass the list of plots to the `grobs` argument and we can specify that we want two plots per row with the `ncol` argument.

```{r print-ale_simple, fig.width=7, fig.height=11}
# Print all plots
patchwork::wrap_plots(ale_gam_diamonds$plots, ncol = 2)
```

## Bootstrapped ALE

One of the key features of the ALE package is bootstrapping of the ALE results to ensure that the results are reliable, that is, generalizable to data beyond the sample on which the model was built. As mentioned above, this assumes that IML analysis is carried out on a final deployment model selected after training and evaluating the model hyperparameters on distinct subsets. When samples are too small for this, we provide a different bootstrapping method, `model_bootstrap()`, explained in the vignette for [small datasets](ale-small-datasets.html "ale package for small datasets").

Although ALE is faster than most other IML techniques for global explanation such as partial dependence plots (PDP) and SHAP, it still requires some time to run. Bootstrapping multiplies that time by the number of bootstrap iterations. Since this vignette is just a demonstration of package functionality rather than a real analysis, we will demonstrate bootstrapping on a small subset of the test data. This will run much faster as the speed of the ALE algorithm depends on the size of the dataset. So, let us take a random sample of 200 rows of the test set.

```{r diamonds_new}
# Bootstraping is rather slow, so create a smaller subset of new data for demonstration
set.seed(0)
new_rows <- sample(nrow(diamonds), 200, replace = FALSE)
diamonds_small_test <- diamonds[new_rows, ]
```

Now we create bootstrapped ALE data and plots using the `boot_it` argument. ALE is a relatively stable IML algorithm (compared to others like PDP), so 100 bootstrap samples should be sufficient for relatively stable results, especially for model development. Final results could be confirmed with 1000 bootstrap samples or more, but there should not be much difference in the results beyond 100 iterations. However, so that this introduction runs faster, we demonstrate it here with only 10 iterations. 

```{r ale_boot, fig.width=7, fig.height=11}

ale_gam_diamonds_boot <- ale(
  diamonds_small_test, gam_diamonds, 
  # Normally boot_it should be set to 100, but just 10 here for a faster demonstration
  boot_it = 10,
  parallel = 2  # CRAN limit (delete this line on your own computer)
)

# Bootstrapping produces confidence intervals
patchwork::wrap_plots(ale_gam_diamonds_boot$plots, ncol = 2)
```

In this case, the bootstrapped results are mostly similar to single (non-bootstrapped) ALE result. In principle, we should always bootstrap the results and trust only in bootstrapped results. The most unusual result is that values of `x_length` (the length of the diamond) from 6.2 mm or so and higher are associated with lower diamond prices. When we compare this with the `y_width` value (width of the diamond), we suspect that when both the length and width (that is, the size) of a diamond become increasingly large, the price increases so much more rapidly with the width than with the length that the width has an inordinately high effect that is tempered by a decreased effect of the length at those high values. This would be worth further exploration for real analysis, but here we are just introducing the key features of the package.

## ALE interactions

Another advantage of ALE is that it provides data for two-way interactions between variables. This is implemented with the `ale_ixn()` function. Like the `ale()` function, `ale_ixn()` similarly requires an input dataset and a model object. By default, it generates ALE data and plots on all possible pairs of input variables used for the model. However, an ALE interaction requires at least one of the variables to be numeric. So, `ale_ixn()` has a notion of x1 and x2 variables; the x1 variable must be numeric whereas the x2 can be of any input datatype. To change the default options (e.g., to calculate interactions for only certain pairs of variables), see details in the help file for the function: `help(ale_ixn)`.

```{r ale_ixn}
# ALE two-way interactions
ale_ixn_gam_diamonds <- ale_ixn(
  diamonds, gam_diamonds,
  parallel = 2  # CRAN limit (delete this line on your own computer)
)

```

Like the `ale()` function, the `ale_ixn()` returns a list with one element per input x1 variable, as well as a `.common_data` element with details about the outcome (y) variable. However, in this case, each variable's element consists of a list of all the x2 variables for which the x1 interaction is calculated. Each x2 element then has two elements: the ALE data for that variable and a `ggplot` plot object that plots that ALE data. In the interaction plots, the x1 variable is always shown on the x axis and the x2 variable on the y axis.

Again, we provide here some demonstration code to plot all the ALE plots. It is a little more complex this time because of the two levels of interacting variables in the output data, so we use the `purrr` package to iterate the list structure. `purrr::walk()` takes a list as its first argument and then we specify an anonymous function for what we want to do with each element of the list. We specify the anonymous function as `\(.x1) {...}` where `.x1` in our case represents each individual element of `ale_ixn_gam_diamonds$plots` in turn, that is, a sublist of plots with which the x1 variable interacts. We print the plots of all the x1 interactions as a combined grid of plots with `patchwork::wrap_plots()`, as before.

```{r print-all-ale_ixn, fig.width=7, fig.height=7}
# Print all interaction plots
ale_ixn_gam_diamonds$plots |>
  # extract list of x1 ALE outputs
  purrr::walk(\(.x1) {
    # plot all x2 plots in each .x1 element
    patchwork::wrap_plots(.x1, ncol = 2) |>
      print()
  })

```

Because we are printing all plots together with the same `patchwork::wrap_plots()` statement, some of them might appear vertically distorted because each plot is forced to be of the same height. For more fine-tuned presentation, we would need to refer to a specific plot. For example, we can print the interaction plot between carat and depth by referring to it thus: `ale_ixn_gam_diamonds$plots$carat$depth`.

```{r print-specific-ixn, fig.width=5, fig.height=3}
ale_ixn_gam_diamonds$plots$carat$depth
```

This is not the best dataset to use to illustrate ALE interactions because there are none here. This is expressed in the graphs by the ALE y values all falling in the middle grey band (the median band), which indicates that any interactions would not shift the price outside the middle 5% of its values. In other words, there is no meaningful interaction effect.

Note that ALE interactions are very particular: an ALE interaction means that two variables have a composite effect over and above their separate independent effects. So, of course `x_length` and `y_width` both have effects on the price, as the one-way ALE plots show, but they have no additional composite effect. To see what ALE interaction plots look like in the presence of interactions, see the [ALEPlot comparison vignette](https://tripartio.github.io/ale/articles/ale-ALEPlot.html), which explains the interaction plots in more detail.
