---
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 supervised machine learning models.
Put simply, an FME is the change in a model's predicted value for a given observation if the feature is changed by a certain value.
Read the [article][4] on how FMEs are computed or the methods [paper][1] for more details. Our [website][5] is the best way to find all resources.

There are three main functions: 

- `fme()` computes FMEs for a given model, data, feature(s) of interest, and step size(s).
- `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).

## Example

Let's look at data from a bike sharing usage system in Washington, D.C. (Fanaee-T and Gama, 2014). 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. In addition to generic `lm`-type models, the `fme` package supports 100+ models from the `mlr3`, `tidymodels` and `caret` libraries. Let's try a random forest using the `ranger` algorithm:

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

---

# Numeric Feature Effects

FMEs can be used to compute feature effects for both numerical and categorical features. This can be done with the `fme()` function. 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 `features` argument. This is a named list with the feature names and step lengths. The step length is chosen to be the number deemed most useful for the purpose of interpretation. Often, this could be a unit change, e.g., `features = list(feature_name = 1)`. As the concept of numerical FMEs extends to multivariate feature changes as well, `fme()` can be asked to compute a multivariate feature effect.

## Univariate Effects

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

```{r}
effects = fme(model = forest,
               data = bikes,
               features = list(temp = 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 data. Thereby, we reduce the risk of model extrapolation.

```{r, message=FALSE}
plot(effects)
```

The black arrow indicates direction and magnitude of the step size. The horizontal line is the average marginal effect (AME). The AME is computed as a simple mean over all observation-wise FMEs. We can extract relevant aggregate information from the `effects` object:

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

Therefore, on average, a temperature increase of 1°C is associated with an increase in predicted bike sharing usage by roughly 56. As can be seen in the plot, the observation-wise effects seem to vary along the range of `temp`. The FME tends to be positive for temperature values between 0 and 17°C and negative for higher temperature values (>17°C). \

For a more in-depth analysis, we can inspect individual FMEs for each observation in the data (excluding extrapolation points):

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

## Multivariate Effects

Multivariate feature effects can be considered when one is interested in the combined effect of two or more numeric features. 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 `features = list(temp = -3, humidity = -0.1)`:

```{r, message=FALSE}
effects2 = fme(model = forest,
               data = bikes,
               features = list(temp = -3, humidity = -0.1),
               ep.method = "envelope")
```

For bivariate effects, we can plot the effects in a way similar to univariate effects (for more than two features, we can plot only the histogram of effects):

```{r, message=FALSE}
plot(effects2)
```

The plot for bivariate FMEs uses a color scale to indicate direction and magnitude of the estimated effect. We see that a drop in both temperature and humidity is associated with lower predicted bike sharing usage especially on days with medium temperatures and medium-to-low humidity. 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 standard deviation of the FMEs implies that effects are highly heterogeneous:

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

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

## Non-Linearity Measure

The non-linearity measure (NLM) is a complimentary tool to an FME. Any numerical, observation-wise FME is prone to be misinterpreted as a linear effect. To counteract this, the NLM quantifies the linearity of the prediction function for a single observation and step size. A value of 1 indicates linearity, a value of 0 or lower indicates non-linearity (similar to R-squared, the NLM can take negative values). A detailed explanation can be found in the [FME methods paper][1].

We can compute and plot NLMs alongside FMEs for univariate and multivariate feature changes. Computing NLMs can be computationally demanding, so we use `furrr` for parallelization. To illustrate NLMs, let's recompute the first example of an increase in temperature by 1 degree Celsius (°C) on a subset of the bikes data:

```{r, results='hide'}
effects3 = fme(model = forest,
               data = bikes[1:200,],
               feature = list(temp = 1),
               ep.method = "envelope",
               compute.nlm = TRUE)
```

Similarly to the AME, we can extract an Average NLM (ANLM):

```{r}
effects3$anlm
```

A value of 0.2 indicates that a linear effect is ill-suited to describe the change of the prediction function along the multivariate feature step. This means we should be weary of interpreting the FME as a linear effect.

If NLMs have been computed, they can be visualized alongside FMEs using `with.nlm = TRUE`:

```{r, message = FALSE, fig.asp = 0.4}
plot(effects3, with.nlm = TRUE)
```

Equivalently, let's compute an example with bivariate FMEs with NLMs:

```{r, results='hide'}
effects4 = fme(model = forest,
               data = bikes[1:200,],
               features = list(temp = -3, humidity = -0.1),
               ep.method = "envelope",
               compute.nlm = TRUE)
```

```{r, message = FALSE, fig.asp = 0.4}
plot(effects4, bins = 25, with.nlm = TRUE)
```

# Categorical Effects

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 `features`. 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}
effects5 = fme(model = forest,
              data = bikes,
              features = list(weather = "rain"))
summary(effects5)
```

An AME of -732 implies that holding all other features constant, a change to rainy weather can be expected to reduce bike sharing usage by 732. \
For categorical feature effects, we can plot the empirical distribution of the FMEs:

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

## Interactions

In a similar way, we can consider interactions of categories from different features. For example, consider the average combined effect of a clear sky on the weekend, i.e., `weather = "clear"` and `workingday = "no"`:  

```{r}
fme(model = forest,
    data = bikes,
    features = list(weather = "clear", workingday = "no"))$ame
```

---

# 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)
overview$results
```

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

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

Again, note that we advise to set `ep.method = "envelope"` so we avoid model extrapolation.

---

# Regional 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 standard deviation (SD) of FMEs is used as a criterion to measure homogeneity in each subspace. We can see that the SD is substantially smaller in two of the three subspaces when compared to 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 season (`season`) and the humidity (`humidity`). The information contained in the boxes below the terminal nodes are equivalent to the summary output and can be extracted from `subspaces$results`. The difference in the cAMEs across the groups means the expected ME varies substantially in direction and magnitude across the subspaces. For example, the cAME is highest on summer days. It is lowest on days in spring, fall or winter when the humidity is below 66%.

---

# 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://link.springer.com/article/10.1007/s10618-023-00993-x

[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

[5]: https://holgstr.github.io/fmeffects/
