---
title: "Get started"
output: 
  rmarkdown::html_vignette:
    toc: true
    toc_depth: 3
params:
  EVAL: !r identical(Sys.getenv("NOT_CRAN"), "true")
vignette: >
  %\VignetteIndexEntry{Get started}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

## Introduction

The `fmeffects` package computes, aggregates, and visualizes forward marginal effects (FMEs) for any supervised machine learning model. Read [here][4] how they are computed or the [research paper][1] for a more in-depth understanding. There are three main functions: 

- `fme()` computes FMEs for a given model, data, feature of interest, and step size
- `came()` can be applied subsequently to find subspaces of the feature space where FMEs are more homogeneous
- `ame()` provides an overview of the prediction function w.r.t. each feature by using average marginal effects (AMEs) based on FMEs.

### Example

For demonstration purposes, we consider usage data from the Capital Bike Sharing scheme (Fanaee-T and Gama, 2014). It contains information about bike sharing usage in Washington, D.C. for the years 2011-2012 during the period from 7 to 8 a.m. We are interested in predicting `count` (the total number of bikes lent out to users).

```{r}
library(fmeffects)
data(bikes, package = "fmeffects")
str(bikes)
```

FMEs are a model-agnostic interpretation method, i.e., they can be applied to any regression or (binary) classification model. Before we can compute FMEs, we need a trained model. The `fme` package supports models from the `mlr3`, `tidymodels` (parsnip) and `caret` libraries. Let's try it with a random forest using the `ranger` algorithm:

```{r, message=FALSE}
set.seed(123)
library(mlr3verse)
library(ranger)
task = as_task_regr(x = bikes, id = "bikes", target = "count")
forest = lrn("regr.ranger")$train(task)
```

---

## Compute FMEs

FMEs can be used to compute feature effects for both numerical and categorical features. This can be done with the `fme()` function.

### Numerical Features

The most common application is to compute the FME for a single numerical feature, i.e., a univariate feature effect. The variable of interest must be specified with the `feature` argument. In this case, `step.size` can be any number deemed most useful for the purpose of interpretation. Most of the time, this will be a unit change, e.g., `step.size = 1`. As the concept of numerical FMEs extends to multivariate feature effects as well, `fme()` can be asked to compute a bivariate feature effect as well. In this case, `feature` needs to be supplied with the names of two numerical features, and `step.size` requires a vector, e.g., `step.size = c(1, 1)`.

#### Univariate Feature Effects

Assume we are interested in the effect of temperature on bike sharing usage. Specifically, we set `step.size = 1` to investigate the FME of an increase in temperature by 1 degree Celsius (°C). Thus, we compute FMEs for ` feature = "temp"` and `step.size = 1`.

```{r}
effects = fme(model = forest,
               data = bikes,
               target = "count",
               feature = "temp",
               step.size = 1,
               ep.method = "envelope")
```

Note that we have specified `ep.method = "envelope"`. This means we exclude observations for which adding 1°C to the temperature results in the temperature value falling outside the range of `temp` in the overall data. Thereby, we reduce the risk of asking the model to extrapolate.

```{r, warning=FALSE}
plot(effects, jitter = c(0.2, 0))
```

The black arrow indicates direction and magnitude of `step.size`. The horizontal line is the average marginal effect (AME). The AME is computed as a simple mean over all observation-wise FMEs. Therefore, on average, the FME of a temperature increase of 1°C on bike sharing usage is roughly 2.4. As can be seen, the observation-wise effects seem to vary for different values of temp. While the FME tends to be positive for lower temperature values (0-20°C), it turns negative for higher temperature values (>20°C). \

Also, we can extract all relevant aggregate information from the `effects` object:

```{r}
effects$ame
```

For a more in-depth analysis, we can inspect the FME for each observation in the data set:

```{r}
head(effects$results)
```


#### Bivariate Feature Effects

Bivariate feature effects can be considered when one is interested in the combined effect of two features on the target variable. Let's assume we want to estimate the effect of a decrease in temperature by 3°C, combined with a decrease in humidity by 10 percentage points, i.e., the FME for `feature = c("temp", "humidity")` and `step.size = c(−3, −0.1)`:

