FirePFN 1.0.0.dev0__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.
Potentially problematic release.
This version of FirePFN might be problematic. Click here for more details.
- firepfn/__init__.py +7 -0
- firepfn/class_tree.py +77 -0
- firepfn/classifier.py +301 -0
- firepfn/encoding.py +347 -0
- firepfn/ensemble.py +44 -0
- firepfn/eval/__init__.py +14 -0
- firepfn/eval/analysis.py +294 -0
- firepfn/eval/plots.py +330 -0
- firepfn/eval/runtime.py +205 -0
- firepfn/eval/tabarena.py +388 -0
- firepfn/loading.py +97 -0
- firepfn/many_class.py +157 -0
- firepfn/model/__init__.py +5 -0
- firepfn/model/_mamba_block.py +49 -0
- firepfn/model/backbone.py +110 -0
- firepfn/model/cross_attention.py +123 -0
- firepfn/model/deltanet.py +134 -0
- firepfn/model/fire_pfn.py +396 -0
- firepfn/model/fla_autotune.py +73 -0
- firepfn/model/hydra2.py +537 -0
- firepfn/model/int32_safe.py +122 -0
- firepfn/model/kumo.py +704 -0
- firepfn/model/linear_attention.py +167 -0
- firepfn/model/stream_infer.py +568 -0
- firepfn/model/triton_rmsnorm.py +119 -0
- firepfn/model/triton_rope.py +152 -0
- firepfn/preprocessing.py +301 -0
- firepfn/train/__init__.py +3 -0
- firepfn/train/__main__.py +57 -0
- firepfn/train/_tabicl_dataset.py +1762 -0
- firepfn/train/configs.py +113 -0
- firepfn/train/loop.py +224 -0
- firepfn/train/optim.py +109 -0
- firepfn/train/prior.py +74 -0
- firepfn/train/schedule.py +125 -0
- firepfn-1.0.0.dev0.dist-info/METADATA +270 -0
- firepfn-1.0.0.dev0.dist-info/RECORD +46 -0
- firepfn-1.0.0.dev0.dist-info/WHEEL +5 -0
- firepfn-1.0.0.dev0.dist-info/licenses/AUTHORS +14 -0
- firepfn-1.0.0.dev0.dist-info/licenses/LICENSE +33 -0
- firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/Apache-2.0.txt +176 -0
- firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/BSD-3-Clause-TabICL.txt +236 -0
- firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/MIT-Hydra.txt +21 -0
- firepfn-1.0.0.dev0.dist-info/licenses/LICENSES/OpenMDW-1.1-Kumo-Tabular-weights.txt +52 -0
- firepfn-1.0.0.dev0.dist-info/licenses/NOTICE +39 -0
- firepfn-1.0.0.dev0.dist-info/top_level.txt +1 -0
firepfn/encoding.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Copyright (c) 2025-2026, the FirePFN authors.
|
|
3
|
+
"""DataFrame input for FirePFN: encoding of non-numeric columns.
|
|
4
|
+
|
|
5
|
+
FirePFNClassifier takes numeric arrays. Real tables come as pandas DataFrames with categorical,
|
|
6
|
+
string, boolean or nullable columns. Two wrappers turn them into numbers:
|
|
7
|
+
|
|
8
|
+
- ``OrdinalEncodedClassifier`` ordinal-encodes every non-numeric column (categories in sorted
|
|
9
|
+
order, unseen categories -> -1, missing stays NaN; FirePFN handles missing values itself) and
|
|
10
|
+
maps predictions back to the original labels.
|
|
11
|
+
- ``TargetEncodedClassifier`` first replaces high-cardinality categorical columns (more than
|
|
12
|
+
``min_levels`` distinct training values, default 500) by their target encoding, on binary
|
|
13
|
+
tasks only by default. Ordinal codes of such columns carry almost no signal; their target
|
|
14
|
+
encoding does. Date/time-like and entity-ID-like columns are not target-encoded (see the class
|
|
15
|
+
docstring).
|
|
16
|
+
|
|
17
|
+
Both encoders are vectorised re-implementations of sklearn's ``OrdinalEncoder`` and
|
|
18
|
+
``TargetEncoder`` (binary targets) that give identical outputs, several times faster on large
|
|
19
|
+
categorical columns.
|
|
20
|
+
|
|
21
|
+
``make_dataframe_classifier`` stacks both, as used in the evaluation::
|
|
22
|
+
|
|
23
|
+
from firepfn import FirePFNClassifier
|
|
24
|
+
from firepfn.encoding import make_dataframe_classifier
|
|
25
|
+
clf = make_dataframe_classifier(FirePFNClassifier())
|
|
26
|
+
clf.fit(X_train_df, y_train).predict_proba(X_test_df)
|
|
27
|
+
"""
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import warnings
|
|
31
|
+
|
|
32
|
+
import numpy as np
|
|
33
|
+
import pandas as pd
|
|
34
|
+
from sklearn.base import BaseEstimator, ClassifierMixin, clone
|
|
35
|
+
from sklearn.model_selection import StratifiedKFold
|
|
36
|
+
from sklearn.preprocessing import LabelEncoder, TargetEncoder
|
|
37
|
+
from sklearn.utils._encode import _unique
|
|
38
|
+
from sklearn.utils.validation import check_is_fitted
|
|
39
|
+
|
|
40
|
+
_NA = "__NA__"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _is_nan(v) -> bool:
|
|
44
|
+
return isinstance(v, float) and v != v
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _as_str(df: pd.DataFrame) -> pd.DataFrame:
|
|
48
|
+
"""String frame for TargetEncoder; missing is its own level."""
|
|
49
|
+
df = df.astype(object)
|
|
50
|
+
return df.where(df.notna(), _NA).astype(str)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _looks_datetime(s: pd.Series, n: int = 200) -> bool:
|
|
54
|
+
"""At least 95% of (up to n sampled) non-numeric-looking values parse as date/time."""
|
|
55
|
+
v = s.dropna().astype(str)
|
|
56
|
+
v = v.sample(min(n, len(v)), random_state=0) if len(v) else v
|
|
57
|
+
v = v[~v.str.fullmatch(r"[+-]?\d+(\.\d+)?")] # plain numbers are not dates
|
|
58
|
+
if len(v) < 10:
|
|
59
|
+
return False
|
|
60
|
+
with warnings.catch_warnings():
|
|
61
|
+
warnings.simplefilter("ignore")
|
|
62
|
+
ok = pd.to_datetime(v, errors="coerce", format="mixed").notna().mean()
|
|
63
|
+
return ok >= 0.95
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _id_lift(s: pd.Series, y, min_rows: float | None = None) -> tuple[float, float]:
|
|
67
|
+
"""(rows per level, lift of within-level label purity over the majority rate).
|
|
68
|
+
|
|
69
|
+
Purity is the share of rows (in levels seen at least twice) carrying their level's majority
|
|
70
|
+
label; lift = (purity - majority rate) / (1 - majority rate). Missing values form their own
|
|
71
|
+
level. With min_rows, the lift is not computed (returned as 0.0) when there are fewer rows per
|
|
72
|
+
level, since such a column cannot be flagged anyway.
|
|
73
|
+
"""
|
|
74
|
+
codes, uniq = pd.factorize(pd.Series(s, copy=False), use_na_sentinel=False)
|
|
75
|
+
n, n_lev = len(codes), max(len(uniq), 1)
|
|
76
|
+
rows_per_level = n / n_lev
|
|
77
|
+
if n == 0 or (min_rows is not None and rows_per_level < min_rows):
|
|
78
|
+
return rows_per_level, 0.0
|
|
79
|
+
yc, ylev = pd.factorize(pd.Series(np.asarray(y)).astype(str), use_na_sentinel=False)
|
|
80
|
+
k = max(len(ylev), 1)
|
|
81
|
+
rep = np.bincount(codes, minlength=n_lev)[codes] >= 2 # rows of levels seen >= 2 times
|
|
82
|
+
n_rep = int(rep.sum())
|
|
83
|
+
if not n_rep:
|
|
84
|
+
return rows_per_level, 0.0
|
|
85
|
+
joint = codes[rep].astype(np.int64) * k + yc[rep]
|
|
86
|
+
u, c = np.unique(joint, return_counts=True) # sorted by level, then label
|
|
87
|
+
lev = u // k
|
|
88
|
+
starts = np.flatnonzero(np.r_[True, lev[1:] != lev[:-1]])
|
|
89
|
+
purity = np.maximum.reduceat(c, starts).sum() / n_rep # majority label count per level
|
|
90
|
+
maj = np.bincount(yc).max() / n
|
|
91
|
+
return rows_per_level, (purity - maj) / max(1.0 - maj, 1e-12)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class _OrdinalEncoder:
|
|
95
|
+
"""Vectorised ``OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1,
|
|
96
|
+
encoded_missing_value=np.nan)`` on object columns (every NA treated as np.nan), with
|
|
97
|
+
identical output. sklearn maps object values with a per-value Python dict lookup; here:
|
|
98
|
+
|
|
99
|
+
* ``categories_[j]`` = sklearn's own ``_unique`` over the column's distinct values (sorted,
|
|
100
|
+
NaN last if missing values occur), the same as fitting on every row;
|
|
101
|
+
* transform: hash lookup in ``pd.Index(categories without NaN)`` (Python equality, like
|
|
102
|
+
sklearn's dict); category-dtype columns are mapped once per category level;
|
|
103
|
+
* missing -> NaN if NaN is a training category, else -1 (unknown), like sklearn.
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
@staticmethod
|
|
107
|
+
def _column(s: pd.Series):
|
|
108
|
+
"""(object values or None, categorical codes or None, levels, missing mask)."""
|
|
109
|
+
miss = s.isna().to_numpy()
|
|
110
|
+
if isinstance(s.dtype, pd.CategoricalDtype):
|
|
111
|
+
levels = np.asarray(s.cat.categories.astype(object), dtype=object)
|
|
112
|
+
return None, s.cat.codes.to_numpy(), levels, miss
|
|
113
|
+
vals = s.astype(object).to_numpy(dtype=object, copy=True)
|
|
114
|
+
vals[miss] = np.nan
|
|
115
|
+
return vals, None, None, miss
|
|
116
|
+
|
|
117
|
+
def fit(self, X: pd.DataFrame):
|
|
118
|
+
self.categories_ = []
|
|
119
|
+
for c in X.columns:
|
|
120
|
+
vals, codes, levels, miss = self._column(X[c])
|
|
121
|
+
if codes is not None:
|
|
122
|
+
present = levels[np.unique(codes[codes >= 0])]
|
|
123
|
+
distinct = np.concatenate([present, [np.nan]]) if miss.any() else present
|
|
124
|
+
else:
|
|
125
|
+
distinct = pd.unique(vals)
|
|
126
|
+
self.categories_.append(_unique(np.asarray(distinct, dtype=object)))
|
|
127
|
+
return self
|
|
128
|
+
|
|
129
|
+
def transform(self, X: pd.DataFrame) -> np.ndarray:
|
|
130
|
+
out = np.empty(X.shape, dtype=np.float64)
|
|
131
|
+
for j, c in enumerate(X.columns):
|
|
132
|
+
cats = self.categories_[j]
|
|
133
|
+
has_nan = len(cats) > 0 and _is_nan(cats[-1])
|
|
134
|
+
index = pd.Index(cats[:-1] if has_nan else cats, dtype=object)
|
|
135
|
+
vals, codes, levels, miss = self._column(X[c])
|
|
136
|
+
if codes is not None:
|
|
137
|
+
level_code = index.get_indexer(levels)
|
|
138
|
+
enc = np.where(codes >= 0, level_code[np.maximum(codes, 0)], -1)
|
|
139
|
+
else:
|
|
140
|
+
enc = index.get_indexer(vals)
|
|
141
|
+
enc = enc.astype(np.float64) # -1 = unknown level
|
|
142
|
+
enc[miss] = np.nan if has_nan else -1
|
|
143
|
+
out[:, j] = enc
|
|
144
|
+
return out
|
|
145
|
+
|
|
146
|
+
def fit_transform(self, X: pd.DataFrame) -> np.ndarray:
|
|
147
|
+
return self.fit(X).transform(X)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _level_keys(col: pd.Series):
|
|
151
|
+
"""(codes, keys): integer codes grouping the values exactly like ``_as_str`` (str() of the
|
|
152
|
+
value, missing = its own level), keys[code] that string. Only distinct values go through str()."""
|
|
153
|
+
codes, uniq = pd.factorize(pd.Series(col, copy=False), use_na_sentinel=False)
|
|
154
|
+
keys = _as_str(pd.DataFrame({0: pd.Series(uniq, dtype=object)}))[0].to_numpy()
|
|
155
|
+
merged, keys = pd.factorize(keys) # distinct raw values with equal str() -> one level
|
|
156
|
+
return merged[codes], np.asarray(keys)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _auto_smooth_encoding(codes: np.ndarray, y: np.ndarray, n_lev: int) -> np.ndarray:
|
|
160
|
+
"""sklearn's smooth="auto" encoding (Micci-Barreca 2001, eq. 5/6) of one feature's levels."""
|
|
161
|
+
y_mean, y_var = np.mean(y), np.var(y)
|
|
162
|
+
cnt = np.bincount(codes, minlength=n_lev).astype(np.float64)
|
|
163
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
164
|
+
mean = np.bincount(codes, weights=y, minlength=n_lev) / cnt
|
|
165
|
+
ssd = np.bincount(codes, weights=(y - mean[codes]) ** 2, minlength=n_lev)
|
|
166
|
+
lam = y_var * cnt / (y_var * cnt + ssd / cnt)
|
|
167
|
+
enc = lam * mean + (1 - lam) * y_mean
|
|
168
|
+
return np.where(np.isnan(lam), y_mean, enc) # level absent / zero variance -> prior
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class _BinaryTargetEncoder:
|
|
172
|
+
"""``TargetEncoder(target_type="auto", smooth="auto", cv, shuffle=True, random_state)`` for
|
|
173
|
+
binary targets with identical output: same StratifiedKFold cross-fitting, same per-level sums
|
|
174
|
+
(np.bincount accumulates in row order like sklearn), levels found with pd.factorize instead
|
|
175
|
+
of sklearn's str-based category search. Input: the raw columns (not ``_as_str``)."""
|
|
176
|
+
|
|
177
|
+
def __init__(self, cv: int = 5, random_state: int = 0):
|
|
178
|
+
self.cv = cv
|
|
179
|
+
self.random_state = random_state
|
|
180
|
+
|
|
181
|
+
def fit_transform(self, X: pd.DataFrame, y) -> np.ndarray:
|
|
182
|
+
y = np.asarray(y)
|
|
183
|
+
classes = np.unique(y)
|
|
184
|
+
assert len(classes) == 2, "binary targets only"
|
|
185
|
+
y01 = (y == classes[1]).astype(np.float64)
|
|
186
|
+
self.target_mean_ = np.mean(y01)
|
|
187
|
+
folds = list(StratifiedKFold(self.cv, shuffle=True, random_state=self.random_state)
|
|
188
|
+
.split(np.zeros((len(y), 1)), y))
|
|
189
|
+
self.keys_, self.encodings_ = [], []
|
|
190
|
+
out = np.empty((len(y), X.shape[1]), dtype=np.float64)
|
|
191
|
+
for j, c in enumerate(X.columns):
|
|
192
|
+
codes, keys = _level_keys(X[c])
|
|
193
|
+
self.keys_.append(pd.Index(keys))
|
|
194
|
+
self.encodings_.append(_auto_smooth_encoding(codes, y01, len(keys)))
|
|
195
|
+
for tr, te in folds:
|
|
196
|
+
out[te, j] = _auto_smooth_encoding(codes[tr], y01[tr], len(keys))[codes[te]]
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
def transform(self, X: pd.DataFrame) -> np.ndarray:
|
|
200
|
+
out = np.empty((len(X), X.shape[1]), dtype=np.float64)
|
|
201
|
+
for j, c in enumerate(X.columns):
|
|
202
|
+
codes, keys = _level_keys(X[c])
|
|
203
|
+
idx = self.keys_[j].get_indexer(keys) # -1: level unseen in training
|
|
204
|
+
enc = np.where(idx >= 0, self.encodings_[j][np.maximum(idx, 0)], self.target_mean_)
|
|
205
|
+
out[:, j] = enc[codes]
|
|
206
|
+
return out
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class OrdinalEncodedClassifier(ClassifierMixin, BaseEstimator):
|
|
210
|
+
"""Ordinal-encode the non-numeric columns of a DataFrame, then fit / predict `estimator`.
|
|
211
|
+
|
|
212
|
+
`classes_` holds the original labels in `predict_proba` column order.
|
|
213
|
+
"""
|
|
214
|
+
|
|
215
|
+
def __init__(self, estimator):
|
|
216
|
+
self.estimator = estimator
|
|
217
|
+
|
|
218
|
+
def fit(self, X, y):
|
|
219
|
+
X = pd.DataFrame(X) if not isinstance(X, pd.DataFrame) else X.copy()
|
|
220
|
+
self.cat_cols_ = X.select_dtypes(exclude="number").columns.tolist()
|
|
221
|
+
if self.cat_cols_:
|
|
222
|
+
self.encoder_ = _OrdinalEncoder()
|
|
223
|
+
X[self.cat_cols_] = self.encoder_.fit_transform(X[self.cat_cols_])
|
|
224
|
+
else:
|
|
225
|
+
self.encoder_ = None
|
|
226
|
+
self.label_encoder_ = LabelEncoder()
|
|
227
|
+
y_enc = self.label_encoder_.fit_transform(y)
|
|
228
|
+
self.estimator_ = clone(self.estimator).fit(X.values, y_enc)
|
|
229
|
+
self.classes_ = self.label_encoder_.classes_
|
|
230
|
+
return self
|
|
231
|
+
|
|
232
|
+
def _transform(self, X):
|
|
233
|
+
X = pd.DataFrame(X) if not isinstance(X, pd.DataFrame) else X.copy()
|
|
234
|
+
if self.encoder_ is not None:
|
|
235
|
+
X[self.cat_cols_] = self.encoder_.transform(X[self.cat_cols_])
|
|
236
|
+
return X.values
|
|
237
|
+
|
|
238
|
+
def predict(self, X):
|
|
239
|
+
check_is_fitted(self, "estimator_")
|
|
240
|
+
pred = np.asarray(self.estimator_.predict(self._transform(X))).astype(int)
|
|
241
|
+
return self.label_encoder_.inverse_transform(pred)
|
|
242
|
+
|
|
243
|
+
def predict_proba(self, X):
|
|
244
|
+
check_is_fitted(self, "estimator_")
|
|
245
|
+
return self.estimator_.predict_proba(self._transform(X))
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
class TargetEncodedClassifier(ClassifierMixin, BaseEstimator):
|
|
249
|
+
"""Target-encode high-cardinality categorical columns, then fit / predict `estimator`.
|
|
250
|
+
|
|
251
|
+
Non-numeric columns with more than `min_levels` distinct training values are dropped and
|
|
252
|
+
their target encodings are appended at the end (binary: one column, multiclass: one column
|
|
253
|
+
per class, sklearn ``TargetEncoder``). binary_only (default): multiclass tasks pass through
|
|
254
|
+
unchanged, since one column per class and level-wise class rates add many weak features. Training rows get cross-fitted (out-of-fold, `cv` folds) encodings,
|
|
255
|
+
so a context row's label does not leak into its own features; test rows use the encoder fit
|
|
256
|
+
on all training rows. Missing is its own level; unseen levels map to the smoothed prior.
|
|
257
|
+
Other columns pass through unchanged (wrap an ``OrdinalEncodedClassifier`` to encode them).
|
|
258
|
+
|
|
259
|
+
skip_datetime: never target-encode date/time-like string columns. Under temporal splits their
|
|
260
|
+
test values are all unseen, while their sorted ordinal codes keep the time order.
|
|
261
|
+
|
|
262
|
+
skip_id_like (ID guard): never target-encode entity-ID-like columns, judged on the training
|
|
263
|
+
data only: levels repeat (at least `id_min_rows` rows per level on average) and the label is
|
|
264
|
+
(nearly) constant within each repeated level (purity lift >= `id_lift`, see ``_id_lift``).
|
|
265
|
+
Under grouped splits such IDs are never seen at test time, but their out-of-fold encoding in
|
|
266
|
+
the context is almost the label. They stay ordinal-encoded.
|
|
267
|
+
"""
|
|
268
|
+
|
|
269
|
+
def __init__(self, estimator, min_levels: int = 500, skip_datetime: bool = True,
|
|
270
|
+
skip_id_like: bool = True, id_lift: float = 0.8, id_min_rows: float = 2.0,
|
|
271
|
+
cv: int = 5, random_state: int = 0, binary_only: bool = True):
|
|
272
|
+
self.estimator = estimator
|
|
273
|
+
self.binary_only = binary_only
|
|
274
|
+
self.min_levels = min_levels
|
|
275
|
+
self.skip_datetime = skip_datetime
|
|
276
|
+
self.skip_id_like = skip_id_like
|
|
277
|
+
self.id_lift = id_lift
|
|
278
|
+
self.id_min_rows = id_min_rows
|
|
279
|
+
self.cv = cv
|
|
280
|
+
self.random_state = random_state
|
|
281
|
+
|
|
282
|
+
def _is_id_like(self, s, y) -> bool:
|
|
283
|
+
rows_per_level, lift = _id_lift(s, y, min_rows=self.id_min_rows)
|
|
284
|
+
return rows_per_level >= self.id_min_rows and lift >= self.id_lift
|
|
285
|
+
|
|
286
|
+
def fit(self, X, y):
|
|
287
|
+
X = pd.DataFrame(X) if not isinstance(X, pd.DataFrame) else X
|
|
288
|
+
binary = pd.Series(np.asarray(y)).nunique() == 2
|
|
289
|
+
cat = [] if self.binary_only and not binary else X.select_dtypes(exclude="number").columns
|
|
290
|
+
cols = [c for c in cat if X[c].nunique(dropna=True) > self.min_levels]
|
|
291
|
+
if self.skip_datetime:
|
|
292
|
+
cols = [c for c in cols if not _looks_datetime(X[c])]
|
|
293
|
+
if self.skip_id_like:
|
|
294
|
+
cols = [c for c in cols if not self._is_id_like(X[c], y)]
|
|
295
|
+
self.te_cols_ = cols
|
|
296
|
+
if cols:
|
|
297
|
+
if binary:
|
|
298
|
+
self.encoder_ = _BinaryTargetEncoder(cv=self.cv, random_state=self.random_state)
|
|
299
|
+
Z = self.encoder_.fit_transform(X[cols], y)
|
|
300
|
+
else:
|
|
301
|
+
self.encoder_ = TargetEncoder(target_type="auto", smooth="auto", cv=self.cv,
|
|
302
|
+
shuffle=True, random_state=self.random_state)
|
|
303
|
+
Z = self.encoder_.fit_transform(_as_str(X[cols]), np.asarray(y))
|
|
304
|
+
Xt = self._replace(X, Z)
|
|
305
|
+
else:
|
|
306
|
+
self.encoder_ = None
|
|
307
|
+
Xt = X
|
|
308
|
+
self.estimator_ = clone(self.estimator).fit(Xt, y)
|
|
309
|
+
self.classes_ = self.estimator_.classes_
|
|
310
|
+
return self
|
|
311
|
+
|
|
312
|
+
def _replace(self, X, Z):
|
|
313
|
+
names = [f"__te{i}" for i in range(Z.shape[1])]
|
|
314
|
+
te = pd.DataFrame(np.asarray(Z, dtype=np.float64), columns=names, index=X.index)
|
|
315
|
+
return pd.concat([X.drop(columns=self.te_cols_), te], axis=1)
|
|
316
|
+
|
|
317
|
+
def _transform(self, X):
|
|
318
|
+
X = pd.DataFrame(X) if not isinstance(X, pd.DataFrame) else X
|
|
319
|
+
if self.encoder_ is None:
|
|
320
|
+
return X
|
|
321
|
+
cols = X[self.te_cols_]
|
|
322
|
+
if not isinstance(self.encoder_, _BinaryTargetEncoder):
|
|
323
|
+
cols = _as_str(cols)
|
|
324
|
+
return self._replace(X, self.encoder_.transform(cols))
|
|
325
|
+
|
|
326
|
+
def predict(self, X):
|
|
327
|
+
check_is_fitted(self, "estimator_")
|
|
328
|
+
return self.estimator_.predict(self._transform(X))
|
|
329
|
+
|
|
330
|
+
def predict_proba(self, X):
|
|
331
|
+
check_is_fitted(self, "estimator_")
|
|
332
|
+
return self.estimator_.predict_proba(self._transform(X))
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def make_dataframe_classifier(estimator, target_encode_min_levels: int | None = 500,
|
|
336
|
+
skip_datetime: bool = True, skip_id_like: bool = True,
|
|
337
|
+
target_encode_binary_only: bool = True):
|
|
338
|
+
"""DataFrame classifier around a numeric `estimator`: target encoding of categoricals with
|
|
339
|
+
more than `target_encode_min_levels` levels (None: off; date/time-like and, with
|
|
340
|
+
`skip_id_like`, entity-ID-like columns excepted; binary tasks only unless
|
|
341
|
+
`target_encode_binary_only=False`), ordinal encoding of the rest."""
|
|
342
|
+
m = OrdinalEncodedClassifier(estimator)
|
|
343
|
+
if target_encode_min_levels is not None:
|
|
344
|
+
m = TargetEncodedClassifier(m, min_levels=target_encode_min_levels,
|
|
345
|
+
skip_datetime=skip_datetime, skip_id_like=skip_id_like,
|
|
346
|
+
binary_only=target_encode_binary_only)
|
|
347
|
+
return m
|
firepfn/ensemble.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright 2022 Noah Hollmann, Samuel Müller, Katharina Eggensperger, Frank Hutter.
|
|
3
|
+
# Copyright (c) 2025-2026, the FirePFN authors (modifications).
|
|
4
|
+
#
|
|
5
|
+
# Ensemble members as in TabPFN v1 (https://github.com/PriorLabs/TabPFN, 2022 release,
|
|
6
|
+
# tabpfn/scripts/transformer_prediction_interface.py; Apache License 2.0): every member sees a
|
|
7
|
+
# circular class shift of the labels and a circular shift of the feature columns. Modified by the
|
|
8
|
+
# FirePFN authors: refactored into standalone functions, added circular shifts of the context rows,
|
|
9
|
+
# explicit RNG.
|
|
10
|
+
"""Ensemble members: (class shift, feature shift, context-row shift) per member."""
|
|
11
|
+
import itertools
|
|
12
|
+
import random
|
|
13
|
+
|
|
14
|
+
import torch
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def make_ensemble_configurations(n_features: int, n_classes: int, n_context: int, n_members: int,
|
|
18
|
+
feature_shift: bool, row_shift: bool, seed: int):
|
|
19
|
+
"""(class_shift, feature_shift, row_shift) for each of ``n_members`` members."""
|
|
20
|
+
gen = torch.Generator().manual_seed(seed)
|
|
21
|
+
# Each axis's candidates are capped at n_members: no more distinct values per axis can be used
|
|
22
|
+
# after the truncation below, and it keeps the product cheap for wide/long tables.
|
|
23
|
+
feature_shifts = torch.randperm(n_features, generator=gen)[:n_members] if feature_shift else [0]
|
|
24
|
+
class_shifts = torch.randperm(n_classes, generator=gen)[:n_members]
|
|
25
|
+
row_shifts = torch.randperm(n_context, generator=gen)[:n_members] if row_shift else [0]
|
|
26
|
+
# Same draw order as the original implementation: features, classes, rows.
|
|
27
|
+
configs = list(itertools.product(class_shifts, feature_shifts, row_shifts))
|
|
28
|
+
random.Random(seed).shuffle(configs)
|
|
29
|
+
return configs[:n_members]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def apply_ensemble_member(xs: torch.Tensor, ys: torch.Tensor, config, n_context: int, n_classes: int):
|
|
33
|
+
"""One member's input. xs: (T, B, H) with the first n_context rows the context, ys:
|
|
34
|
+
(n_context, B). Only context rows are reordered by the row shift."""
|
|
35
|
+
class_shift, feature_shift, row_shift = config
|
|
36
|
+
xs_ = xs.clone()
|
|
37
|
+
ys_ = ((ys.clone() + class_shift) % n_classes).float()
|
|
38
|
+
xs_ = torch.cat([xs_[..., feature_shift:], xs_[..., :feature_shift]], dim=-1)
|
|
39
|
+
if row_shift:
|
|
40
|
+
ctx = xs_[:n_context]
|
|
41
|
+
ctx = torch.cat([ctx[row_shift:], ctx[:row_shift]], dim=0)
|
|
42
|
+
xs_ = torch.cat([ctx, xs_[n_context:]], dim=0)
|
|
43
|
+
ys_ = torch.cat([ys_[row_shift:], ys_[:row_shift]], dim=0)
|
|
44
|
+
return xs_, ys_
|
firepfn/eval/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Copyright (c) 2025-2026, the FirePFN authors.
|
|
3
|
+
"""Evaluation of FirePFN as in the paper (install with ``pip install "FirePFN[eval]"``).
|
|
4
|
+
|
|
5
|
+
* :mod:`firepfn.eval.tabarena` -- TabArena classification tasks (official splits and metrics);
|
|
6
|
+
* :mod:`firepfn.eval.runtime` -- fit + predict time and peak GPU memory against the number of
|
|
7
|
+
context rows;
|
|
8
|
+
* :mod:`firepfn.eval.analysis` -- leaderboard, tables and plots from result CSVs, against the
|
|
9
|
+
baseline results shipped in ``results/``;
|
|
10
|
+
* :mod:`firepfn.eval.plots` -- the plotting functions used by the analysis.
|
|
11
|
+
|
|
12
|
+
Baselines are not run by this package: their results (produced with the same harness) are
|
|
13
|
+
shipped as CSV files.
|
|
14
|
+
"""
|