tabsil 0.1.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.
- tabsil/__init__.py +72 -0
- tabsil/hub/__init__.py +169 -0
- tabsil/inference/__init__.py +12 -0
- tabsil/inference/ensemble.py +455 -0
- tabsil/inference/preprocessing.py +249 -0
- tabsil/inference/subsample.py +94 -0
- tabsil/models/__init__.py +165 -0
- tabsil/models/bar_distribution.py +194 -0
- tabsil/models/column_row_transformer.py +1535 -0
- tabsil/models/quantile_distribution.py +86 -0
- tabsil/py.typed +0 -0
- tabsil/recipe.py +190 -0
- tabsil/utils.py +27 -0
- tabsil-0.1.0.dist-info/METADATA +179 -0
- tabsil-0.1.0.dist-info/RECORD +19 -0
- tabsil-0.1.0.dist-info/WHEEL +4 -0
- tabsil-0.1.0.dist-info/licenses/LICENSE +202 -0
- tabsil-0.1.0.dist-info/licenses/LICENSES/TabICL-BSD-3-Clause.txt +28 -0
- tabsil-0.1.0.dist-info/licenses/NOTICE +23 -0
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
"""Preprocessing member ensemble: sklearn-style `EnsembleClassifier` and `EnsembleRegressor` for a
|
|
2
|
+
model with `forward(x, y_train, task)` (the `tabsil.models` model).
|
|
3
|
+
|
|
4
|
+
clf = EnsembleClassifier(model, n_estimators=8).fit(x_train, y_train)
|
|
5
|
+
proba = clf.predict_proba(x_test)
|
|
6
|
+
|
|
7
|
+
`tabsil.recipe.TabSilClassifier` and `TabSilRegressor` set TabSil's defaults (8 `standard` members,
|
|
8
|
+
at most 768 columns per member chosen `balanced`).
|
|
9
|
+
|
|
10
|
+
`fit` trains no weights. Each member fits its preprocessing to the training rows
|
|
11
|
+
(`tabsil.inference.preprocessing`), and prediction runs the training and test rows through the
|
|
12
|
+
model together.
|
|
13
|
+
|
|
14
|
+
- per member: shuffled feature order, (classification) shuffled class indices, and a sample
|
|
15
|
+
identifier column of standard normal noise
|
|
16
|
+
- numeric values more than 12 standard deviations from the column mean are clipped to that bound
|
|
17
|
+
- categorical columns are one-hot encoded; columns with more than `MAX_ONE_HOT_CATEGORIES`
|
|
18
|
+
categories stay codes. If the column count after expansion exceeds `max_one_hot_width`
|
|
19
|
+
(default: `max_features` of the model config, the feature count seen in training, or
|
|
20
|
+
`MAX_FEATURES` if the config has none), columns revert to codes starting from the one with the
|
|
21
|
+
most categories. Two categories become one 0/1 column. Missing values and categories unseen in
|
|
22
|
+
training (which become missing when encoded) are NaN
|
|
23
|
+
- (with `max_features_per_member`) on tables with more features than that, each member picks that
|
|
24
|
+
many original columns: `feature_subsampling="random"` draws independently per member
|
|
25
|
+
(`tabsil.inference.preprocessing.feature_subset`), `"balanced"` spreads the columns evenly
|
|
26
|
+
- classification: softmax of the logits divided by a temperature (`softmax_temperature`, default
|
|
27
|
+
0.9), averaged over members
|
|
28
|
+
- regression: y is z-normalized, and half of the members also apply a power transform to y (off,
|
|
29
|
+
off, on, on, ...), exactly half when the member count is a multiple of 4. The model's 999
|
|
30
|
+
quantile outputs become bucket probabilities on the regression borders per member (no
|
|
31
|
+
temperature, `tabsil.models.quantile_distribution.quantiles_to_bucket_probs`). For the predictive
|
|
32
|
+
distribution only the borders are inverse-transformed, moved onto the common borders, and
|
|
33
|
+
averaged
|
|
34
|
+
|
|
35
|
+
Choices for the regression prediction (the mean):
|
|
36
|
+
|
|
37
|
+
- Values of the two tail buckets: in the borders built from the prior the outermost buckets are
|
|
38
|
+
very wide (z width 24-28), so the mean of a half-normal tail lands near z ±34. On data whose
|
|
39
|
+
training targets go beyond the inner borders (skewed y), the 1-2% of probability in the tails
|
|
40
|
+
would be valued that far out and shift the prediction a lot, so a tail bucket is valued at the
|
|
41
|
+
end of the training target range (only when that lies beyond the inner border, clipped inside
|
|
42
|
+
the outermost border).
|
|
43
|
+
- The mean is computed per member in its own space rather than on the common borders; target
|
|
44
|
+
power members inverse-transform their bucket values. Moving to the common borders assumes a
|
|
45
|
+
uniform density within each bucket, so when mass is concentrated near a common border
|
|
46
|
+
(cpu_activity's y=0, just above an inner border) part of the probability leaks into a tail
|
|
47
|
+
bucket.
|
|
48
|
+
- Depending on λ, the Yeo-Johnson inverse is undefined (NaN) beyond one end and arbitrarily steep
|
|
49
|
+
near it. Values outside the training target range are set to its end values, so the bucket
|
|
50
|
+
values of target power members lie within the training target range.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
from __future__ import annotations
|
|
54
|
+
|
|
55
|
+
import contextlib
|
|
56
|
+
from typing import Any
|
|
57
|
+
|
|
58
|
+
import numpy as np
|
|
59
|
+
import pandas as pd
|
|
60
|
+
import torch
|
|
61
|
+
from sklearn.preprocessing import LabelEncoder, PowerTransformer
|
|
62
|
+
from torch import nn
|
|
63
|
+
|
|
64
|
+
from tabsil.inference.preprocessing import (
|
|
65
|
+
FEATURE_SUBSAMPLINGS,
|
|
66
|
+
MEMBER_KINDS,
|
|
67
|
+
Member,
|
|
68
|
+
MemberPreprocessor,
|
|
69
|
+
apply_encoder,
|
|
70
|
+
balanced_feature_subsets,
|
|
71
|
+
feature_subset,
|
|
72
|
+
row_hashes,
|
|
73
|
+
row_identifier,
|
|
74
|
+
select_features,
|
|
75
|
+
to_numeric,
|
|
76
|
+
)
|
|
77
|
+
from tabsil.models.quantile_distribution import quantiles_to_bucket_probs
|
|
78
|
+
|
|
79
|
+
# One-hot width cap of a model whose config records no feature cap (`max_features_of`)
|
|
80
|
+
MAX_FEATURES = 160
|
|
81
|
+
|
|
82
|
+
SOFTMAX_TEMPERATURE = 0.9
|
|
83
|
+
DEFAULT_MEMBER_KINDS = MEMBER_KINDS
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def resolve_member_kinds(
|
|
87
|
+
value: str | tuple[str, ...] | list[str], presets: dict[str, tuple[str, ...]] | None = None
|
|
88
|
+
) -> tuple[str, ...]:
|
|
89
|
+
"""Member preprocessing kinds: a name in `presets` (the recipe's `MEMBER_KIND_PRESETS`), a comma
|
|
90
|
+
separated string, or a sequence of kinds from `MEMBER_KINDS`."""
|
|
91
|
+
presets = presets or {}
|
|
92
|
+
if isinstance(value, str):
|
|
93
|
+
if value in presets:
|
|
94
|
+
return presets[value]
|
|
95
|
+
value = [k.strip() for k in value.split(",") if k.strip()]
|
|
96
|
+
kinds = tuple(value)
|
|
97
|
+
if not kinds or set(kinds) - set(MEMBER_KINDS):
|
|
98
|
+
names = f" or one of the presets {tuple(presets)}" if presets else ""
|
|
99
|
+
raise ValueError(f"member_kinds are chosen from {MEMBER_KINDS}{names}: {value}")
|
|
100
|
+
return kinds
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def max_features_of(model: nn.Module) -> int:
|
|
104
|
+
"""The feature cap the model saw in training (`config.max_features`).
|
|
105
|
+
|
|
106
|
+
It is not part of the registry contract, so `MAX_FEATURES` is used when it is missing. Shared
|
|
107
|
+
by the inference defaults and the evaluation scripts."""
|
|
108
|
+
return getattr(model.config, "max_features", MAX_FEATURES)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def max_classes_of(model: nn.Module) -> int:
|
|
112
|
+
"""The maximum number of classes for classification: the model's `max_classes` (the
|
|
113
|
+
column_row_transformer retrieval decoder groups label embeddings and accepts more classes than
|
|
114
|
+
outputs), else the output count (`config.n_out`). Shared by `EnsembleClassifier` and the
|
|
115
|
+
TabArena/BeyondArena limits of the evaluation scripts."""
|
|
116
|
+
return int(getattr(model, "max_classes", model.config.n_out))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def forward_kwargs(model: nn.Module, task: str) -> dict:
|
|
120
|
+
"""Keyword arguments for the model forward: the task, and `inference=True` (the
|
|
121
|
+
memory-saving computation of large tables) for a model that takes inference options
|
|
122
|
+
(`supports_inference_options`)."""
|
|
123
|
+
kwargs = {"task": task}
|
|
124
|
+
if getattr(model, "supports_inference_options", False):
|
|
125
|
+
kwargs["inference"] = True
|
|
126
|
+
return kwargs
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class _Base:
|
|
130
|
+
# the task this ensemble predicts (passed to the forward of a multitask model)
|
|
131
|
+
task = ""
|
|
132
|
+
|
|
133
|
+
def __init__(
|
|
134
|
+
self,
|
|
135
|
+
model: nn.Module,
|
|
136
|
+
*,
|
|
137
|
+
n_estimators: int,
|
|
138
|
+
categorical_features_indices: list[int] | None = None,
|
|
139
|
+
member_kinds: tuple[str, ...] | str = DEFAULT_MEMBER_KINDS,
|
|
140
|
+
softmax_temperature: float = SOFTMAX_TEMPERATURE,
|
|
141
|
+
max_one_hot_width: int | None = None,
|
|
142
|
+
max_features_per_member: int | None = None,
|
|
143
|
+
feature_subsampling: str = "random",
|
|
144
|
+
device: str = "cpu",
|
|
145
|
+
random_state: int = 0,
|
|
146
|
+
) -> None:
|
|
147
|
+
if feature_subsampling not in FEATURE_SUBSAMPLINGS:
|
|
148
|
+
raise ValueError(
|
|
149
|
+
f"feature_subsampling is one of {FEATURE_SUBSAMPLINGS}: {feature_subsampling}"
|
|
150
|
+
)
|
|
151
|
+
self.feature_subsampling = feature_subsampling
|
|
152
|
+
# `member_kinds` is kept for the saved inference settings; TabSil has one kind, "standard"
|
|
153
|
+
self.member_kinds = resolve_member_kinds(member_kinds)
|
|
154
|
+
self.softmax_temperature = softmax_temperature
|
|
155
|
+
# cap on the column count after one-hot expansion: the feature count the model saw in
|
|
156
|
+
# training (max_features of the model config)
|
|
157
|
+
if max_one_hot_width is None:
|
|
158
|
+
max_one_hot_width = max_features_of(model)
|
|
159
|
+
self.max_one_hot_width = max_one_hot_width
|
|
160
|
+
# cap on the original features one member uses (None: all, `feature_subsets`)
|
|
161
|
+
self.max_features_per_member = max_features_per_member
|
|
162
|
+
self.model = model
|
|
163
|
+
self.n_estimators = n_estimators
|
|
164
|
+
self.categorical_features_indices = categorical_features_indices
|
|
165
|
+
self.device = torch.device(device)
|
|
166
|
+
self.random_state = random_state
|
|
167
|
+
|
|
168
|
+
def _fit_members(self, X: Any, members: list[Member]) -> None:
|
|
169
|
+
# training rows as a numeric array: `cat_ix_` are the categorical columns (strings and
|
|
170
|
+
# categories turned into codes)
|
|
171
|
+
X_num, self.cat_ix_, self.encoder_ = to_numeric(X, self.categorical_features_indices)
|
|
172
|
+
# columns per member (only when features exceed the cap; set from the member seed, so a
|
|
173
|
+
# member always gets the same columns)
|
|
174
|
+
if self.feature_subsampling == "balanced":
|
|
175
|
+
rng = np.random.default_rng([m.seed for m in members])
|
|
176
|
+
self.feature_subsets_ = balanced_feature_subsets(
|
|
177
|
+
X_num.shape[1], self.max_features_per_member, len(members), rng
|
|
178
|
+
)
|
|
179
|
+
else:
|
|
180
|
+
self.feature_subsets_ = [
|
|
181
|
+
feature_subset(X_num.shape[1], self.max_features_per_member, m.seed + 4)
|
|
182
|
+
for m in members
|
|
183
|
+
]
|
|
184
|
+
self.preprocessors_ = []
|
|
185
|
+
self.X_trains_ = []
|
|
186
|
+
for m, cols in zip(members, self.feature_subsets_, strict=True):
|
|
187
|
+
x, cat_ix = select_features(X_num, self.cat_ix_, cols)
|
|
188
|
+
prep = MemberPreprocessor(m, cat_ix, self.max_one_hot_width).fit(x)
|
|
189
|
+
self.preprocessors_.append(prep)
|
|
190
|
+
# the transformed training rows do not change, so compute them once per member
|
|
191
|
+
identifier = np.random.default_rng(m.seed + 2).standard_normal((x.shape[0], 1))
|
|
192
|
+
self.X_trains_.append(prep.transform(x, identifier))
|
|
193
|
+
|
|
194
|
+
def _model_targets(self, y: torch.Tensor) -> tuple[torch.Tensor, dict]:
|
|
195
|
+
"""The training-row targets for the model (1, train rows) and extra forward kwargs."""
|
|
196
|
+
return y, {}
|
|
197
|
+
|
|
198
|
+
def _iter_inputs(self, X: Any, y_trains: list[np.ndarray]):
|
|
199
|
+
"""Per member (index, model input x (1, train + test rows, F), y_train (1, train rows))."""
|
|
200
|
+
X_test = apply_encoder(pd.DataFrame(X), self.cat_ix_, self.encoder_)
|
|
201
|
+
# a test row's identifier depends on that row only (not on the batch or row order): a hash
|
|
202
|
+
# of all its encoded values, hashed once and mixed with each member's seed
|
|
203
|
+
hashes = row_hashes(X_test)
|
|
204
|
+
for i, (prep, y_train) in enumerate(zip(self.preprocessors_, y_trains, strict=True)):
|
|
205
|
+
x_test, _ = select_features(X_test, self.cat_ix_, self.feature_subsets_[i])
|
|
206
|
+
x_test = prep.transform(x_test, row_identifier(hashes, prep.member.seed + 3))
|
|
207
|
+
x = np.concatenate([self.X_trains_[i], x_test])
|
|
208
|
+
x = torch.as_tensor(x, dtype=torch.float32, device=self.device).unsqueeze(0)
|
|
209
|
+
y = torch.as_tensor(y_train, dtype=torch.float32, device=self.device).unsqueeze(0)
|
|
210
|
+
yield i, x, y
|
|
211
|
+
|
|
212
|
+
def _iter_logits(self, X: Any, y_trains: list[np.ndarray]):
|
|
213
|
+
model = self.model.to(self.device).eval()
|
|
214
|
+
autocast = self.device.type == "cuda" # bfloat16, as in training
|
|
215
|
+
kwargs = forward_kwargs(model, self.task)
|
|
216
|
+
# member forwards reuse one large CPU buffer (the cell state of the interleaved
|
|
217
|
+
# column_row_transformer), released after the last member (also on an exception)
|
|
218
|
+
hold = getattr(model, "hold_host_state", None)
|
|
219
|
+
with hold() if hold is not None else contextlib.nullcontext():
|
|
220
|
+
for i, x, y in self._iter_inputs(X, y_trains):
|
|
221
|
+
y, extra = self._model_targets(y)
|
|
222
|
+
with (
|
|
223
|
+
torch.autocast(self.device.type, dtype=torch.bfloat16, enabled=autocast),
|
|
224
|
+
torch.inference_mode(),
|
|
225
|
+
):
|
|
226
|
+
logits = model(x, y, **kwargs, **extra)[0].float()
|
|
227
|
+
# yielded outside autocast: the consumer's math (e.g. the regression mean matmul)
|
|
228
|
+
# runs in float32
|
|
229
|
+
yield i, logits
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class EnsembleClassifier(_Base):
|
|
233
|
+
"""Classification: shuffle the class indices per member, softmax the logits divided by a
|
|
234
|
+
temperature, and average.
|
|
235
|
+
|
|
236
|
+
More classes than model outputs (`config.n_out`, the number of label embeddings) are accepted
|
|
237
|
+
only by a retrieval decoder model (one with a larger `max_classes_of`, column_row_transformer).
|
|
238
|
+
The label embedding gets the shuffled index modulo `n_out` (its group), the decoder gets the
|
|
239
|
+
shuffled index itself. The decoder averages the training rows' original-class one-hots with
|
|
240
|
+
its attention weights, so every class gets a probability. Indices are shuffled per member, so
|
|
241
|
+
the classes sharing an embedding differ between members. With 11 classes only one group has 2.
|
|
242
|
+
(Our choice; the official TabPFN-3.5 learns 160 label embeddings and does not group them.)
|
|
243
|
+
"""
|
|
244
|
+
|
|
245
|
+
task = "classification"
|
|
246
|
+
|
|
247
|
+
def fit(self, X: Any, y: Any) -> EnsembleClassifier:
|
|
248
|
+
rng = np.random.default_rng(self.random_state)
|
|
249
|
+
y = self._fit_labels(y)
|
|
250
|
+
return self.fit_members(X, y, self._default_members(rng, len(self.classes_)))
|
|
251
|
+
|
|
252
|
+
def _default_members(self, rng: np.random.Generator, n_classes: int) -> list[Member]:
|
|
253
|
+
return [
|
|
254
|
+
Member(
|
|
255
|
+
class_permutation=rng.permutation(n_classes),
|
|
256
|
+
target_power=False,
|
|
257
|
+
seed=int(rng.integers(0, 2**31 - 1)),
|
|
258
|
+
)
|
|
259
|
+
for i in range(self.n_estimators)
|
|
260
|
+
]
|
|
261
|
+
|
|
262
|
+
def _fit_labels(self, y: Any) -> np.ndarray:
|
|
263
|
+
"""Set the classes (`classes_`) and return the targets as indices starting at 0."""
|
|
264
|
+
self.label_encoder_ = LabelEncoder()
|
|
265
|
+
y = self.label_encoder_.fit_transform(np.asarray(y))
|
|
266
|
+
self.classes_ = self.label_encoder_.classes_
|
|
267
|
+
n_classes = len(self.classes_)
|
|
268
|
+
if n_classes > max_classes_of(self.model):
|
|
269
|
+
raise ValueError(
|
|
270
|
+
f"{n_classes} classes exceed what the model accepts ({max_classes_of(self.model)})."
|
|
271
|
+
)
|
|
272
|
+
return y
|
|
273
|
+
|
|
274
|
+
def _model_targets(self, y: torch.Tensor) -> tuple[torch.Tensor, dict]:
|
|
275
|
+
# with more classes than label embeddings: group index for the embedding, original index
|
|
276
|
+
# for the decoder (class docstring)
|
|
277
|
+
n_out, n_classes = self.model.config.n_out, len(self.classes_)
|
|
278
|
+
if n_classes <= n_out:
|
|
279
|
+
return y, {}
|
|
280
|
+
return torch.remainder(y, n_out), {"y_classes": y, "n_classes": n_classes}
|
|
281
|
+
|
|
282
|
+
def fit_members(self, X: Any, y: np.ndarray, members: list[Member]) -> EnsembleClassifier:
|
|
283
|
+
"""Fit with the given members. `y` holds `classes_` indices (after `_fit_labels`)."""
|
|
284
|
+
self._fit_members(X, members)
|
|
285
|
+
# each member gets the training targets as shuffled indices: original class c -> perm[c]
|
|
286
|
+
self.y_trains_ = [m.class_permutation[y] for m in members]
|
|
287
|
+
return self
|
|
288
|
+
|
|
289
|
+
def member_logits(self, X: Any):
|
|
290
|
+
"""Per member (index, logits in the original class order (n, n_classes))."""
|
|
291
|
+
n_classes = len(self.classes_)
|
|
292
|
+
with contextlib.closing(self._iter_logits(X, self.y_trains_)) as members:
|
|
293
|
+
for i, logits in members:
|
|
294
|
+
perm = self.preprocessors_[i].member.class_permutation
|
|
295
|
+
yield i, logits[:, :n_classes][:, perm] # shuffled-index logits back to class order
|
|
296
|
+
|
|
297
|
+
def predict_proba(self, X: Any) -> np.ndarray:
|
|
298
|
+
with contextlib.closing(self.member_logits(X)) as members:
|
|
299
|
+
probs = [
|
|
300
|
+
torch.softmax(logits / self.softmax_temperature, dim=-1) for _, logits in members
|
|
301
|
+
]
|
|
302
|
+
return torch.stack(probs).mean(0).cpu().numpy()
|
|
303
|
+
|
|
304
|
+
def predict(self, X: Any) -> np.ndarray:
|
|
305
|
+
return self.classes_[self.predict_proba(X).argmax(axis=1)]
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _probs_on_borders(probs: torch.Tensor, frm: torch.Tensor, to: torch.Tensor) -> torch.Tensor:
|
|
309
|
+
"""Move bucket probabilities on borders `frm` onto borders `to` (uniform within a bucket)."""
|
|
310
|
+
cdf = torch.cat([torch.zeros_like(probs[:, :1]), probs.cumsum(-1)], dim=-1) # CDF on frm
|
|
311
|
+
idx = (torch.searchsorted(frm, to) - 1).clamp(0, len(frm) - 2)
|
|
312
|
+
width = (frm[idx + 1] - frm[idx]).clamp_min(1e-12)
|
|
313
|
+
share = ((to - frm[idx]) / width).clamp(0, 1)
|
|
314
|
+
at_to = cdf[:, idx] + probs[:, idx] * share
|
|
315
|
+
at_to[:, to <= frm[0]] = 0.0
|
|
316
|
+
at_to[:, to >= frm[-1]] = 1.0
|
|
317
|
+
at_to[:, 0], at_to[:, -1] = 0.0, 1.0
|
|
318
|
+
return (at_to[:, 1:] - at_to[:, :-1]).clamp_min(0)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _clipped_inverse(transform: PowerTransformer, u_train: np.ndarray):
|
|
322
|
+
"""Inverse of the power transform, with values outside the training target range [lo, hi]
|
|
323
|
+
set to its end values.
|
|
324
|
+
|
|
325
|
+
The inverse is undefined beyond the right end for λ < 0 and beyond the left end for λ > 2, and
|
|
326
|
+
arbitrarily steep near it, so extending it past the range (even linearly with the end slope)
|
|
327
|
+
sends z into the thousands.
|
|
328
|
+
"""
|
|
329
|
+
lo, hi = float(u_train.min()), float(u_train.max())
|
|
330
|
+
|
|
331
|
+
def g(u: np.ndarray) -> np.ndarray:
|
|
332
|
+
u = np.clip(np.asarray(u, dtype=np.float64).reshape(-1, 1), lo, hi)
|
|
333
|
+
with np.errstate(all="ignore"):
|
|
334
|
+
return transform.inverse_transform(u).ravel()
|
|
335
|
+
|
|
336
|
+
return g
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _bucket_values(borders: torch.Tensor, u_train: np.ndarray) -> np.ndarray:
|
|
340
|
+
"""The value of each bucket for the mean: inner buckets use their midpoint, the two tail
|
|
341
|
+
buckets the ends of the training target range.
|
|
342
|
+
|
|
343
|
+
Tail values are clipped inside the outermost borders (so a single extreme row does not set
|
|
344
|
+
them).
|
|
345
|
+
"""
|
|
346
|
+
b = borders.double().numpy()
|
|
347
|
+
values = (b[1:] + b[:-1]) / 2
|
|
348
|
+
values[0] = max(b[0], min(b[1], float(u_train.min())))
|
|
349
|
+
values[-1] = min(b[-1], max(b[-2], float(u_train.max())))
|
|
350
|
+
return values
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
class EnsembleRegressor(_Base):
|
|
354
|
+
"""Regression: bucket probabilities computed per member in its own space and averaged (module
|
|
355
|
+
docstring). Half of the members apply a Yeo-Johnson power transform to the target."""
|
|
356
|
+
|
|
357
|
+
task = "regression"
|
|
358
|
+
|
|
359
|
+
def __init__(self, model: nn.Module, borders: torch.Tensor, **kwargs: Any) -> None:
|
|
360
|
+
super().__init__(model, **kwargs)
|
|
361
|
+
self.borders = borders.float().cpu() # moved to the device only to compute; results on CPU
|
|
362
|
+
|
|
363
|
+
def fit(self, X: Any, y: Any) -> EnsembleRegressor:
|
|
364
|
+
rng = np.random.default_rng(self.random_state)
|
|
365
|
+
return self.fit_members(X, y, self._default_members(rng))
|
|
366
|
+
|
|
367
|
+
def _default_members(self, rng: np.random.Generator) -> list[Member]:
|
|
368
|
+
return [
|
|
369
|
+
Member(
|
|
370
|
+
class_permutation=None,
|
|
371
|
+
target_power=(i // 2) % 2 == 1, # off, off, on, on, ...
|
|
372
|
+
seed=int(rng.integers(0, 2**31 - 1)),
|
|
373
|
+
)
|
|
374
|
+
for i in range(self.n_estimators)
|
|
375
|
+
]
|
|
376
|
+
|
|
377
|
+
def fit_members(self, X: Any, y: Any, members: list[Member]) -> EnsembleRegressor:
|
|
378
|
+
"""Fit with the given members. `y` is in original units."""
|
|
379
|
+
y = np.asarray(y, dtype=np.float64)
|
|
380
|
+
self.y_mean_, self.y_std_ = float(y.mean()), float(y.std()) + 1e-12
|
|
381
|
+
z = (y - self.y_mean_) / self.y_std_
|
|
382
|
+
self._fit_members(X, members)
|
|
383
|
+
b = self.borders.double().numpy()
|
|
384
|
+
self.y_trains_, self.bucket_values_, self.border_maps_ = [], [], []
|
|
385
|
+
for m in members:
|
|
386
|
+
u, values, border_map = z, _bucket_values(self.borders, z), None
|
|
387
|
+
if m.target_power:
|
|
388
|
+
transform = PowerTransformer(method="yeo-johnson", standardize=True)
|
|
389
|
+
u = np.asarray(transform.fit_transform(z.reshape(-1, 1))).ravel()
|
|
390
|
+
inverse = _clipped_inverse(transform, u)
|
|
391
|
+
# bucket values and borders from member space to z space (the borders are used
|
|
392
|
+
# by predict_distribution)
|
|
393
|
+
values = np.clip(inverse(_bucket_values(self.borders, u)), b[0], b[-1])
|
|
394
|
+
back = np.clip(np.maximum.accumulate(inverse(b)), b[0], b[-1])
|
|
395
|
+
border_map = torch.as_tensor(back, dtype=torch.float32)
|
|
396
|
+
self.y_trains_.append(u)
|
|
397
|
+
self.bucket_values_.append(torch.as_tensor(values, dtype=torch.float32))
|
|
398
|
+
self.border_maps_.append(border_map)
|
|
399
|
+
return self
|
|
400
|
+
|
|
401
|
+
def predict_distribution(self, X: Any) -> tuple[torch.Tensor, torch.Tensor]:
|
|
402
|
+
"""(bucket log probabilities (n, n_buckets), borders in original units (float64)).
|
|
403
|
+
|
|
404
|
+
The mixture of the members moved onto the common borders. Its tails are the common
|
|
405
|
+
borders' half-normal tails, so the mean of this distribution differs from `predict` (use
|
|
406
|
+
`predict` for the mean). Borders are mapped to original units in float64: inner buckets
|
|
407
|
+
are as narrow as 1e-6 in z, so with a large target mean and small spread several borders
|
|
408
|
+
would collapse to one value in float32.
|
|
409
|
+
"""
|
|
410
|
+
with contextlib.closing(self._member_probs(X)) as members:
|
|
411
|
+
probs = [self._on_common_borders(i, p) for i, p in members]
|
|
412
|
+
return self._mixture(probs)
|
|
413
|
+
|
|
414
|
+
def predict(self, X: Any) -> np.ndarray:
|
|
415
|
+
"""Mean of the predictive distribution. The mean of the member mixture is the average of
|
|
416
|
+
the member means, so each member uses its own bucket values (`bucket_values_`) without
|
|
417
|
+
moving to the common borders."""
|
|
418
|
+
with contextlib.closing(self._member_probs(X)) as members:
|
|
419
|
+
return self._mean([self._member_mean(i, p) for i, p in members])
|
|
420
|
+
|
|
421
|
+
def predict_full(self, X: Any) -> tuple[np.ndarray, torch.Tensor, torch.Tensor]:
|
|
422
|
+
"""(the `predict` mean, the `predict_distribution` log probabilities and borders) from one
|
|
423
|
+
forward pass. Distribution-quality evaluation (`tabsil_train.benchmarks.uncertainty`) uses
|
|
424
|
+
the point prediction and the distribution together."""
|
|
425
|
+
means, probs = [], []
|
|
426
|
+
with contextlib.closing(self._member_probs(X)) as members:
|
|
427
|
+
for i, p in members:
|
|
428
|
+
means.append(self._member_mean(i, p))
|
|
429
|
+
probs.append(self._on_common_borders(i, p))
|
|
430
|
+
return (self._mean(means), *self._mixture(probs))
|
|
431
|
+
|
|
432
|
+
def _member_probs(self, X: Any):
|
|
433
|
+
"""Per member (index, bucket probabilities in its own space): the quantile outputs turned
|
|
434
|
+
into bucket probabilities on the borders, without a temperature (module docstring)."""
|
|
435
|
+
with contextlib.closing(self._iter_logits(X, self.y_trains_)) as members:
|
|
436
|
+
for i, logits in members:
|
|
437
|
+
p = quantiles_to_bucket_probs(logits, self.borders)
|
|
438
|
+
yield i, torch.softmax(p.clamp_min(1e-30).log(), dim=-1)
|
|
439
|
+
|
|
440
|
+
def _member_mean(self, i: int, p: torch.Tensor) -> torch.Tensor:
|
|
441
|
+
return p @ self.bucket_values_[i].to(p.device)
|
|
442
|
+
|
|
443
|
+
def _mean(self, means: list[torch.Tensor]) -> np.ndarray:
|
|
444
|
+
return torch.stack(means).mean(0).cpu().numpy() * self.y_std_ + self.y_mean_
|
|
445
|
+
|
|
446
|
+
def _on_common_borders(self, i: int, p: torch.Tensor) -> torch.Tensor:
|
|
447
|
+
if self.border_maps_[i] is None:
|
|
448
|
+
return p
|
|
449
|
+
# move the probabilities from the power-transformed borders mapped back to z space
|
|
450
|
+
borders = self.borders.to(p.device)
|
|
451
|
+
return _probs_on_borders(p, self.border_maps_[i].to(p.device), borders)
|
|
452
|
+
|
|
453
|
+
def _mixture(self, probs: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
|
|
454
|
+
log_probs = torch.stack(probs).mean(0).clamp_min(1e-12).log().cpu()
|
|
455
|
+
return log_probs, self.borders.double() * self.y_std_ + self.y_mean_
|