```{r}
effects2 = fme(model = forest,
               data = bikes,
               target = "count",
               feature = c("temp", "humidity"),
               step.size = c(-3, -0.1),
               ep.method = "envelope")

plot(effects2, jitter = c(0.1, 0.02))
```

The plot for bivariate FMEs uses a color scale to indicate direction and magnitude of the estimated effect. Let's check the AME:

```{r}
effects2$ame
```

It seems that a combined decrease in temperature by 3°C and humidity by 10 percentage points seems to result in slightly lower bike sharing usage (on average). However, a quick check of the variance of the FMEs implies that effects are highly heterogeneous:

```{r}
var(effects2$results$fme)
```

Therefore, it could be interesting to move the interpretation of feature effects from a global to a [semi-global perspective][Semi-global Interpretations] via the `came()` function.

### Categorical Features

For a categorical feature, the FME of an observation is simply the difference in predictions when changing the observed category of the feature to the category specified in `step.size`. For instance, one could be interested in the effect of rainy weather on the bike sharing demand, i.e., the FME of changing the feature value of `weather` to `rain` for observations where weather is either `clear` or `misty`:

```{r}
effects3 = fme(model = forest,
              data = bikes,
              target = "count",
              feature = "weather",
              step.size = "rain")
summary(effects3)
```

Here, the AME of `rain` is -55. Therefore, while holding all other features constant, a change to rainy weather can be expected to reduce bike sharing usage by 55. \
For categorical feature effects, we can plot the empirical distribution of the FMEs:

```{r, warning=FALSE}
plot(effects3)
```

### Model Overview with AMEs

For an informative overview of all feature effects in a model, we can use the `ame()` function:

```{r, warning=FALSE}
overview = ame(model = forest,
           data = bikes,
           target = "count")
overview$results
```

This computes the AME for each feature included in the model, with a default step size of 1 for numerical features (or, 0.01 if their range is smaller than 1). For categorical features, AMEs are computed for all available categories. \
<!--We can specify a custom subset of features and step sizes using the `features` argument:

```{r, warning=FALSE}
overview = ame(model = forest,
               data = bikes,
               target = "count",
               features = c(weather = c("rain", "clear"), temp = -1, humidity = 0.1),
               ep.method = "envelope")
overview$results
```

Again, note that often it is advisable to set `ep.method = "envelope"` so we avoid model extrapolation.
-->
------

## Semi-global Interpretations

We can use `came()` on a specific FME object to compute subspaces of the feature space where FMEs are more homogeneous. Let's take the effect of a decrease in temperature by 3°C combined with a decrease in humidity by 10 percentage points, and see if we can find three appropriate subspaces.

```{r}
subspaces = came(effects = effects2, number.partitions = 3)
summary(subspaces)
```

As can be seen, the CTREE algorithm was used to partition the feature space into three subspaces. The coefficient of variation (CoV) is used as a criterion to measure homogeneity in each subspace. We can see that the CoV is substantially smaller in each of the subspaces than in the root node, i.e., the global feature space. The conditional AME (cAME) can be used to interpret how the expected FME varies across the subspaces. Let's visualize our results:

```{r}
plot(subspaces)
```

In this case, we get a decision tree that assigns observations to a feature subspace according to the weather situation (`weather`) and the day of the week (`weekday`). The information contained in the boxes below the terminal nodes are equivalent to the summary output and can be extracted from `subspaces$results`. With cAMEs of -4.88, 4.16, and 25.68, respectively, the expected ME is estimated to vary substantially in direction and magnitude across the subspaces. For example, the cAME is highest on rainy days. It turns negative on non-rainy days in spring, summer and winter.

---

## References

Fanaee-T, H. and Gama, J. (2014). Event labeling combining ensemble detectors and background knowledge. Progress in Artificial Intelligence 2(2): 113–127

Vanschoren, J., van Rijn, J. N., Bischl, B. and Torgo, L. (2013). Openml: networked science in machine learning. SIGKDD Explorations 15(2): 49–60

[1]: https://arxiv.org/abs/2201.08837

[2]: https://www.openml.org/search?type=data&status=active&id=42712

[3]: https://mlr3learners.mlr-org.com/

[4]: https://holgstr.github.io/fmeffects/articles/fme_theory.html
