shapformer 1.0.0__py3-none-any.whl

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.
shapformer/__init__.py ADDED
@@ -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}'")
shapformer/data.py ADDED
@@ -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