shapformer 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ venv/
2
+ .venv/
3
+ *.ckpt
4
+ /models/
5
+ __pycache__/
6
+ *.pyc
7
+ dist/
8
+ build/
9
+ *.egg-info/
10
+ .ipynb_checkpoints/
11
+ .pytest_cache/
12
+ .idea/
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Karlsruhe Institute of Technology
4
+ Author: Matthias Hertel
5
+ Contact: matthias.hertel@kit.edu
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.5
2
+ Name: shapformer
3
+ Version: 1.0.0
4
+ Summary: Explainable time-series forecasting with sampling-free SHAP for Transformers
5
+ Project-URL: Repository, https://github.com/KIT-IAI/SHAPformer
6
+ Project-URL: Paper, https://doi.org/10.1038/s41467-026-73243-5
7
+ Author: Matthias Hertel
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: Owen values,SHAP,Shapley values,explainable AI,forecasting,time series,transformer
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: 3.15
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: numpy>=1.26
23
+ Requires-Dist: pandas>=2.2
24
+ Requires-Dist: scikit-learn>=1.3
25
+ Requires-Dist: scipy>=1.11
26
+ Requires-Dist: torch>=2.1
27
+ Requires-Dist: tqdm>=4.64
28
+ Provides-Extra: examples
29
+ Requires-Dist: fev; extra == 'examples'
30
+ Requires-Dist: matplotlib>=3.8; extra == 'examples'
31
+ Requires-Dist: notebook; extra == 'examples'
32
+ Requires-Dist: pyarrow; extra == 'examples'
33
+ Requires-Dist: workalendar; extra == 'examples'
34
+ Provides-Extra: plot
35
+ Requires-Dist: matplotlib>=3.8; extra == 'plot'
36
+ Provides-Extra: test
37
+ Requires-Dist: matplotlib>=3.8; extra == 'test'
38
+ Requires-Dist: pytest>=8; extra == 'test'
39
+ Description-Content-Type: text/markdown
40
+
41
+ # SHAPformer: Explainable time-series forecasting with sampling-free SHAP for Transformers
42
+
43
+ This repository contains the code accompanying the [Nature Communications publication](https://www.nature.com/articles/s41467-026-73243-5) on a new algorithm for estimating Shapley additive explanations (SHAP) for time-series forecasting.
44
+ It introduces an explainable model, called SHAPformer, that relies on attention manipulation to evaluate feature subsets without the need for sampling from background data.
45
+
46
+ > Matthias Hertel, Sebastian Pütz, Ralf Mikut, Veit Hagenmeyer, Benjamin Schäfer.
47
+ > *Explainable time-series forecasting with sampling-free SHAP for Transformers.*
48
+ > Nature Communications (2026). DOI: https://doi.org/10.1038/s41467-026-73243-5
49
+
50
+ A recording of a presentation of SHAPformer at the Helmholtz AI Conference 2025 is available via [YouTube](https://www.youtube.com/watch?v=Cfhcffm9DD0&list=PL_Qg4h55JDFui2bUKprmOiHtPNHLD_NuU&index=3) (duration: 11 minutes).
51
+
52
+ ## Installation
53
+
54
+ SHAPformer requires Python 3.11 or newer and can be installed with pip:
55
+
56
+ ```bash
57
+ pip install shapformer
58
+ ```
59
+
60
+ Optional dependencies are available as extras:
61
+
62
+ | Extra | Adds |
63
+ |---|---|
64
+ | `pip install "shapformer[plot]"` | plots of explanations (matplotlib) |
65
+ | `pip install "shapformer[examples]"` | plots and everything the example notebooks need (Jupyter, fev, pyarrow, workalendar) |
66
+ | `pip install "shapformer[test]"` | the test suite (pytest) |
67
+
68
+ The quotes are needed in some shells, such as zsh.
69
+
70
+ ### GPU support
71
+
72
+ SHAPformer is based on PyTorch and runs on NVIDIA GPUs with CUDA.
73
+ On Linux, the PyTorch version installed from PyPI already supports CUDA.
74
+ On Windows, PyPI only has a CPU version of PyTorch, so install a CUDA version of PyTorch first ([other CUDA versions](https://pytorch.org/get-started/locally/)):
75
+
76
+ ```bash
77
+ pip install torch --index-url https://download.pytorch.org/whl/cu128
78
+ pip install shapformer
79
+ ```
80
+
81
+ To use the GPU, move the model to it; training, forecasting and explaining then run on the GPU:
82
+
83
+ ```python
84
+ model = SHAPformer(...).to("cuda")
85
+ ```
86
+
87
+ ## Usage
88
+
89
+ ```python
90
+ from shapformer import SHAPformer, plot_explanation
91
+
92
+ # df: a dataframe with a time index, the target and the covariates;
93
+ # categorical covariates have the number of their categories (values 0 to n - 1), continuous ones None
94
+ model = SHAPformer(
95
+ target="load",
96
+ feature_categories={"hour_of_day": 24, "day_of_week": 7, "temperature": None},
97
+ d_model=128,
98
+ n_layers=1,
99
+ n_heads=4,
100
+ )
101
+ model.fit(df, validation_start="2019-01-01")
102
+
103
+ # past: the last 168 time steps with the target and the covariates; future: the next 168 time steps with the covariates
104
+ prediction = model.predict(past, future)
105
+ explanation = model.explain(past, future) # prediction = base + sum of the SHAP values
106
+ plot_explanation(explanation) # needs shapformer[plot]
107
+ ```
108
+
109
+ See the [example notebooks](#demos) for complete examples.
110
+
111
+ ## Datasets
112
+
113
+ The datasets used in the paper can be downloaded via this link: [data.zip](https://drive.google.com/file/d/16mawim_Ps1dqkB9b5FoStMNYDWpQ73pc/view?usp=sharing). It contains:
114
+
115
+ - the synthetic dataset with ground truth explanations,
116
+ - the real-world dataset with the electrical load of TransnetBW (original source: [OPSD](https://data.open-power-system-data.org/time_series/2020-10-06)) and weather data (original source: [Copernicus](https://cds.climate.copernicus.eu/datasets/sis-energy-derived-reanalysis)).
117
+
118
+ The notebooks expect these datasets in the folder `data/` of the repository (`data/synthetic/` and `data/transnet/`).
119
+ The example notebooks use further public datasets, which they download automatically:
120
+
121
+ - EPF-DE (German electricity prices) and solar_with_weather_1H (solar generation) from the [fev-bench](https://github.com/autogluon/fev) benchmark, loaded with the `fev` package,
122
+ - [UCI Bike Sharing](https://archive.ics.uci.edu/dataset/275/bike+sharing+dataset) (hourly bike rentals in Washington, D.C.).
123
+
124
+ ## Demos
125
+
126
+ | Notebook | Content |
127
+ |---|---|
128
+ | [ground_truth_explanations.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/ground_truth_explanations.ipynb) | Usage of the synthetic dataset with ground truth explanations |
129
+ | [training_json.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/training_json.ipynb) | Training of `ExogenousTransformer` on the TransnetBW data in JSON format (runtime on GPU: <5 minutes) |
130
+ | [evaluation_json.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/evaluation_json.ipynb) | Predictions and explanations with the trained `ExogenousTransformer` (runtime on GPU: <5 minutes) |
131
+ | [training_dataframe.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/training_dataframe.ipynb) | Dataframe interface on the TransnetBW data: training, forecasting, explaining and comparing the two explanation methods |
132
+ | [adapt_context_and_horizon_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/adapt_context_and_horizon_example.ipynb) | TransnetBW load forecasting with a two-week input and a two-day horizon (`input_length`, `horizon`) |
133
+ | [uneven_periods_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/uneven_periods_example.ipynb) | TransnetBW load forecasting with four weeks of input in periods of different lengths (`period_length=(336, 168, 144, 24)`) |
134
+ | [quarter_hourly_resolution_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/quarter_hourly_resolution_example.ipynb) | TransnetBW load forecasting on quarter-hourly data, one week of input in days (`period_length=96`) |
135
+ | [no_periods_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/no_periods_example.ipynb) | TransnetBW load forecasting with the past load as a single feature (`period_length=input_length`) |
136
+ | [electricity_price_forecasting_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/electricity_price_forecasting_example.ipynb) | Electricity price forecasting on EPF-DE with load and PV/wind forecasts |
137
+ | [solar_energy_forecasting_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/solar_energy_forecasting_example.ipynb) | Solar generation forecasting with weather covariates and gaps in the data |
138
+ | [bike_sharing_forecasting_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/bike_sharing_forecasting_example.ipynb) | Bike rental forecasting with monthly retraining and instance normalization |
139
+
140
+ The example notebooks evaluate the forecasts against naive baselines, explain one forecast and show dependence plots of 1000 explanations.
141
+ They save trained models in the folder `models/` of the repository.
142
+
143
+ ## Changes since version 0.1.0
144
+
145
+ - **Dataframe interface:** the new class `SHAPformer` ([shapformer.py](https://github.com/KIT-IAI/SHAPformer/blob/main/src/shapformer/models/shapformer.py)) is built on `ExogenousTransformer`, the model of version 0.1.0 ([exogenous_transformer.py](https://github.com/KIT-IAI/SHAPformer/blob/main/src/shapformer/models/exogenous_transformer.py)), and trains (`fit`), forecasts (`predict`) and explains (`explain`) directly on pandas dataframes, with early stopping on a validation set. `ExogenousTransformer` is still available for preprocessed samples in JSON format (see [training_json.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/training_json.ipynb)).
146
+ - **Incomplete data:** `fit` accepts missing values and missing time steps and only uses complete windows.
147
+ - **Window lengths:** `SHAPformer(input_length=..., horizon=...)` sets the number of past and forecasted time steps (default: 168 each).
148
+ - **Periods of the past target:** `SHAPformer(period_length=...)` sets the groups ("periods") in which the past target is explained (default: 24 time steps, one period per day of hourly data). It takes an int for periods of equal length, or a sequence of lengths from the oldest to the most recent period, e.g. `(336, 168, 144, 24)` for four weeks of hourly data. With a single period (`period_length=input_length`), the past target is masked as a whole, like a covariate, without masking time steps. The explanation columns are named `period 1` (the oldest) to `period n`, or after the target for a single period.
149
+ - **Training on fewer windows:** `fit(window_stride=...)` trains and validates on every n-th window only, e.g. on windows that start at full hours of quarter-hourly data.
150
+ - **Instance normalization:** optional per-sample normalization of the target (`instance_norm="mean"` or `"RevIN"`).
151
+ - **Approximate explanations:** `explain(method="permutation")` estimates the Owen values from sampled permutations, much faster than the exact method (`method="exact"`, default).
152
+ - **Plots:** [plot.py](https://github.com/KIT-IAI/SHAPformer/blob/main/src/shapformer/plot.py) plots single explanations (`plot_explanation`) and dependence plots over many explanations (`plot_dependence`).
153
+ - **Example notebooks:** dataframe interface on TransnetBW, EPF-DE, solar and bike sharing data (see [Demos](#demos)).
154
+ - **Python package:** SHAPformer can be installed with `pip install shapformer` (version 1.0.0). The plots are optional (`shapformer[plot]`), and a test suite checks the explanations, the masking and the training.
155
+
156
+ ## Development
157
+
158
+ To work on the code, clone the repository and install it in editable mode with all extras:
159
+
160
+ ```bash
161
+ git clone https://github.com/KIT-IAI/SHAPformer.git
162
+ cd SHAPformer
163
+ pip install -e ".[examples,test]"
164
+ pytest
165
+ ```
@@ -0,0 +1,125 @@
1
+ # SHAPformer: Explainable time-series forecasting with sampling-free SHAP for Transformers
2
+
3
+ This repository contains the code accompanying the [Nature Communications publication](https://www.nature.com/articles/s41467-026-73243-5) on a new algorithm for estimating Shapley additive explanations (SHAP) for time-series forecasting.
4
+ It introduces an explainable model, called SHAPformer, that relies on attention manipulation to evaluate feature subsets without the need for sampling from background data.
5
+
6
+ > Matthias Hertel, Sebastian Pütz, Ralf Mikut, Veit Hagenmeyer, Benjamin Schäfer.
7
+ > *Explainable time-series forecasting with sampling-free SHAP for Transformers.*
8
+ > Nature Communications (2026). DOI: https://doi.org/10.1038/s41467-026-73243-5
9
+
10
+ A recording of a presentation of SHAPformer at the Helmholtz AI Conference 2025 is available via [YouTube](https://www.youtube.com/watch?v=Cfhcffm9DD0&list=PL_Qg4h55JDFui2bUKprmOiHtPNHLD_NuU&index=3) (duration: 11 minutes).
11
+
12
+ ## Installation
13
+
14
+ SHAPformer requires Python 3.11 or newer and can be installed with pip:
15
+
16
+ ```bash
17
+ pip install shapformer
18
+ ```
19
+
20
+ Optional dependencies are available as extras:
21
+
22
+ | Extra | Adds |
23
+ |---|---|
24
+ | `pip install "shapformer[plot]"` | plots of explanations (matplotlib) |
25
+ | `pip install "shapformer[examples]"` | plots and everything the example notebooks need (Jupyter, fev, pyarrow, workalendar) |
26
+ | `pip install "shapformer[test]"` | the test suite (pytest) |
27
+
28
+ The quotes are needed in some shells, such as zsh.
29
+
30
+ ### GPU support
31
+
32
+ SHAPformer is based on PyTorch and runs on NVIDIA GPUs with CUDA.
33
+ On Linux, the PyTorch version installed from PyPI already supports CUDA.
34
+ On Windows, PyPI only has a CPU version of PyTorch, so install a CUDA version of PyTorch first ([other CUDA versions](https://pytorch.org/get-started/locally/)):
35
+
36
+ ```bash
37
+ pip install torch --index-url https://download.pytorch.org/whl/cu128
38
+ pip install shapformer
39
+ ```
40
+
41
+ To use the GPU, move the model to it; training, forecasting and explaining then run on the GPU:
42
+
43
+ ```python
44
+ model = SHAPformer(...).to("cuda")
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ ```python
50
+ from shapformer import SHAPformer, plot_explanation
51
+
52
+ # df: a dataframe with a time index, the target and the covariates;
53
+ # categorical covariates have the number of their categories (values 0 to n - 1), continuous ones None
54
+ model = SHAPformer(
55
+ target="load",
56
+ feature_categories={"hour_of_day": 24, "day_of_week": 7, "temperature": None},
57
+ d_model=128,
58
+ n_layers=1,
59
+ n_heads=4,
60
+ )
61
+ model.fit(df, validation_start="2019-01-01")
62
+
63
+ # past: the last 168 time steps with the target and the covariates; future: the next 168 time steps with the covariates
64
+ prediction = model.predict(past, future)
65
+ explanation = model.explain(past, future) # prediction = base + sum of the SHAP values
66
+ plot_explanation(explanation) # needs shapformer[plot]
67
+ ```
68
+
69
+ See the [example notebooks](#demos) for complete examples.
70
+
71
+ ## Datasets
72
+
73
+ The datasets used in the paper can be downloaded via this link: [data.zip](https://drive.google.com/file/d/16mawim_Ps1dqkB9b5FoStMNYDWpQ73pc/view?usp=sharing). It contains:
74
+
75
+ - the synthetic dataset with ground truth explanations,
76
+ - the real-world dataset with the electrical load of TransnetBW (original source: [OPSD](https://data.open-power-system-data.org/time_series/2020-10-06)) and weather data (original source: [Copernicus](https://cds.climate.copernicus.eu/datasets/sis-energy-derived-reanalysis)).
77
+
78
+ The notebooks expect these datasets in the folder `data/` of the repository (`data/synthetic/` and `data/transnet/`).
79
+ The example notebooks use further public datasets, which they download automatically:
80
+
81
+ - EPF-DE (German electricity prices) and solar_with_weather_1H (solar generation) from the [fev-bench](https://github.com/autogluon/fev) benchmark, loaded with the `fev` package,
82
+ - [UCI Bike Sharing](https://archive.ics.uci.edu/dataset/275/bike+sharing+dataset) (hourly bike rentals in Washington, D.C.).
83
+
84
+ ## Demos
85
+
86
+ | Notebook | Content |
87
+ |---|---|
88
+ | [ground_truth_explanations.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/ground_truth_explanations.ipynb) | Usage of the synthetic dataset with ground truth explanations |
89
+ | [training_json.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/training_json.ipynb) | Training of `ExogenousTransformer` on the TransnetBW data in JSON format (runtime on GPU: <5 minutes) |
90
+ | [evaluation_json.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/evaluation_json.ipynb) | Predictions and explanations with the trained `ExogenousTransformer` (runtime on GPU: <5 minutes) |
91
+ | [training_dataframe.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/training_dataframe.ipynb) | Dataframe interface on the TransnetBW data: training, forecasting, explaining and comparing the two explanation methods |
92
+ | [adapt_context_and_horizon_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/adapt_context_and_horizon_example.ipynb) | TransnetBW load forecasting with a two-week input and a two-day horizon (`input_length`, `horizon`) |
93
+ | [uneven_periods_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/uneven_periods_example.ipynb) | TransnetBW load forecasting with four weeks of input in periods of different lengths (`period_length=(336, 168, 144, 24)`) |
94
+ | [quarter_hourly_resolution_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/quarter_hourly_resolution_example.ipynb) | TransnetBW load forecasting on quarter-hourly data, one week of input in days (`period_length=96`) |
95
+ | [no_periods_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/no_periods_example.ipynb) | TransnetBW load forecasting with the past load as a single feature (`period_length=input_length`) |
96
+ | [electricity_price_forecasting_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/electricity_price_forecasting_example.ipynb) | Electricity price forecasting on EPF-DE with load and PV/wind forecasts |
97
+ | [solar_energy_forecasting_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/solar_energy_forecasting_example.ipynb) | Solar generation forecasting with weather covariates and gaps in the data |
98
+ | [bike_sharing_forecasting_example.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/bike_sharing_forecasting_example.ipynb) | Bike rental forecasting with monthly retraining and instance normalization |
99
+
100
+ The example notebooks evaluate the forecasts against naive baselines, explain one forecast and show dependence plots of 1000 explanations.
101
+ They save trained models in the folder `models/` of the repository.
102
+
103
+ ## Changes since version 0.1.0
104
+
105
+ - **Dataframe interface:** the new class `SHAPformer` ([shapformer.py](https://github.com/KIT-IAI/SHAPformer/blob/main/src/shapformer/models/shapformer.py)) is built on `ExogenousTransformer`, the model of version 0.1.0 ([exogenous_transformer.py](https://github.com/KIT-IAI/SHAPformer/blob/main/src/shapformer/models/exogenous_transformer.py)), and trains (`fit`), forecasts (`predict`) and explains (`explain`) directly on pandas dataframes, with early stopping on a validation set. `ExogenousTransformer` is still available for preprocessed samples in JSON format (see [training_json.ipynb](https://github.com/KIT-IAI/SHAPformer/blob/main/notebooks/training_json.ipynb)).
106
+ - **Incomplete data:** `fit` accepts missing values and missing time steps and only uses complete windows.
107
+ - **Window lengths:** `SHAPformer(input_length=..., horizon=...)` sets the number of past and forecasted time steps (default: 168 each).
108
+ - **Periods of the past target:** `SHAPformer(period_length=...)` sets the groups ("periods") in which the past target is explained (default: 24 time steps, one period per day of hourly data). It takes an int for periods of equal length, or a sequence of lengths from the oldest to the most recent period, e.g. `(336, 168, 144, 24)` for four weeks of hourly data. With a single period (`period_length=input_length`), the past target is masked as a whole, like a covariate, without masking time steps. The explanation columns are named `period 1` (the oldest) to `period n`, or after the target for a single period.
109
+ - **Training on fewer windows:** `fit(window_stride=...)` trains and validates on every n-th window only, e.g. on windows that start at full hours of quarter-hourly data.
110
+ - **Instance normalization:** optional per-sample normalization of the target (`instance_norm="mean"` or `"RevIN"`).
111
+ - **Approximate explanations:** `explain(method="permutation")` estimates the Owen values from sampled permutations, much faster than the exact method (`method="exact"`, default).
112
+ - **Plots:** [plot.py](https://github.com/KIT-IAI/SHAPformer/blob/main/src/shapformer/plot.py) plots single explanations (`plot_explanation`) and dependence plots over many explanations (`plot_dependence`).
113
+ - **Example notebooks:** dataframe interface on TransnetBW, EPF-DE, solar and bike sharing data (see [Demos](#demos)).
114
+ - **Python package:** SHAPformer can be installed with `pip install shapformer` (version 1.0.0). The plots are optional (`shapformer[plot]`), and a test suite checks the explanations, the masking and the training.
115
+
116
+ ## Development
117
+
118
+ To work on the code, clone the repository and install it in editable mode with all extras:
119
+
120
+ ```bash
121
+ git clone https://github.com/KIT-IAI/SHAPformer.git
122
+ cd SHAPformer
123
+ pip install -e ".[examples,test]"
124
+ pytest
125
+ ```
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "shapformer"
7
+ version = "1.0.0"
8
+ description = "Explainable time-series forecasting with sampling-free SHAP for Transformers"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Matthias Hertel" }]
13
+ requires-python = ">=3.11"
14
+ keywords = ["explainable AI", "SHAP", "Shapley values", "Owen values", "time series", "forecasting", "transformer"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Science/Research",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: 3.14",
24
+ "Programming Language :: Python :: 3.15",
25
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
26
+ ]
27
+ dependencies = [
28
+ "numpy>=1.26",
29
+ "pandas>=2.2",
30
+ "scikit-learn>=1.3",
31
+ "scipy>=1.11",
32
+ "torch>=2.1",
33
+ "tqdm>=4.64",
34
+ ]
35
+
36
+ [project.optional-dependencies]
37
+ plot = ["matplotlib>=3.8"]
38
+ examples = ["shapformer[plot]", "notebook", "fev", "pyarrow", "workalendar"]
39
+ test = ["shapformer[plot]", "pytest>=8"]
40
+
41
+ [project.urls]
42
+ Repository = "https://github.com/KIT-IAI/SHAPformer"
43
+ Paper = "https://doi.org/10.1038/s41467-026-73243-5"
44
+
45
+ [tool.hatch.build.targets.wheel]
46
+ packages = ["src/shapformer"]
47
+
48
+ [tool.hatch.build.targets.sdist]
49
+ include = ["/src/shapformer", "/tests", "/README.md", "/LICENSE", "/pyproject.toml"]
50
+
51
+ [tool.pytest.ini_options]
52
+ testpaths = ["tests"]
53
+ filterwarnings = [
54
+ # pyparsing deprecations triggered inside matplotlib, not by this package
55
+ "ignore:.*deprecated - use:DeprecationWarning",
56
+ ]
@@ -0,0 +1,23 @@
1
+ """SHAPformer: explainable time-series forecasting with sampling-free SHAP for Transformers."""
2
+ from importlib.metadata import PackageNotFoundError, version
3
+
4
+ from .data import load_data
5
+ from .models.exogenous_transformer import ExogenousTransformer
6
+ from .models.shapformer import SHAPformer
7
+ from .shap import explain_sample
8
+
9
+ try:
10
+ __version__ = version("shapformer")
11
+ except PackageNotFoundError: # not installed, e.g. imported from a source checkout
12
+ __version__ = "unknown"
13
+
14
+ __all__ = ["SHAPformer", "ExogenousTransformer", "explain_sample", "load_data", "plot_explanation",
15
+ "plot_dependence", "__version__"]
16
+
17
+
18
+ def __getattr__(name):
19
+ # the plots need matplotlib (pip install shapformer[plot]), so they are only imported when used
20
+ if name in ("plot_explanation", "plot_dependence"):
21
+ from . import plot
22
+ return getattr(plot, name)
23
+ raise AttributeError(f"module 'shapformer' has no attribute '{name}'")
@@ -0,0 +1,20 @@
1
+ import json
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+
7
+ def load_data(path, device: Optional[str] = None):
8
+ # loads preprocessed samples (dictionaries with "x_enc", "x_dec" and "y") from a JSON file as tensors;
9
+ # device: where to put the tensors, by default the GPU if one is available, else the CPU
10
+ if device is None:
11
+ device = "cuda" if torch.cuda.is_available() else "cpu"
12
+ with open(path, "r") as f:
13
+ data = json.load(f)
14
+ for i in range(len(data)):
15
+ for key in data[i]["x_enc"]:
16
+ data[i]["x_enc"][key] = torch.tensor(data[i]["x_enc"][key], device=device)
17
+ for key in data[i]["x_dec"]:
18
+ data[i]["x_dec"][key] = torch.tensor(data[i]["x_dec"][key], device=device)
19
+ data[i]["y"] = torch.tensor(data[i]["y"], device=device)
20
+ return data
File without changes
@@ -0,0 +1,202 @@
1
+ from typing import Dict, List, Optional
2
+
3
+ import torch
4
+ from torch import nn
5
+ from .transformer_network import PositionalEncoding
6
+ from ..transformer.transformer import Transformer
7
+
8
+
9
+ class CategoricalEmbedding(nn.Module):
10
+ def __init__(self, n_embeddings, dim: int):
11
+ super(CategoricalEmbedding, self).__init__()
12
+ self.embedding = nn.Embedding(num_embeddings=n_embeddings, embedding_dim=dim)
13
+
14
+ def forward(self, x):
15
+ return self.embedding(x)
16
+
17
+
18
+ class LinearEmbedding(nn.Module):
19
+ def __init__(self, dim: int):
20
+ super(LinearEmbedding, self).__init__()
21
+ self.embedding = nn.Linear(1, dim)
22
+
23
+ def forward(self, x):
24
+ x = x.unsqueeze(-1)
25
+ return self.embedding(x)
26
+
27
+
28
+ class FeatureEmbedding(nn.Module):
29
+ def __init__(
30
+ self,
31
+ feature_names: List[str],
32
+ categories: List[Optional[int]],
33
+ dim: int,
34
+ dummy_feature: bool = False
35
+ ):
36
+ super(FeatureEmbedding, self).__init__()
37
+ self.feature_names = feature_names
38
+ self.categories = categories
39
+ self.dim = dim
40
+ self.embeddings = nn.ParameterDict()
41
+ self._initialize_embeddings()
42
+ self.attention = nn.MultiheadAttention(dim, num_heads=1, batch_first=True)
43
+ self.dummy_feature = dummy_feature
44
+ self.attention_weights = None
45
+ self.n_with_nans = 0
46
+ self.n_total = 0
47
+
48
+ def _initialize_embeddings(self):
49
+ for name, n_vals in zip(self.feature_names, self.categories):
50
+ if n_vals is None:
51
+ self.embeddings[name] = LinearEmbedding(self.dim)
52
+ else:
53
+ self.embeddings[name] = CategoricalEmbedding(n_vals, self.dim)
54
+
55
+ def forward(self, x: Dict[str, torch.Tensor], mask: torch.Tensor):
56
+ embeddings = []
57
+ for name in self.embeddings:
58
+ embd = self.embeddings[name](x[name])
59
+ embeddings.append(embd)
60
+ embeddings = torch.stack(embeddings, dim=-1)
61
+ batch_size = embeddings.shape[0]
62
+ seq_len = embeddings.shape[1]
63
+ embeddings = embeddings * mask[:, None, None, :]
64
+ n_active_features = torch.sum(mask, dim=-1)[:, None, None]
65
+ n_active_features[n_active_features == 0] = 1
66
+ embedding_sum = torch.sum(embeddings, dim=-1) / n_active_features
67
+ query = embedding_sum.reshape((-1, 1, self.dim))
68
+ embeddings = embeddings.transpose(2, 3)
69
+ key = embeddings.reshape((-1, embeddings.shape[2], embeddings.shape[3]))
70
+ if self.dummy_feature:
71
+ dummy_mask = torch.zeros((batch_size, 1), device=mask.device)
72
+ rows_without_features = torch.sum(mask, dim=1) == 0
73
+ dummy_mask[rows_without_features, :] = 1
74
+ mask = torch.concatenate((dummy_mask, mask), dim=1)
75
+ dummy_key = torch.zeros((key.shape[0], 1, self.dim), device=key.device)
76
+ key = torch.cat((dummy_key, key), dim=1)
77
+ attn_mask = 1 - mask
78
+ attn_mask[attn_mask == 1.0] = -torch.inf
79
+ attn_mask = attn_mask.repeat_interleave(168, dim=0)[:, None, :]
80
+ attn_output, attn_weights = self.attention(
81
+ query=query,
82
+ key=key,
83
+ value=key,
84
+ attn_mask=attn_mask
85
+ )
86
+ self.attention_weights = attn_weights
87
+ attn_output = attn_output.reshape((batch_size, seq_len, self.dim))
88
+ return attn_output
89
+
90
+
91
+ class ConcatEmbedding(nn.Module):
92
+ def __init__(
93
+ self,
94
+ feature_names: List[str],
95
+ categories: List[Optional[int]],
96
+ dim: int
97
+ ):
98
+ super(ConcatEmbedding, self).__init__()
99
+ self.feature_names = feature_names
100
+ self.categories = categories
101
+ self.dim = dim
102
+ self.linear = nn.Linear(len(feature_names) * 2, dim)
103
+
104
+ def _concatenate_mask_and_features(self, x: Dict[str, torch.Tensor], mask: torch.Tensor):
105
+ ts_len = x[list(x)[0]].shape[1]
106
+ mask_repeat = mask.repeat(1, ts_len, 1)
107
+ feature_values = [x[feature][:, :, None] for feature in x]
108
+ concatenated = torch.cat(feature_values, dim=-1)
109
+ concatenated = torch.cat((mask_repeat, concatenated), dim=-1)
110
+ return concatenated
111
+
112
+ def forward(self, x: Dict[str, torch.Tensor], mask: torch.Tensor):
113
+ concatenated = self._concatenate_mask_and_features(x, mask)
114
+ # apply mask:
115
+ concatenated[:, :, len(mask):] = concatenated[:, :, len(mask):] * mask
116
+ # linear transformation:
117
+ out = self.linear(concatenated)
118
+ return out
119
+
120
+
121
+ class ExogenousTransformer(nn.Module):
122
+ def __init__(
123
+ self,
124
+ encoder_feature_names: List[str],
125
+ encoder_categories: List[Optional[int]],
126
+ decoder_feature_names: List[str],
127
+ decoder_categories: List[Optional[int]],
128
+ d_model: int,
129
+ n_layers: int,
130
+ n_heads: int,
131
+ output_dimensions: int = 1,
132
+ embedding: str = "attention"
133
+ ):
134
+ super(ExogenousTransformer, self).__init__()
135
+ self.n_layers = n_layers
136
+ self.n_heads = n_heads
137
+ self.d_model = d_model
138
+ if embedding == "attention":
139
+ self.encoder_embedding = FeatureEmbedding(
140
+ feature_names=encoder_feature_names,
141
+ categories=encoder_categories,
142
+ dim=d_model
143
+ )
144
+ self.decoder_embedding = FeatureEmbedding(
145
+ feature_names=decoder_feature_names,
146
+ categories=decoder_categories,
147
+ dim=d_model,
148
+ dummy_feature=True
149
+ )
150
+ else:
151
+ self.encoder_embedding = ConcatEmbedding(
152
+ feature_names=encoder_feature_names,
153
+ categories=encoder_categories,
154
+ dim=d_model
155
+ )
156
+ self.decoder_embedding = ConcatEmbedding(
157
+ feature_names=decoder_feature_names,
158
+ categories=decoder_categories,
159
+ dim=d_model
160
+ )
161
+ self.positional_encoding = PositionalEncoding(d_model)
162
+ self.transformer = Transformer(
163
+ d_model=d_model,
164
+ nhead=n_heads,
165
+ num_encoder_layers=n_layers,
166
+ num_decoder_layers=n_layers,
167
+ dim_feedforward=d_model,
168
+ batch_first=True
169
+ )
170
+ self.projection = nn.Linear(d_model, output_dimensions)
171
+ self.relu = nn.ReLU()
172
+ self.output_dimensions = output_dimensions
173
+ self.cross_attention_weights = None
174
+ self.feature_names = encoder_feature_names
175
+
176
+ def _add_ghost_vector(self, embedding, attn_mask):
177
+ embedding_shape = embedding.shape
178
+ new_embedding = torch.zeros((embedding_shape[0], embedding_shape[1] + 1, embedding_shape[2]),
179
+ device=embedding.device)
180
+ new_embedding[:, 1:, :] = embedding
181
+ attn_mask_shape = attn_mask.shape
182
+ new_attn_mask = torch.zeros((attn_mask_shape[0], attn_mask_shape[1] + 1, attn_mask_shape[2] + 1),
183
+ device=attn_mask.device)
184
+ new_attn_mask[:, 1:, 1:] = attn_mask
185
+ new_attn_mask[:, 0, 1:] = -torch.inf
186
+ return new_embedding, new_attn_mask
187
+
188
+ def forward(self, x_enc, x_dec, mask_enc, mask_dec, attn_mask):
189
+ enc_embedding = self.encoder_embedding(x_enc, mask_enc)
190
+ enc_embedding += self.positional_encoding(enc_embedding)
191
+ enc_embedding, attn_mask = self._add_ghost_vector(enc_embedding, attn_mask)
192
+ dec_embedding = self.decoder_embedding(x_dec, mask_dec)
193
+ dec_embedding += self.positional_encoding(dec_embedding)
194
+ attn_mask = attn_mask.repeat_interleave(self.n_heads, dim=0)
195
+ out = self.transformer(enc_embedding, dec_embedding, src_mask=attn_mask, memory_mask=attn_mask[:, 1:, :])
196
+ out = self.projection(self.relu(out))
197
+ if self.output_dimensions == 1:
198
+ out = out[:, :, 0]
199
+ return out
200
+
201
+ def get_device(self):
202
+ return next(self.parameters()).device