# Plot Slopes

Bambi's sub-package `interpret` features a set of functions to help interpret complex regression models. The sub-package is inspired by the R package [marginaleffects](https://marginaleffects.com/chapters/predictions.html#conditional-predictions). In this notebook we will discuss two functions [slopes](../reference/interpret.slopes.md) and [plot_slopes](../reference/interpret.plot_slopes.md). These two functions allow the modeler to easier interpret slopes, either by a inspecting a summary output or plotting them.

Below, it is described why estimating the slope of the prediction function is useful in interpreting generalized linear models (GLMs), how this methodology is implemented in Bambi, and how to use [slopes](../reference/interpret.slopes.md) and [plot_slopes](../reference/interpret.plot_slopes.md). It is assumed that the reader is familiar with the basics of GLMs. If not, refer to the Bambi [Basic Building Blocks](https://bambinos.github.io/bambi/notebooks/how_bambi_works.html#Link-functions) example.

## Interpretation of Regression Coefficients

Assuming we have fit a linear regression model of the form

``` math
y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \dots + \beta_k x_k + \epsilon
```

the "safest" interpretation of the regression coefficients $`\beta`$ is as a comparison between two groups of items that differ by $`1`$ in the relevant predictor variable $`x_i`$ while being identical in all the other predictors. Formally, the predicted difference between two items $`i`$ and $`j`$ that differ by an amount $`n`$ on predictor $`k`$, but are identical on all other predictors, the predicted difference is $`y_i - y_j`$ is $`\beta_kx`$, on average.

However, once we move away from a regression model with a Gaussian response, the identity function, and no interaction terms, the interpretation of the coefficients are not as straightforward. For example, in a logistic regression model, the coefficients are on a different scale and are measured in logits (log odds), not probabilities or percentage points. Thus, you cannot interpret the coefficents as a "one unit increase in $`x_k`$ is associated with an $`n`$ percentage point decrease in $`y`$". First, the logits must be converted to the probability scale. Secondly, a one unit change in $`x_k`$ may produce a larger or smaller change in the outcome, depending upon how far away from zero the logits are.

[slopes](../reference/interpret.slopes.md) and [plot_slopes](../reference/interpret.plot_slopes.md), by default, computes quantities of interest on the response scale for GLMs. For example, for a logistic regression model, this is the probability scale, and for a Poisson regression model, this is the count scale.

### Interpreting interaction effects

Specifying interactions in a regression model is a way of allowing parameters to be conditional on certain aspects of the data. By contrast, for a model with no interactions, the parameters are **not** conditional and thus, the value of one parameter is not dependent on the value of another covariate. However, once interactions exist, multiple parameters are always in play at the same time. Additionally, interactions can be specified for either categorical, continuous, or both types of covariates. Thus, making the interpretation of the parameters more difficult.

With GLMs, every covariate essentially interacts with itself because of the link function. To demonstrate parameters interacting with themselves, consider the mean of a Gaussian linear model with an identity link function

``` math
\mu = \alpha + \beta x
```

where the rate of change in $`\mu`$ with respect to $`x`$ is just $`\beta`$, i.e., the rate of change is constant no matter what the value of $`x`$ is. But when we consider GLMs with link functions used to map outputs to exponential family distribution parameters, calculating the derivative of the mean output $`\mu`$ with respect to the predictor is not as straightforward as in the Gaussian linear model. For example, computing the rate of change in a binomial probability $`p`$ with respect to $`x`$

``` math
p = \frac{exp(\alpha + \beta x)}{1 + exp(\alpha + \beta x)}
```

And taking the derivative of $`p`$ with respect to $`x`$ yields

``` math
\frac{\partial p}{\partial x} = \frac{\beta}{2(1 + cosh(\alpha + \beta x))}
```

Since $`x`$ appears in the derivative, the impact of a change in $`x`$ depends upon $`x`$, i.e., an interaction with itself even though no interaction term was specified in the model.Thus, visualizing the rate of change in the mean response with respect to a covariate $`x`$ becomes a useful tool in interpreting GLMs.

## Average Predictive Slopes

Here, we adopt the notation from Chapter 14.4 of [Regression and Other Stories](https://avehtari.github.io/ROS-Examples/) to first describe average predictive differences which is essential to computing [slopes](../reference/interpret.slopes.md), and then secondly, average predictive slopes. Assume we have fit a Bambi model predicting an outcome $`Y`$ based on inputs $`X`$ and parameters $`\theta`$. Consider the following scalar inputs:

``` math
w: \text{the input of interest}
```
``` math
c: \text{all the other inputs}
```
``` math
X = (w, c)
```

In contrast to [comparisons](../reference/interpret.comparisons.md), for [slopes](../reference/interpret.slopes.md) we are interested in comparing $`w^{\text{value}}`$ to $`w^{\text{value}+\epsilon}`$ (perhaps age = 60 and 60.0001 respectively) with all other inputs $`c`$ held constant. The *predictive difference* in the outcome changing **only** $`w`$ is:

``` math
\text{average predictive difference} = \mathbb{E}(y|w^{\text{value}+\epsilon}, c, \theta) - \mathbb{E}(y|w^{\text{value}}, c, \theta)
```

Selecting $`w`$ and $`w^{\text{value}+\epsilon}`$ and averaging over all other inputs $`c`$ in the data gives you a new "hypothetical" dataset and corresponds to counting all pairs of transitions of $`(w^\text{value})`$ to $`(w^{\text{value}+\epsilon})`$, i.e., differences in $`w`$ with $`c`$ held constant. The difference between these two terms is the average predictive difference.

However, to obtain the slope estimate, we need to take the above formula and divide by $`\epsilon`$ to obtain the *average predictive slope*:

``` math
\text{average predictive slope} = \frac{\mathbb{E}(y|w^{\text{value}+\epsilon}, c, \theta) - \mathbb{E}(y|w^{\text{value}}, c, \theta)}{\epsilon}
```

## Computing Slopes

The objective of [slopes](../reference/interpret.slopes.md) and [plot_slopes](../reference/interpret.plot_slopes.md) is to compute the rate of change (slope) in the mean of the response $`y`$ with respect to a small change $`\epsilon`$ in the predictor $`x`$ conditional on other covariates $`c`$ specified in the model. $`w`$ is specified by the user and the original value is either provided by the user, else a default value (the mean) is computed by Bambi. The values for the other covariates $`c`$ specified in the model can be determined under the following three scenarios:

1.  user provided values
2.  a grid of equally spaced and central values
3.  empirical distribution (original data used to fit the model)

In the case of (1) and (2) above, Bambi assembles all pairwise combinations (transitions) of $`w`$ and $`c`$ into a new "hypothetical" dataset. In (3), Bambi uses the original $`c`$, and adds a small amount $`\epsilon`$ to each unit of observation's $`w`$. In each scenario, predictions are made on the data using the fitted model. Once the predictions are made, comparisons are computed using the posterior samples by taking the difference in the predicted outcome for each pair of transitions and dividing by $`\epsilon`$. The average of these slopes is the average predictive slopes.

For variables $`w`$ with a string or categorical data type, use the [comparisons](../reference/interpret.comparisons.md) function as [slopes](../reference/interpret.slopes.md) expects a numeric data type to approximate the derivative via finite-differences. Please refer to the [comparisons](https://bambinos.github.io/bambi/notebooks/plot_comparisons.html) documentation for more details.

Below, we present several examples showing how to use Bambi to perform these computations for us, and to return either a summary dataframe, or a visualization of the results.

``` python
%config InlineBackend.figure_format = "retina"
%config InlineBackend.print_figure_kwargs = {'bbox_inches': None}

import arviz as az
import bambi as bmb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

plt.style.use("bambi.mplstyle")
seed = sum(map(ord, "Plot slopes"))
rng = np.random.default_rng(seed)
```

## Logistic Regression

To demonstrate [slopes](../reference/interpret.slopes.md) and [plot_slopes](../reference/interpret.plot_slopes.md), we will use the [well switching dataset](https://vincentarelbundock.github.io/Rdatasets/doc/carData/Wells.html) to model the probability a household in Bangladesh switches water wells. The data are for an area of Arahazar Upazila, Bangladesh. The researchers labelled each well with its level of arsenic and an indication of whether the well was "safe" or "unsafe". Those using unsafe wells were encouraged to switch. After several years, it was determined whether each household using an unsafe well had changed its well. The data contains $`3020`$ observations on the following five variables:

- `switch`: a factor with levels `no` and `yes` indicating whether the household switched to a new well
- `arsenic`: the level of arsenic in the old well (measured in micrograms per liter)
- `dist`: the distance to the nearest safe well (measured in meters)
- `assoc`: a factor with levels `no` and `yes` indicating whether the household is a member of an arsenic education group
- `educ`: years of education of the household head

First, a logistic regression model with no interactions is fit to the data. Subsequently, to demonstrate the benefits of [plot_slopes](../reference/interpret.plot_slopes.md) in interpreting interactions, we will fit a logistic regression model with an interaction term.

``` python
data = pd.read_csv(
    "https://vincentarelbundock.github.io/Rdatasets/csv/carData/Wells.csv"
)
data["switch"] = pd.Categorical(data["switch"])
data["dist100"] = data["distance"] / 100
data["educ4"] = data["education"] / 4
data.head()
```

|     | rownames | switch | arsenic | distance | education | association | dist100 | educ4 |
|-----|----------|--------|---------|----------|-----------|-------------|---------|-------|
| 0   | 1        | yes    | 2.36    | 16.826   | 0         | no          | 0.16826 | 0.0   |
| 1   | 2        | yes    | 0.71    | 47.322   | 0         | no          | 0.47322 | 0.0   |
| 2   | 3        | no     | 2.07    | 20.967   | 10        | no          | 0.20967 | 2.5   |
| 3   | 4        | yes    | 1.15    | 21.486   | 12        | no          | 0.21486 | 3.0   |
| 4   | 5        | yes    | 1.10    | 40.874   | 14        | yes         | 0.40874 | 3.5   |

``` python
well_model = bmb.Model("switch ~ dist100 + arsenic + educ4", data, family="bernoulli")

well_idata = well_model.fit(random_seed=seed, chains=4)
```

    Modeling the probability that switch==no
    NUTS[nutpie]: [dist100, arsenic, educ4, Intercept_centered]

*\[Rich HTML output -- view on the documentation site\]*

```
```

### User provided values

First, an example of scenario 1 (user provided values) is given below. In both [plot_slopes](../reference/interpret.plot_slopes.md) and [slopes](../reference/interpret.slopes.md), $`w`$ and $`c`$ are represented by `wrt` (with respect to) and `conditional`, respectively. The modeler has the ability to pass their own values for `wrt` and `conditional` by using a dictionary where the key-value pairs are the covariate and value(s) of interest.

For example, if we wanted to compute the slope of the probability of switching wells for a typical `arsenic` value of $`1.3`$ conditional on a range of `dist` and `educ` values, we would pass the following dictionary in the code block below. By default, for $`w`$, Bambi compares $`w^\text{value}`$ to $`w^{\text{value} + \epsilon}`$ where $`\epsilon =`$ `1e-4`. However, the value for $`\epsilon`$ can be changed by passing a value to the argument `eps`.

Thus, in this example, $`w^\text{value} = 1.3`$ and $`w^{\text{value} + \epsilon} = 1.3001`$. The user is not limited to passing a list for the values. A `np.array` can also be used. Furthermore, Bambi by default, maps the order of the dict keys to the main, group, and panel of the matplotlib figure. Below, since `dist100` is the first key, this is used for the x-axis, and `educ4` is used for the group (color). If a third key was passed, it would be used for the panel (facet).

``` python
bmb.interpret.plot_slopes(
    well_model,
    well_idata,
    wrt={"arsenic": 1.3},
    conditional={"dist100": [0.20, 0.50, 0.80], "educ4": [1.00, 1.20, 2.00]},
)
```

![](plot_slopes_files/figure-html/cell-5-output-1.png)

The plot above shows that, for example, conditional on `dist100` $`= 0.2`$ and `educ4` $`= 1.0`$ a unit increase in `arsenic` is associated with households being $`11`$% less likely to switch wells. Notice that even though we fit a logistic regression model where the coefficients are on the log-odds scale, the [slopes](../reference/interpret.slopes.md) function returns the slope on the probability scale. Thus, we can interpret the y-axis (slope) as the expected change in the probability of switching wells for a unit increase in `arsenic` conditional on the specified covariates.

[slopes](../reference/interpret.slopes.md) can be called directly to view a summary dataframe that includes the term name, estimate type (discussed in detail in the *interpreting coefficients as an elasticity* section), values $`w`$ used to compute the estimate, the specified conditional covariates $`c`$, and the expected slope of the outcome with the uncertainty interval (by default the $`94`$% highest density interval is computed).

[slopes](../reference/interpret.slopes.md) returns a `Result` named tuple with two fields: `summary` and `draws`. The `summary` field is a pandas DataFrame containing the point estimates (posterior mean) and credible intervals for each row of the slope grid. The `draws` field is an `arviz.InferenceData` object containing the full posterior samples used to compute the summary. The `summary` is useful for quick inspection and tabular reporting, while `draws` gives access to the complete posterior distribution for custom analyses or visualizations beyond the default summary statistics.

``` python
result = bmb.interpret.slopes(
    well_model,
    well_idata,
    wrt={"arsenic": 1.5},
    conditional={"dist100": [0.20, 0.50, 0.80], "educ4": [1.00, 1.20, 2.00]},
)

result.summary
```

|     | term    | estimate_type | value | dist100 | educ4 | estimate  | lower_5.5% | upper_94.5% |
|-----|---------|---------------|-------|---------|-------|-----------|------------|-------------|
| 0   | arsenic | dydx          | 1.5   | 0.2     | 1.0   | -0.110389 | -0.125874  | -0.094861   |
| 1   | arsenic | dydx          | 1.5   | 0.2     | 1.2   | -0.109469 | -0.125705  | -0.094977   |
| 2   | arsenic | dydx          | 1.5   | 0.2     | 2.0   | -0.105268 | -0.120446  | -0.090918   |
| 3   | arsenic | dydx          | 1.5   | 0.5     | 1.0   | -0.115644 | -0.131987  | -0.099068   |
| 4   | arsenic | dydx          | 1.5   | 0.5     | 1.2   | -0.115192 | -0.131314  | -0.098507   |
| 5   | arsenic | dydx          | 1.5   | 0.5     | 2.0   | -0.112724 | -0.129273  | -0.097016   |
| 6   | arsenic | dydx          | 1.5   | 0.8     | 1.0   | -0.116827 | -0.133396  | -0.100224   |
| 7   | arsenic | dydx          | 1.5   | 0.8     | 1.2   | -0.116908 | -0.133295  | -0.099970   |
| 8   | arsenic | dydx          | 1.5   | 0.8     | 2.0   | -0.116513 | -0.133101  | -0.099705   |

Since all covariates used to fit the model were also specified to compute the slopes, no default value is used for unspecified covariates. A default value is computed for the unspecified covariates because in order to peform predictions, Bambi is expecting a value for each covariate used to fit the model. Additionally, with GLM models, average predictive slopes are conditional in the sense that the estimate depends on the values of **all** the covariates in the model. Thus, for unspecified covariates, [slopes](../reference/interpret.slopes.md) and [plot_slopes](../reference/interpret.plot_slopes.md) computes a default value (mean or mode based on the data type of the covariate). Each row in the summary dataframe is read as "the slope (or rate of change) of the probability of switching wells with respect to a small change in $`w`$ conditional on $`c`$ is $`y`$".

### Conditional slopes

As stated in the *interpreting interaction effects* section, interpreting coefficients of multiple interaction terms can be difficult and cumbersome. Thus, [plot_slopes](../reference/interpret.plot_slopes.md) provides an effective way to visualize the conditional slopes of the interaction effects. Below, we will use the same well switching dataset, but with interaction terms. Specifically, one interaction is added between `dist100` and `educ4`, and another between `arsenic` and `educ4`.

``` python
well_model_interact = bmb.Model(
    "switch ~ dist100 + arsenic + educ4 + dist100:educ4 + arsenic:educ4",
    data=data,
    family="bernoulli",
)

well_idata_interact = well_model_interact.fit(
    draws=500, tune=500, random_seed=seed, chains=4
)
```

    Modeling the probability that switch==no
    NUTS[nutpie]: [dist100, arsenic, educ4, dist100:educ4, arsenic:educ4, Intercept_centered]

*\[Rich HTML output -- view on the documentation site\]*

```
```

``` python
# summary of coefficients
az.summary(well_idata_interact)
```

|  | mean | sd | eti89_lb | eti89_ub | ess_bulk | ess_tail | r_hat | mcse_mean | mcse_sd |
|----|----|----|----|----|----|----|----|----|----|
| dist100 | 1.32 | 0.169 | 1 | 1.6 | 1035 | 1045 | 1.01 | 0.0052 | 0.0037 |
| arsenic | -0.395 | 0.061 | -0.49 | -0.3 | 797 | 939 | 1.00 | 0.0022 | 0.0016 |
| educ4 | 0.102 | 0.077 | -0.019 | 0.22 | 807 | 1034 | 1.00 | 0.0027 | 0.002 |
| dist100:educ4 | -0.33 | 0.103 | -0.49 | -0.16 | 989 | 1212 | 1.01 | 0.0033 | 0.0023 |
| arsenic:educ4 | -0.079 | 0.043 | -0.15 | -0.01 | 699 | 1023 | 1.00 | 0.0016 | 0.0011 |
| Intercept_centered | -0.34 | 0.038 | -0.4 | -0.28 | 2103 | 1264 | 1.00 | 0.00084 | 0.00055 |
| Intercept | -0.1 | 0.12 | -0.29 | 0.092 | 1097 | 1294 | 1.00 | 0.0036 | 0.0025 |

The coefficients of the linear model are shown in the table above. The interaction coefficents indicate the slope varies in a continuous fashion with the continuous variable.

A negative value for `arsenic:dist100` indicates that the "effect" of arsenic on the outcome is less negative as distance from the well increases. Similarly, a negative value for `arsenic:educ4` indicates that the "effect" of arsenic on the outcome is more negative as education increases. Remember, these coefficients are still on the logit scale. Furthermore, as more variables and interaction terms are added to the model, interpreting these coefficients becomes more difficult.

Thus, lets use [plot_slopes](../reference/interpret.plot_slopes.md) to visually see how the slope changes with respect to `arsenic` conditional on `dist100` and `educ4` changing. Notice in the code block below how parameters are passed to the `subplot_kwargs` and `fig_kwargs` arguments. At times, it can be useful to pass specific `group` and `panel` arguments to aid in the interpretation of the plot. Therefore, `subplot_kwargs` allows the user to manipulate the plotting by passing a dictionary where the keys are `{"main": ..., "group": ..., "panel": ...}` and the values are the names of the covariates to be plotted. `fig_kwargs` are figure level key word arguments such as a theme dictionary (dictionary of matplotlib rc parameters).

``` python
bmb.interpret.plot_slopes(
    well_model_interact,
    well_idata_interact,
    wrt="arsenic",
    conditional={"dist100": np.linspace(0, 4, 50), "educ4": np.arange(0, 5, 1)},
    subplot_kwargs={"main": "dist100", "group": "educ4", "panel": "educ4"},
    fig_kwargs={"theme": {"figure.figsize": (7, 3)}, "title": "educ4={}".format},
)
```

![](plot_slopes_files/figure-html/cell-9-output-1.png)

With interaction terms now defined, it can be seen how the slope of the outcome with respect to `arsenic` differ depending on the value of `educ4`. Especially in the case of `educ4` $`= 4.25`$, the slope is more "constant", but with greater uncertainty. Lets compare this with the model that does not include any interaction terms.

``` python
bmb.interpret.plot_slopes(
    well_model,
    well_idata,
    wrt="arsenic",
    conditional={"dist100": np.linspace(0, 4, 50), "educ4": np.arange(0, 5, 1)},
    subplot_kwargs={"main": "dist100", "group": "educ4", "panel": "educ4"},
    fig_kwargs={"theme": {"figure.figsize": (7, 3)}, "title": "educ4={}".format},
)
```

![](plot_slopes_files/figure-html/cell-10-output-1.png)

For the non-interaction model, conditional on a range of values for `educ4` and `dist100`, the slopes of the outcome are nearly identical.

### Unit level slopes

Evaluating average predictive slopes at central values for the conditional covariates $`c`$ can be problematic when the inputs have a large variance since no single central value (mean, median, etc.) is representative of the covariate. This is especially true when $`c`$ exhibits bi or multimodality. Thus, it may be desireable to use the empirical distribution of $`c`$ to compute the predictive slopes, and then average over a specific or set of covariates to obtain average slopes. To achieve unit level slopes, do not pass a parameter into `conditional` and or specify `None`.

``` python
unit_level = bmb.interpret.slopes(
    well_model_interact, well_idata_interact, wrt="arsenic", conditional=None
)

# empirical distribution
print(unit_level.summary.shape[0] == well_model_interact.data.shape[0])
unit_level.summary.head(10)
```

    True

|     | term    | estimate_type | value   | dist100 | educ4 | estimate  | lower_5.5% | upper_94.5% |
|-----|---------|---------------|---------|---------|-------|-----------|------------|-------------|
| 0   | arsenic | dydx          | 1.65693 | 0.16826 | 0.00  | -0.091903 | -0.114374  | -0.070111   |
| 1   | arsenic | dydx          | 1.65693 | 0.47322 | 0.00  | -0.098274 | -0.122678  | -0.074347   |
| 2   | arsenic | dydx          | 1.65693 | 0.20967 | 2.50  | -0.129909 | -0.154778  | -0.106674   |
| 3   | arsenic | dydx          | 1.65693 | 0.21486 | 3.00  | -0.136089 | -0.166030  | -0.107350   |
| 4   | arsenic | dydx          | 1.65693 | 0.40874 | 3.50  | -0.143600 | -0.178097  | -0.105631   |
| 5   | arsenic | dydx          | 1.65693 | 0.69518 | 2.25  | -0.136762 | -0.163649  | -0.114345   |
| 6   | arsenic | dydx          | 1.65693 | 0.80711 | 1.00  | -0.118370 | -0.134498  | -0.101300   |
| 7   | arsenic | dydx          | 1.65693 | 0.55146 | 2.50  | -0.136943 | -0.165057  | -0.112000   |
| 8   | arsenic | dydx          | 1.65693 | 0.52647 | 0.00  | -0.098609 | -0.123459  | -0.074822   |
| 9   | arsenic | dydx          | 1.65693 | 0.75072 | 0.00  | -0.097313 | -0.119793  | -0.071896   |

``` python
well_model_interact.data.head(10)
```

|     | rownames | switch | arsenic | distance | education | association | dist100 | educ4 |
|-----|----------|--------|---------|----------|-----------|-------------|---------|-------|
| 0   | 1        | yes    | 2.36    | 16.826   | 0         | no          | 0.16826 | 0.00  |
| 1   | 2        | yes    | 0.71    | 47.322   | 0         | no          | 0.47322 | 0.00  |
| 2   | 3        | no     | 2.07    | 20.967   | 10        | no          | 0.20967 | 2.50  |
| 3   | 4        | yes    | 1.15    | 21.486   | 12        | no          | 0.21486 | 3.00  |
| 4   | 5        | yes    | 1.10    | 40.874   | 14        | yes         | 0.40874 | 3.50  |
| 5   | 6        | yes    | 3.90    | 69.518   | 9         | yes         | 0.69518 | 2.25  |
| 6   | 7        | yes    | 2.97    | 80.711   | 4         | yes         | 0.80711 | 1.00  |
| 7   | 8        | yes    | 3.24    | 55.146   | 10        | no          | 0.55146 | 2.50  |
| 8   | 9        | yes    | 3.28    | 52.647   | 0         | yes         | 0.52647 | 0.00  |
| 9   | 10       | yes    | 2.52    | 75.072   | 0         | yes         | 0.75072 | 0.00  |

Above, `unit_level` is the slopes summary dataframe and `well_model_interact.data` is the empirical data used to fit the model. Notice how the values for $`c`$ are identical in both dataframes. However, for $`w`$, the values are the original $`w`$ value plus $`\epsilon`$. Thus, the `estimate` value represents the instantaneous rate of change for that unit of observation. However, these unit level slopes are difficult to interpret since each row may have a different slope estimate. Therefore, it is useful to average over (marginalize) the estimates to summarize the unit level predictive slopes.

#### Marginalizing over covariates

Since the empirical distrubution is used for computing the average predictive slopes, the same number of rows ($`3020`$) is returned as the data used to fit the model. To average over a covariate, use the `average_by` argument. If `all` is passed, then [slopes](../reference/interpret.slopes.md) averages over **all** covariates. Else, if a single or list of covariates are passed, then [slopes](../reference/interpret.slopes.md) averages by the covariates passed.

``` python
result = bmb.interpret.slopes(
    well_model_interact,
    well_idata_interact,
    wrt="arsenic",
    conditional=None,
    average_by="all",
)

result.summary
```

|     | term    | estimate_type | value   | estimate  | lower_5.5% | upper_94.5% |
|-----|---------|---------------|---------|-----------|------------|-------------|
| 0   | arsenic | dydx          | 1.65693 | -0.113861 | -0.134562  | -0.093332   |

The code block above is equivalent to taking the mean of the `estimate` and uncertainty columns. For example:

``` python
unit_level.summary[["estimate", "lower_5.5%", "upper_94.5%"]].mean()
```

    estimate      -0.113861
    lower_5.5%    -0.134562
    upper_94.5%   -0.093332
    dtype: float64

#### Average by subgroups

Averaging over all covariates may not be desired, and you would rather average by a group or specific covariate. To perform averaging by subgroups, users can pass a single or list of covariates to `average_by` to average over specific covariates. For example, if we wanted to average by `educ4`:

``` python
# average by educ4
result = bmb.interpret.slopes(
    well_model_interact,
    well_idata_interact,
    wrt="arsenic",
    conditional=None,
    average_by="educ4",
)

result.summary
```

|     | term    | estimate_type | value   | educ4 | estimate  | lower_5.5% | upper_94.5% |
|-----|---------|---------------|---------|-------|-----------|------------|-------------|
| 0   | arsenic | dydx          | 1.65693 | 0.00  | -0.093121 | -0.116023  | -0.070629   |
| 1   | arsenic | dydx          | 1.65693 | 0.25  | -0.098570 | -0.117900  | -0.078090   |
| 2   | arsenic | dydx          | 1.65693 | 0.50  | -0.103115 | -0.120196  | -0.084622   |
| 3   | arsenic | dydx          | 1.65693 | 0.75  | -0.107333 | -0.123334  | -0.091178   |
| 4   | arsenic | dydx          | 1.65693 | 1.00  | -0.112070 | -0.127723  | -0.096982   |
| 5   | arsenic | dydx          | 1.65693 | 1.25  | -0.116392 | -0.131254  | -0.100455   |
| 6   | arsenic | dydx          | 1.65693 | 1.50  | -0.120698 | -0.137271  | -0.104486   |
| 7   | arsenic | dydx          | 1.65693 | 1.75  | -0.124458 | -0.142886  | -0.106716   |
| 8   | arsenic | dydx          | 1.65693 | 2.00  | -0.127525 | -0.148050  | -0.107654   |
| 9   | arsenic | dydx          | 1.65693 | 2.25  | -0.132131 | -0.156087  | -0.109919   |
| 10  | arsenic | dydx          | 1.65693 | 2.50  | -0.134233 | -0.159904  | -0.108851   |
| 11  | arsenic | dydx          | 1.65693 | 2.75  | -0.135452 | -0.162561  | -0.107285   |
| 12  | arsenic | dydx          | 1.65693 | 3.00  | -0.138863 | -0.170535  | -0.108881   |
| 13  | arsenic | dydx          | 1.65693 | 3.25  | -0.139158 | -0.171243  | -0.106743   |
| 14  | arsenic | dydx          | 1.65693 | 3.50  | -0.143796 | -0.182423  | -0.108202   |
| 15  | arsenic | dydx          | 1.65693 | 3.75  | -0.145642 | -0.186503  | -0.106641   |
| 16  | arsenic | dydx          | 1.65693 | 4.00  | -0.146772 | -0.192417  | -0.105486   |
| 17  | arsenic | dydx          | 1.65693 | 4.25  | -0.148971 | -0.194465  | -0.108419   |

``` python
# average by both educ4 and dist100
result = bmb.interpret.slopes(
    well_model_interact,
    well_idata_interact,
    wrt="arsenic",
    conditional=None,
    average_by=["educ4", "dist100"],
)

result.summary
```

|  | term | estimate_type | value | educ4 | dist100 | estimate | lower_5.5% | upper_94.5% |
|----|----|----|----|----|----|----|----|----|
| 0 | arsenic | dydx | 1.65693 | 0.00 | 0.00591 | -0.085940 | -0.106116 | -0.065399 |
| 1 | arsenic | dydx | 1.65693 | 0.00 | 0.02409 | -0.086676 | -0.107118 | -0.066001 |
| 2 | arsenic | dydx | 1.65693 | 0.00 | 0.02454 | -0.086694 | -0.107143 | -0.066014 |
| 3 | arsenic | dydx | 1.65693 | 0.00 | 0.02791 | -0.086829 | -0.107319 | -0.066112 |
| 4 | arsenic | dydx | 1.65693 | 0.00 | 0.03252 | -0.087012 | -0.108041 | -0.066800 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 2992 | arsenic | dydx | 1.65693 | 4.00 | 1.13727 | -0.146872 | -0.200715 | -0.100090 |
| 2993 | arsenic | dydx | 1.65693 | 4.00 | 1.14418 | -0.146861 | -0.200829 | -0.099996 |
| 2994 | arsenic | dydx | 1.65693 | 4.00 | 1.25308 | -0.146665 | -0.203429 | -0.099060 |
| 2995 | arsenic | dydx | 1.65693 | 4.00 | 1.67025 | -0.145518 | -0.206141 | -0.087538 |
| 2996 | arsenic | dydx | 1.65693 | 4.25 | 0.29633 | -0.148971 | -0.194465 | -0.108419 |

2997 rows × 8 columns

It is still possible to use [plot_slopes](../reference/interpret.plot_slopes.md) when passing an argument to `average_by`. In the plot below, the empirical distribution is used to compute unit level slopes with respect to `arsenic` and then averaged over `educ4` to obtain the average predictive slopes.

``` python
bmb.interpret.plot_slopes(
    well_model_interact,
    well_idata_interact,
    wrt="arsenic",
    conditional=None,
    average_by="educ4",
)
```

![](plot_slopes_files/figure-html/cell-17-output-1.png)

### Interpreting coefficients as an elasticity

In some fields, such as economics, it is useful to interpret the results of a regression model in terms of an elasticity (a percent change in $`x`$ is associated with a percent change in $`y`$) or semi-elasticity (a unit change in $`x`$ is associated with a percent change in $`y`$, or vice versa). Typically, this is achieved by fitting a model where either the outcome and or the covariates are log-transformed. However, since the log transformation is performed by the modeler, to compute elasticities for [slopes](../reference/interpret.slopes.md) and [plot_slopes](../reference/interpret.plot_slopes.md), Bambi "post-processes" the predictions to compute the elasticities. Below, it is shown the possible elasticity arguments and how they are computed for [slopes](../reference/interpret.slopes.md) and [plot_slopes](../reference/interpret.plot_slopes.md):

- `eyex`: a percentage point increase in $`x_1`$ is associated with an $`n`$ percentage point increase in $`y`$

``` math
\frac{\partial \hat{y}}{\partial x_1} * \frac{x_1}{\hat{y}}
```

- `eydx`: a unit increase in $`x_1`$ is associated with an $`n`$ percentage point increase in $`y`$

``` math
\frac{\partial \hat{y}}{\partial x_1} * \frac{1}{\hat{y}}
```

- `dyex`: a percentage point increase in $`x_1`$ is associated with an $`n`$ unit increase in $`y`$

``` math
\frac{\partial \hat{y}}{\partial x_1} * x_1
```

Below, each code cell shows the same model, and `wrt` and `conditional` argument, but with a different elasticity (`slope`) argument. By default, `dydx` (a derivative with no post-processing) is used.

``` python
result = bmb.interpret.slopes(
    well_model_interact,
    well_idata_interact,
    wrt="arsenic",
    slope="eyex",
    conditional=None,
    average_by="all",
)

result.summary
```

|     | term    | estimate_type | value   | estimate  | lower_5.5% | upper_94.5% |
|-----|---------|---------------|---------|-----------|------------|-------------|
| 0   | arsenic | eyex          | 1.65693 | -0.480062 | -0.572801  | -0.383858   |

``` python
result = bmb.interpret.slopes(
    well_model_interact,
    well_idata_interact,
    wrt="arsenic",
    slope="eydx",
    conditional=None,
    average_by="all",
)

result.summary
```

|     | term    | estimate_type | value   | estimate | lower_5.5% | upper_94.5% |
|-----|---------|---------------|---------|----------|------------|-------------|
| 0   | arsenic | eydx          | 1.65693 | -0.28973 | -0.3457    | -0.231668   |

``` python
result = bmb.interpret.slopes(
    well_model_interact,
    well_idata_interact,
    wrt="arsenic",
    slope="dyex",
    conditional=None,
    average_by="all",
)

result.summary
```

|     | term    | estimate_type | value   | estimate | lower_5.5% | upper_94.5% |
|-----|---------|---------------|---------|----------|------------|-------------|
| 0   | arsenic | dyex          | 1.65693 | -0.18866 | -0.22296   | -0.154645   |

`slope` is also an argument for [plot_slopes](../reference/interpret.plot_slopes.md). Below, we visualize the elasticity with respect to `arsenic` conditional on a range of `dist100` and `educ4` values (notice this is the same plot as in the *conditional slopes* section).

``` python
bmb.interpret.plot_slopes(
    well_model_interact,
    well_idata_interact,
    wrt="arsenic",
    conditional={"dist100": np.linspace(0, 4, 50), "educ4": np.arange(0, 5, 1)},
    slope="eyex",
    subplot_kwargs={"main": "dist100", "group": "educ4", "panel": "educ4"},
    fig_kwargs={"theme": {"figure.figsize": (7, 3)}, "title": "educ4={}".format},
)
```

![](plot_slopes_files/figure-html/cell-21-output-1.png)

``` python
%load_ext watermark
%watermark -n -u -v -iv -w
```

    Last updated: Sat, 29 Aug 2026

    Python implementation: CPython
    Python version       : 3.14.7
    IPython version      : 9.16.1

    arviz     : 1.3.0
    bambi     : 0.20.1.dev78+g69d4473ea.d20260829
    matplotlib: 3.11.1
    numpy     : 2.4.6
    pandas    : 2.3.3

    Watermark: 2.6.0
