---
title: "Introduction to the ale package"
author: "Chitu Okoli"
date: "August 27, 2025"
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 (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 <doi:10.1111/rssb.12377>). 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 reimplements the original algorithm from the [`{ALEPlot}` package](https://CRAN.r-project.org/package=ALEPlot) and 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. <doi: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) and show how the `{ale}` package handles [various datatypes of input variables](ale-x-datatypes.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 on the same dataset that was used to train the model. An explanation is an explanation of a trained model and a trained model is intrinsically linked to the dataset on which it is trained. (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 generalized 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 generalized 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 statistical or 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.
# 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)
```

## `ALE` object for ALE data

The core object in the `{ale}` package is the `{S7}` `ALE` object. `effect` stores the ALE data and, optionally, ALE statistics and bootstrap data for one or more categories. The first argument to the `ALE()` constructor is a model object--any R model object that can generate numeric predictions is acceptable. By default, it generates 1D (or "first order") ALE on all the variables in the dataset that was used to train the model, if the dataset is included in the model object. If not, the dataset can be specified with the `data` argument. It can optionally create ALE only for specified variables and interactions using the `x_cols` argument. To change these options (e.g., to calculate ALE for only a subset of variables; to output the data only or to use a custom, non-standard predict function for the model), see details in the help file for the object: `help(ALE)`. In this introduction, we only demonstrate The basics of retrieving and plotting ALE data. For details on ALE statistics see [the dedicated vignette](ale-statistics.html "ALE-based statistics") on that topic.

For faster demonstrations, this vignette uses precreated ALE objects. For the full experience, you can uncomment the relevant lines in the code below.

```{r ale_simple}
# Simple ALE without bootstrapping

# For speed, these examples use retrieve_rds() to load pre-created objects 
# from an online repository.
# To run the code yourself, execute the code blocks directly.  
serialized_objects_site <- "https://github.com/tripartio/ale/raw/main/download"

# Create ALE data
ale_gam_diamonds <- retrieve_rds(
  # For speed, load a pre-created object by default.
  c(serialized_objects_site, 'ale_gam_diamonds.0.5.2.rds'),
  {
    # To run the code yourself, execute this code block directly.
    # For standard models like mgcv::gam that store their data,
    # there is no need to specify the data argument.
    ALE(gam_diamonds)
  }
)
# saveRDS(ale_gam_diamonds, file.choose())
```

By default, most core functions in the `{ale}` package use parallel processing. If your computer has problems with this, you can disable parallelization with the argument `parallel = 0`.

To access the plot for a specific variable, we must first create an `ALEPlots` object by calling the `plot()` method on the `ALE` object which internally generates `ggplot` objects with the full flexibility of {ggplot2}:

```{r create-plots}
# Print a plot by entering its reference
diamonds_plots <- plot(ale_gam_diamonds)
```

To retrieve a specific variable plot, you can use the `get()` method of the `ALEPlots` object.  For example, to access and print the `carat` ALE plot, we can simply refer to `get(diamonds_plots, 'carat')`:

```{r print-carat, fig.width=3.5, fig.width=4}
# Print a plot by entering its reference
get(diamonds_plots, 'carat')
```

To display all the ALE plots in an `ALEPlots` object, we can simply call its `print()` or `plot()` methods. Behind the scenes, they use the `{patchwork}` package to arrange multiple plots in a common plot grid using `patchwork::wrap_plots()`, so we can pass arguments from that function. For example, 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
plot(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 trained. As mentioned above, this assumes that IML analysis is carried out on a model whose hyperparameters were determined by cross-validation. When samples are too small for cross-validation, we provide a different approach by bootstrapping the entire model with a `ModelBoot` object, 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 much of that time by the number of bootstrap iterations. 

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. 

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

ale_gam_diamonds_boot <- retrieve_rds(
  # For speed, load a pre-created object by default.
  c(serialized_objects_site, 'ale_gam_diamonds_boot.0.5.2.rds'),
  {
    # To run the code yourself, execute this code block directly.
    # For standard models like mgcv::gam that store their data,
    # there is no need to specify the data argument.
    ALE(
      gam_diamonds,
      boot_it = 100
    )
  }
)
# saveRDS(ale_gam_diamonds_boot, file.choose())

# Bootstrapping produces confidence intervals
plot(ale_gam_diamonds_boot) |> 
  print(ncol = 2)
```

In this case, the bootstrapped results are mostly similar to single (non-bootstrapped) ALE results. 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 2D interactions between variables. This is also implemented with the `ALE()` constructor. When the `d2` element of the `x_cols` list argument is set to `TRUE`, `ALE()` generates ALE data on all possible 2D interactions from the input dataset. To change the default options (e.g., to calculate interactions for only certain pairs of variables), see details in the help file for the object: `help(ALE)`.

```{r ale_2D}
# ALE two-way interactions

ale_2D_gam_diamonds <- retrieve_rds(
  # For speed, load a pre-created object by default.
  c(serialized_objects_site, 'ale_2D_gam_diamonds.0.5.2.rds'),
  {
    # To run the code yourself, execute this code block directly.
    ALE(
      gam_diamonds,
      x_cols = list(d2 = TRUE)
    )
  }
)
# saveRDS(ale_2D_gam_diamonds, file.choose())

```

The `plot()` method similarly creates 2D ALE plots from the `ALE` object. The `subset()` method of `ALEPlots` extracts a new `ALEPlots` object with only the selected variables or interaction terms:

```{r print-all-2D, fig.width=7, fig.height=7}
diamonds_2D_plots <- plot(ale_2D_gam_diamonds)

diamonds_2D_plots |>
  # Select all 2D interactions that involve 'carat'
  subset(list(d2_all = 'carat')) |> 
  print(ncol = 2)
```

Because we are printing all plots together, 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. The `ale` package supports the standard R formula notation for specifying variables. For example, we can print the interaction plot between carat and depth by referring to it thus: `get(diamonds_2D_plots, ~ carat:clarity)`.

```{r print-specific-ixn, fig.width=5, fig.height=3}
get(diamonds_2D_plots, ~ carat:clarity)
```

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 being grey, the middle range of data. In the plots, the darker squares indicate the relative percentage of actual data in each interaction intersection. So, there is very little actual data for 0.2 carats; there is much more higher carat ranges.

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 their interaction has no additional composite effect.
