interpretability_with_shap.mdx 7.64 KB
Newer Older
bailuo's avatar
readme  
bailuo committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
---
title: "Model Interpretability"
description: "Learn how to interpret model predictions using SHAP values to understand the impact of exogenous variables."
icon: "square-root-variable"
---

## What Are SHAP Values?

SHAP (SHapley Additive exPlanation) values use game theory concepts to explain how each feature influences machine learning forecasts. They're particularly useful when working with exogenous (external) variables, letting you understand contributions both at individual prediction steps and across entire forecast horizons.

SHAP values can be seamlessly combined with visualization methods from the [SHAP](https://shap.readthedocs.io/en/latest/) Python package for powerful plots and insights. Before proceeding, make sure you understand forecasting with exogenous features. For reference, see our [tutorial on exogenous variables](/forecasting/exogenous-variables/numeric_features).

## How to Use SHAP Values for TimeGPT

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Nixtla/nixtla/blob/main/nbs/docs/tutorials/21_shap_values.ipynb)

## Install SHAP

Install the SHAP library.

```bash
pip install shap
```

For more details, visit the [official SHAP documentation](https://shap.readthedocs.io/en/latest/).

### Step 1: Import Packages

Import the necessary libraries and initialize the Nixtla client.

```python
import pandas as pd
from nixtla import NixtlaClient

nixtla_client = NixtlaClient(
    api_key='my_api_key_provided_by_nixtla'  # Or use os.environ.get("NIXTLA_API_KEY")
)
```

### Step 2: Load Data

We'll use exogenous variables (covariates) to enhance electricity market forecasting accuracy. The widely known EPF dataset is available at
[this link](https://zenodo.org/records/4624805). It contains hourly prices and relevant exogenous factors for five different electricity markets.

For this tutorial, we'll focus on the Belgian electricity market (BE). The data includes:
- Hourly prices (y)
- Forecasts for load (Exogenous1) and generation (Exogenous2)
- Day-of-week indicators (one-hot encoded)

If your data relies on factors such as weather, holiday calendars, marketing, or other elements, ensure they're similarly structured.

```python
market = "BE"

df = pd.read_csv(
    'https://raw.githubusercontent.com/Nixtla/transfer-learning-time-series/main/datasets/electricity-short-with-ex-vars.csv'
)

df.head()
```

| unique_id | ds | y | Exogenous1 | Exogenous2 | day_0 | day_1 | day_2 | day_3 | day_4 | day_5 | day_6 |
|-----------|----|---|------------|------------|-------|-------|-------|-------|-------|-------|-------|
| BE        | 2016-10-22 00:00:00 | 70.00 | 57253.0 | 49593.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 0.0 |
| BE        | 2016-10-22 01:00:00 | 37.10 | 51887.0 | 46073.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 0.0 |
| BE        | 2016-10-22 02:00:00 | 37.10 | 51896.0 | 44927.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 0.0 |
| BE        | 2016-10-22 03:00:00 | 44.75 | 48428.0 | 44483.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 0.0 |
| BE        | 2016-10-22 04:00:00 | 37.10 | 46721.0 | 44338.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 0.0 |

### Step 3: Forecast with Exogenous Variables

To make forecasts with exogenous variables, you must have future data for these variables available at the time of prediction.


Before generating forecasts, ensure you have (or can generate) future exogenous values. Below, we load future exogenous features to obtain 24-step-ahead predictions:

```python
future_ex_vars_df = pd.read_csv(
    'https://raw.githubusercontent.com/Nixtla/transfer-learning-time-series/main/datasets/electricity-short-future-ex-vars.csv'
)

future_ex_vars_df.head()
```

| unique_id | ds | Exogenous1 | Exogenous2 | day_0 | day_1 | day_2 | day_3 | day_4 | day_5 | day_6 |
|-----------|----|------------|------------|-------|-------|-------|-------|-------|-------|-------|
| BE        | 2016-12-31 00:00:00 | 70318.0 | 64108.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 0.0 |
| BE        | 2016-12-31 01:00:00 | 67898.0 | 62492.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 0.0 |
| BE        | 2016-12-31 02:00:00 | 68379.0 | 61571.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 0.0 |
| BE        | 2016-12-31 03:00:00 | 64972.0 | 60381.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 0.0 |
| BE        | 2016-12-31 04:00:00 | 62900.0 | 60298.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 1.0 | 0.0 |

Next, create forecasts using the Nixtla API:

```python
timegpt_fcst_ex_vars_df = nixtla_client.forecast(
    df=df,
    X_df=future_ex_vars_df,
    h=24,
    level=[80, 90],
    feature_contributions=True
)

timegpt_fcst_ex_vars_df.head()
```

| unique_id | ds | TimeGPT | TimeGPT-hi-80 | TimeGPT-hi-90 | TimeGPT-lo-80 | TimeGPT-lo-90 |
|-----------|----|---------|---------------|---------------|---------------|---------------|
| BE        | 2016-12-31 00:00:00 | 51.632830 | 61.598820 | 66.088295 | 41.666843 | 37.177372 |
| BE        | 2016-12-31 01:00:00 | 45.750877 | 54.611988 | 60.176445 | 36.889767 | 31.325312 |
| BE        | 2016-12-31 02:00:00 | 39.650543 | 46.256210 | 52.842808 | 33.044876 | 26.458277 |
| BE        | 2016-12-31 03:00:00 | 34.000072 | 44.015310 | 47.429000 | 23.984835 | 20.571144 |
| BE        | 2016-12-31 04:00:00 | 33.785370 | 43.140503 | 48.581240 | 24.430239 | 18.989498 |


### Step 4: Extract SHAP Values

After forecasting, you can retrieve SHAP values to see how each feature contributed to the model's predictions.

```python
shap_df = nixtla_client.feature_contributions
shap_df = shap_df.query("unique_id == @market")

shap_df.head()
```

### Step 5: Visualization with SHAP

Visualizing SHAP values helps interpret the impact of exogenous features in detail. Below, we demonstrate three common SHAP plots.

#### Bar Plot

Use a bar plot to see the average impact of each feature across predictions:

```python
import shap
import matplotlib.pyplot as plt

shap_columns = shap_df.columns.difference(['unique_id', 'ds', 'TimeGPT', 'base_value'])

shap_obj = shap.Explanation(
    values=shap_df[shap_columns].values,
    base_values=shap_df['base_value'].values,
    feature_names=shap_columns
)

shap.plots.bar(
    shap_obj,
    max_display=len(shap_columns),
    show=False
)

plt.title(f'SHAP values for {market}')
plt.show()
```

<Frame caption="Bar Plot">
  ![Bar Plot](https://raw.githubusercontent.com/Nixtla/nixtla/readme_docs/nbs/_docs/docs/tutorials/21_shap_values_files/figure-markdown_strict/cell-14-output-1.png)
</Frame>

#### Waterfall Plot

A waterfall plot shows how each feature contributes to a single prediction step. Here, we select the earliest date for illustration:

```python
selected_ds = shap_df['ds'].min()

filtered_df = shap_df[shap_df['ds'] == selected_ds]

shap_obj = shap.Explanation(
    values=filtered_df[shap_columns].values.flatten(),
    base_values=filtered_df['base_value'].values[0],
    feature_names=shap_columns
)

shap.plots.waterfall(shap_obj, show=False)

plt.title(f'Waterfall Plot: {market}, date: {selected_ds}')
plt.show()
```

<Frame caption="Waterfall Plot">
  ![Waterfall Plot](https://raw.githubusercontent.com/Nixtla/nixtla/readme_docs/nbs/_docs/docs/tutorials/21_shap_values_files/figure-markdown_strict/cell-15-output-1.png)
</Frame>

#### Heatmap

Visualize how feature impacts vary across each forecast step. This often reveals time-dependent effects of certain variables.

```python
shap_obj = shap.Explanation(
    values=shap_df[shap_columns].values,
    feature_names=shap_columns
)

shap.plots.heatmap(shap_obj, show=False)

plt.title(f'SHAP Heatmap (Unique ID: {market})')
plt.show()
```

<Frame caption="SHAP Heatmap">
  ![SHAP Heatmap](https://raw.githubusercontent.com/Nixtla/nixtla/readme_docs/nbs/_docs/docs/tutorials/21_shap_values_files/figure-markdown_strict/cell-16-output-1.png)
</Frame>