pretab 0.0.1__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.
- pretab/__init__.py +3 -0
- pretab/__version__.py +4 -0
- pretab/preprocessor.py +532 -0
- pretab/transformers/__init__.py +41 -0
- pretab/transformers/binning/__init__.py +3 -0
- pretab/transformers/binning/binning.py +98 -0
- pretab/transformers/embeddings/__init__.py +3 -0
- pretab/transformers/embeddings/language_transformer.py +58 -0
- pretab/transformers/feature_maps/__init__.py +11 -0
- pretab/transformers/feature_maps/rbf.py +123 -0
- pretab/transformers/feature_maps/relu.py +113 -0
- pretab/transformers/feature_maps/sigmoid.py +122 -0
- pretab/transformers/feature_maps/tanh.py +116 -0
- pretab/transformers/onehot/__init__.py +3 -0
- pretab/transformers/onehot/onehot.py +67 -0
- pretab/transformers/ple/__init__.py +3 -0
- pretab/transformers/ple/ple.py +145 -0
- pretab/transformers/ple/tree_to_code.py +59 -0
- pretab/transformers/splines/__init__.py +13 -0
- pretab/transformers/splines/cubic.py +136 -0
- pretab/transformers/splines/integrated_spline.py +98 -0
- pretab/transformers/splines/natural_cubic.py +141 -0
- pretab/transformers/splines/p_spline.py +141 -0
- pretab/transformers/splines/tensor_product.py +170 -0
- pretab/transformers/splines/thinplate_spline.py +130 -0
- pretab/transformers/temporal/__init__.py +9 -0
- pretab/transformers/temporal/cyclic.py +29 -0
- pretab/transformers/temporal/lag.py +31 -0
- pretab/transformers/temporal/rolling_stats.py +47 -0
- pretab/transformers/utils/__init__.py +0 -0
- pretab/transformers/utils/continuous_ordinal.py +67 -0
- pretab/transformers/utils/floats.py +63 -0
- pretab/transformers/utils/utils.py +24 -0
- pretab/utils/__init__.py +7 -0
- pretab/utils/get_categorical.py +46 -0
- pretab/utils/get_numerical.py +111 -0
- pretab-0.0.1.dist-info/LICENSE +21 -0
- pretab-0.0.1.dist-info/METADATA +208 -0
- pretab-0.0.1.dist-info/RECORD +41 -0
- pretab-0.0.1.dist-info/WHEEL +5 -0
- pretab-0.0.1.dist-info/top_level.txt +1 -0
pretab/__init__.py
ADDED
pretab/__version__.py
ADDED
pretab/preprocessor.py
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from sklearn.compose import ColumnTransformer
|
|
4
|
+
from sklearn.exceptions import NotFittedError
|
|
5
|
+
from sklearn.pipeline import Pipeline
|
|
6
|
+
from sklearn.base import TransformerMixin
|
|
7
|
+
|
|
8
|
+
from .utils import (
|
|
9
|
+
get_numerical_transformer_steps,
|
|
10
|
+
get_categorical_transformer_steps,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Preprocessor(TransformerMixin):
|
|
15
|
+
"""
|
|
16
|
+
Preprocessor class for automated tabular feature preprocessing using scikit-learn-compatible pipelines.
|
|
17
|
+
|
|
18
|
+
This class provides a flexible interface for preprocessing tabular datasets containing numerical and
|
|
19
|
+
categorical features. It automatically detects feature types, applies user-defined or default preprocessing
|
|
20
|
+
strategies, and supports both dictionary and array-style outputs. It also supports integration with external
|
|
21
|
+
embedding vectors.
|
|
22
|
+
|
|
23
|
+
Features
|
|
24
|
+
--------
|
|
25
|
+
- Supports a wide range of preprocessing methods for numerical and categorical features.
|
|
26
|
+
- Automatically detects feature types (numerical vs. categorical).
|
|
27
|
+
- Compatible with both pandas DataFrames and NumPy arrays.
|
|
28
|
+
- Handles external embedding arrays for models that require learned representations.
|
|
29
|
+
- Returns either a dictionary of transformed feature blocks or a single NumPy array.
|
|
30
|
+
- Fully compatible with scikit-learn transformers and pipelines.
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
feature_preprocessing : dict, optional
|
|
35
|
+
Dictionary mapping feature names to specific preprocessing methods. Overrides global defaults.
|
|
36
|
+
n_bins : int, default=64
|
|
37
|
+
Number of bins used for binning-based preprocessing (e.g., for discretizers or PLE).
|
|
38
|
+
numerical_preprocessing : str, default="ple"
|
|
39
|
+
Preprocessing method for numerical features (e.g., "standardization", "minmax", "ple", "rbf", etc.).
|
|
40
|
+
categorical_preprocessing : str, default="int"
|
|
41
|
+
Preprocessing method for categorical features (e.g., "int", "ordinal", "onehot").
|
|
42
|
+
use_decision_tree_bins : bool, default=False
|
|
43
|
+
Whether to use decision tree binning for numerical discretization.
|
|
44
|
+
binning_strategy : str, default="uniform"
|
|
45
|
+
Strategy for bin placement when not using tree-based methods. Options: "uniform", "quantile".
|
|
46
|
+
task : str, default="regression"
|
|
47
|
+
Problem type used to guide preprocessing (e.g., "regression" or "classification").
|
|
48
|
+
cat_cutoff : float or int, default=0.03
|
|
49
|
+
Threshold to determine whether integer-valued features are treated as categorical.
|
|
50
|
+
treat_all_integers_as_numerical : bool, default=False
|
|
51
|
+
If True, treat all integer-typed columns as numerical regardless of cardinality.
|
|
52
|
+
degree : int, default=3
|
|
53
|
+
Degree of polynomial or spline basis functions where applicable.
|
|
54
|
+
scaling_strategy : str, default="minmax"
|
|
55
|
+
Strategy for feature scaling (e.g., "standardization", "minmax", etc.).
|
|
56
|
+
n_knots : int, default=64
|
|
57
|
+
Number of knots used in spline-based feature expansions.
|
|
58
|
+
use_decision_tree_knots : bool, default=True
|
|
59
|
+
Whether to use decision tree-based knot placement for spline transformations.
|
|
60
|
+
knots_strategy : str, default="uniform"
|
|
61
|
+
Strategy for placing knots for splines ("uniform" or "quantile").
|
|
62
|
+
spline_implementation : str, default="sklearn"
|
|
63
|
+
Which spline backend implementation to use (e.g., "sklearn", "custom").
|
|
64
|
+
min_unique_vals : int, default=5
|
|
65
|
+
Minimum number of unique values required for a feature to be treated as numerical.
|
|
66
|
+
|
|
67
|
+
Attributes
|
|
68
|
+
----------
|
|
69
|
+
column_transformer : ColumnTransformer
|
|
70
|
+
The internal scikit-learn column transformer that handles feature-wise preprocessing.
|
|
71
|
+
fitted : bool
|
|
72
|
+
Whether the preprocessor has been fitted.
|
|
73
|
+
embeddings : bool
|
|
74
|
+
Whether embedding vectors are expected and used in transformation.
|
|
75
|
+
embedding_dimensions : dict
|
|
76
|
+
Dictionary of embedding feature names to their expected dimensionality.
|
|
77
|
+
|
|
78
|
+
Examples
|
|
79
|
+
--------
|
|
80
|
+
>>> from prefab import Preprocessor
|
|
81
|
+
>>> import pandas as pd
|
|
82
|
+
>>> df = pd.DataFrame({
|
|
83
|
+
... "age": [25, 32, 47],
|
|
84
|
+
... "gender": ["M", "F", "F"]
|
|
85
|
+
... })
|
|
86
|
+
>>> pre = Preprocessor()
|
|
87
|
+
>>> pre.fit(df)
|
|
88
|
+
>>> out = pre.transform(df)
|
|
89
|
+
>>> out.keys()
|
|
90
|
+
dict_keys(['num_age', 'cat_gender'])
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
def __init__(
|
|
94
|
+
self,
|
|
95
|
+
feature_preprocessing=None,
|
|
96
|
+
n_bins=64,
|
|
97
|
+
numerical_preprocessing="ple",
|
|
98
|
+
categorical_preprocessing="int",
|
|
99
|
+
use_decision_tree_bins=False,
|
|
100
|
+
binning_strategy="uniform",
|
|
101
|
+
task="regression",
|
|
102
|
+
cat_cutoff=0.03,
|
|
103
|
+
treat_all_integers_as_numerical=False,
|
|
104
|
+
degree=3,
|
|
105
|
+
scaling_strategy="minmax",
|
|
106
|
+
n_knots=64,
|
|
107
|
+
use_decision_tree_knots=True,
|
|
108
|
+
knots_strategy="uniform",
|
|
109
|
+
spline_implementation="sklearn",
|
|
110
|
+
min_unique_vals=5,
|
|
111
|
+
):
|
|
112
|
+
"""
|
|
113
|
+
Initialize the Preprocessor with various transformation options for tabular data.
|
|
114
|
+
|
|
115
|
+
Parameters
|
|
116
|
+
----------
|
|
117
|
+
feature_preprocessing : dict, optional
|
|
118
|
+
Dictionary specifying preprocessing methods per feature. If None, global settings are used.
|
|
119
|
+
n_bins : int, default=64
|
|
120
|
+
Number of bins to use for binning-based transformations.
|
|
121
|
+
numerical_preprocessing : str, default="ple"
|
|
122
|
+
Preprocessing strategy for numerical features.
|
|
123
|
+
categorical_preprocessing : str, default="int"
|
|
124
|
+
Preprocessing strategy for categorical features.
|
|
125
|
+
use_decision_tree_bins : bool, default=False
|
|
126
|
+
Whether to use decision tree-based binning for numerical features.
|
|
127
|
+
binning_strategy : str, default="uniform"
|
|
128
|
+
Strategy for determining bin edges ("uniform", "quantile").
|
|
129
|
+
task : str, default="regression"
|
|
130
|
+
Task type for decision tree splitting ("regression", "classification").
|
|
131
|
+
cat_cutoff : float or int, default=0.03
|
|
132
|
+
Threshold to determine whether integer-valued columns are treated as categorical.
|
|
133
|
+
treat_all_integers_as_numerical : bool, default=False
|
|
134
|
+
If True, treat all integer columns as numerical.
|
|
135
|
+
degree : int, default=3
|
|
136
|
+
Degree of polynomial or spline basis expansion.
|
|
137
|
+
scaling_strategy : str, default="minmax"
|
|
138
|
+
Scaling method for numerical data ("standardization", "minmax", etc.).
|
|
139
|
+
n_knots : int, default=64
|
|
140
|
+
Number of knots for spline transformations.
|
|
141
|
+
use_decision_tree_knots : bool, default=True
|
|
142
|
+
Use decision tree-based knot placement for splines.
|
|
143
|
+
knots_strategy : str, default="uniform"
|
|
144
|
+
Strategy for placing spline knots.
|
|
145
|
+
spline_implementation : str, default="sklearn"
|
|
146
|
+
Backend implementation to use for splines.
|
|
147
|
+
min_unique_vals : int, default=5
|
|
148
|
+
Minimum number of unique values required for numerical processing.
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
self.n_bins = n_bins
|
|
152
|
+
self.numerical_preprocessing = (
|
|
153
|
+
numerical_preprocessing.lower()
|
|
154
|
+
if numerical_preprocessing is not None
|
|
155
|
+
else "none"
|
|
156
|
+
)
|
|
157
|
+
self.categorical_preprocessing = (
|
|
158
|
+
categorical_preprocessing.lower()
|
|
159
|
+
if categorical_preprocessing is not None
|
|
160
|
+
else "none"
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
self.use_decision_tree_bins = use_decision_tree_bins
|
|
164
|
+
self.feature_preprocessing = feature_preprocessing or {}
|
|
165
|
+
self.column_transformer = None
|
|
166
|
+
self.fitted = False
|
|
167
|
+
self.binning_strategy = binning_strategy
|
|
168
|
+
self.task = task
|
|
169
|
+
self.cat_cutoff = cat_cutoff
|
|
170
|
+
self.treat_all_integers_as_numerical = treat_all_integers_as_numerical
|
|
171
|
+
self.degree = degree
|
|
172
|
+
self.scaling_strategy = scaling_strategy
|
|
173
|
+
self.n_knots = n_knots
|
|
174
|
+
self.use_decision_tree_knots = use_decision_tree_knots
|
|
175
|
+
self.knots_strategy = knots_strategy
|
|
176
|
+
self.spline_implementation = spline_implementation
|
|
177
|
+
self.min_unique_vals = min_unique_vals
|
|
178
|
+
self.embeddings = False
|
|
179
|
+
self.embedding_dimensions = {}
|
|
180
|
+
|
|
181
|
+
def _detect_column_types(self, X):
|
|
182
|
+
"""
|
|
183
|
+
Detects categorical and numerical features in the input data.
|
|
184
|
+
|
|
185
|
+
Parameters
|
|
186
|
+
----------
|
|
187
|
+
X : pandas.DataFrame, numpy.ndarray, or dict
|
|
188
|
+
The input data to analyze.
|
|
189
|
+
|
|
190
|
+
Returns
|
|
191
|
+
-------
|
|
192
|
+
numerical_features : list of str
|
|
193
|
+
Column names detected as numerical features.
|
|
194
|
+
categorical_features : list of str
|
|
195
|
+
Column names detected as categorical features.
|
|
196
|
+
"""
|
|
197
|
+
|
|
198
|
+
categorical_features = []
|
|
199
|
+
numerical_features = []
|
|
200
|
+
|
|
201
|
+
if isinstance(X, dict):
|
|
202
|
+
X = pd.DataFrame(X)
|
|
203
|
+
elif isinstance(X, np.ndarray):
|
|
204
|
+
X = pd.DataFrame(X, columns=[f"feature_{i}" for i in range(X.shape[1])])
|
|
205
|
+
|
|
206
|
+
for col in X.columns:
|
|
207
|
+
num_unique_values = X[col].nunique()
|
|
208
|
+
total_samples = len(X[col])
|
|
209
|
+
|
|
210
|
+
if self.treat_all_integers_as_numerical and X[col].dtype.kind == "i":
|
|
211
|
+
numerical_features.append(col)
|
|
212
|
+
else:
|
|
213
|
+
if isinstance(self.cat_cutoff, float):
|
|
214
|
+
cutoff_condition = (
|
|
215
|
+
num_unique_values / total_samples
|
|
216
|
+
) < self.cat_cutoff
|
|
217
|
+
elif isinstance(self.cat_cutoff, int):
|
|
218
|
+
cutoff_condition = num_unique_values < self.cat_cutoff
|
|
219
|
+
else:
|
|
220
|
+
raise ValueError(
|
|
221
|
+
"cat_cutoff should be either a float or an integer."
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
if X[col].dtype.kind not in "iufc" or (
|
|
225
|
+
X[col].dtype.kind == "i" and cutoff_condition
|
|
226
|
+
):
|
|
227
|
+
categorical_features.append(col)
|
|
228
|
+
else:
|
|
229
|
+
numerical_features.append(col)
|
|
230
|
+
|
|
231
|
+
return numerical_features, categorical_features
|
|
232
|
+
|
|
233
|
+
def fit(self, X, y=None, embeddings=None):
|
|
234
|
+
"""
|
|
235
|
+
Fit the preprocessor to the input data and target labels.
|
|
236
|
+
|
|
237
|
+
Parameters
|
|
238
|
+
----------
|
|
239
|
+
X : pandas.DataFrame, numpy.ndarray, or dict
|
|
240
|
+
The input features.
|
|
241
|
+
y : array-like, default=None
|
|
242
|
+
Target values (used for decision tree-based methods).
|
|
243
|
+
embeddings : np.ndarray or list of np.ndarray, optional
|
|
244
|
+
External embedding arrays to be passed and validated.
|
|
245
|
+
|
|
246
|
+
Returns
|
|
247
|
+
-------
|
|
248
|
+
self : Preprocessor
|
|
249
|
+
Fitted instance of the preprocessor.
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
if isinstance(X, dict):
|
|
253
|
+
X = pd.DataFrame(X)
|
|
254
|
+
elif isinstance(X, np.ndarray):
|
|
255
|
+
X = pd.DataFrame(X, columns=[f"feature_{i}" for i in range(X.shape[1])])
|
|
256
|
+
|
|
257
|
+
if embeddings is not None:
|
|
258
|
+
self.embeddings = True
|
|
259
|
+
if isinstance(embeddings, np.ndarray):
|
|
260
|
+
self.embedding_dimensions["embedding_1"] = embeddings.shape[1]
|
|
261
|
+
elif isinstance(embeddings, list):
|
|
262
|
+
for i, e in enumerate(embeddings):
|
|
263
|
+
self.embedding_dimensions[f"embedding_{i + 1}"] = e.shape[1]
|
|
264
|
+
|
|
265
|
+
numerical_features, categorical_features = self._detect_column_types(X)
|
|
266
|
+
transformers = []
|
|
267
|
+
|
|
268
|
+
for feature in numerical_features:
|
|
269
|
+
method = self.feature_preprocessing.get(
|
|
270
|
+
feature, self.numerical_preprocessing
|
|
271
|
+
)
|
|
272
|
+
steps = get_numerical_transformer_steps(
|
|
273
|
+
method=method,
|
|
274
|
+
task=self.task,
|
|
275
|
+
use_decision_tree=self.use_decision_tree_knots,
|
|
276
|
+
add_imputer=True,
|
|
277
|
+
imputer_strategy="mean",
|
|
278
|
+
bins=self.n_bins,
|
|
279
|
+
degree=self.degree,
|
|
280
|
+
n_knots=self.n_knots,
|
|
281
|
+
scaling=self.scaling_strategy,
|
|
282
|
+
strategy=self.knots_strategy,
|
|
283
|
+
implementation=self.spline_implementation,
|
|
284
|
+
)
|
|
285
|
+
transformers.append((f"num_{feature}", Pipeline(steps), [feature]))
|
|
286
|
+
|
|
287
|
+
for feature in categorical_features:
|
|
288
|
+
method = self.feature_preprocessing.get(
|
|
289
|
+
feature, self.categorical_preprocessing
|
|
290
|
+
)
|
|
291
|
+
steps = get_categorical_transformer_steps(method)
|
|
292
|
+
transformers.append((f"cat_{feature}", Pipeline(steps), [feature]))
|
|
293
|
+
|
|
294
|
+
self.column_transformer = ColumnTransformer(
|
|
295
|
+
transformers=transformers, remainder="passthrough"
|
|
296
|
+
)
|
|
297
|
+
self.column_transformer.fit(X, y)
|
|
298
|
+
self.fitted = True
|
|
299
|
+
return self
|
|
300
|
+
|
|
301
|
+
def transform(self, X, embeddings=None, return_array=False):
|
|
302
|
+
"""
|
|
303
|
+
Transform the input data using the fitted column transformer.
|
|
304
|
+
|
|
305
|
+
Parameters
|
|
306
|
+
----------
|
|
307
|
+
X : pandas.DataFrame, numpy.ndarray, or dict
|
|
308
|
+
Input features to transform.
|
|
309
|
+
embeddings : np.ndarray or list of np.ndarray, optional
|
|
310
|
+
Optional external embeddings to attach to the transformation.
|
|
311
|
+
return_array : bool, default=False
|
|
312
|
+
If True, return a single stacked NumPy array. If False, return a dict of transformed arrays.
|
|
313
|
+
|
|
314
|
+
Returns
|
|
315
|
+
-------
|
|
316
|
+
dict or np.ndarray
|
|
317
|
+
Transformed data. A dictionary if return_array=False, else a NumPy array.
|
|
318
|
+
"""
|
|
319
|
+
|
|
320
|
+
if not self.fitted:
|
|
321
|
+
raise NotFittedError(
|
|
322
|
+
"Preprocessor must be fitted before calling transform."
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
if isinstance(X, dict):
|
|
326
|
+
X = pd.DataFrame(X)
|
|
327
|
+
elif isinstance(X, np.ndarray):
|
|
328
|
+
X = pd.DataFrame(X, columns=[f"feature_{i}" for i in range(X.shape[1])])
|
|
329
|
+
else:
|
|
330
|
+
X = X.copy()
|
|
331
|
+
|
|
332
|
+
transformed_X = self.column_transformer.transform(X)
|
|
333
|
+
|
|
334
|
+
if return_array:
|
|
335
|
+
return transformed_X
|
|
336
|
+
|
|
337
|
+
transformed_dict = {}
|
|
338
|
+
start = 0
|
|
339
|
+
for name, transformer, columns in self.column_transformer.transformers_:
|
|
340
|
+
if transformer == "drop":
|
|
341
|
+
continue
|
|
342
|
+
if hasattr(transformer, "transform"):
|
|
343
|
+
width = transformer.transform(X[columns]).shape[1]
|
|
344
|
+
else:
|
|
345
|
+
width = 1
|
|
346
|
+
transformed_dict[name] = transformed_X[:, start : start + width]
|
|
347
|
+
start += width
|
|
348
|
+
|
|
349
|
+
if embeddings is not None:
|
|
350
|
+
if not self.embeddings:
|
|
351
|
+
raise ValueError("Embeddings were not expected, but were provided.")
|
|
352
|
+
if isinstance(embeddings, np.ndarray):
|
|
353
|
+
transformed_dict["embedding_1"] = embeddings.astype(np.float32)
|
|
354
|
+
elif isinstance(embeddings, list):
|
|
355
|
+
for idx, e in enumerate(embeddings):
|
|
356
|
+
transformed_dict[f"embedding_{idx + 1}"] = e.astype(np.float32)
|
|
357
|
+
|
|
358
|
+
return transformed_dict
|
|
359
|
+
|
|
360
|
+
def fit_transform(self, X, y=None, embeddings=None, return_array=False):
|
|
361
|
+
"""
|
|
362
|
+
Convenience method that fits the preprocessor and transforms the data.
|
|
363
|
+
|
|
364
|
+
Parameters
|
|
365
|
+
----------
|
|
366
|
+
X : pandas.DataFrame, numpy.ndarray, or dict
|
|
367
|
+
Input features.
|
|
368
|
+
y : array-like, optional
|
|
369
|
+
Target values.
|
|
370
|
+
embeddings : np.ndarray or list of np.ndarray, optional
|
|
371
|
+
Optional embedding arrays.
|
|
372
|
+
return_array : bool, default=False
|
|
373
|
+
Whether to return a stacked NumPy array or a dictionary of arrays.
|
|
374
|
+
|
|
375
|
+
Returns
|
|
376
|
+
-------
|
|
377
|
+
dict or np.ndarray
|
|
378
|
+
Transformed dataset in the specified output format.
|
|
379
|
+
"""
|
|
380
|
+
|
|
381
|
+
return self.fit(X, y, embeddings=embeddings).transform(
|
|
382
|
+
X, embeddings, return_array
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
def get_feature_info(self, verbose=True):
|
|
386
|
+
"""
|
|
387
|
+
Retrieves metadata about the transformed features.
|
|
388
|
+
|
|
389
|
+
Provides detailed information for each input feature, including:
|
|
390
|
+
- preprocessing applied
|
|
391
|
+
- output dimensionality
|
|
392
|
+
- number of categories (for categorical features)
|
|
393
|
+
- embedding dimensions (if any)
|
|
394
|
+
|
|
395
|
+
Parameters
|
|
396
|
+
----------
|
|
397
|
+
verbose : bool, default=True
|
|
398
|
+
If True, prints detailed information for each feature.
|
|
399
|
+
|
|
400
|
+
Returns
|
|
401
|
+
-------
|
|
402
|
+
tuple of dicts
|
|
403
|
+
numerical_feature_info : dict
|
|
404
|
+
Metadata for numerical features.
|
|
405
|
+
categorical_feature_info : dict
|
|
406
|
+
Metadata for categorical features.
|
|
407
|
+
embedding_feature_info : dict
|
|
408
|
+
Metadata for embedding features, if used.
|
|
409
|
+
"""
|
|
410
|
+
|
|
411
|
+
if not self.fitted:
|
|
412
|
+
raise NotFittedError(
|
|
413
|
+
"Preprocessor must be fitted before calling get_feature_info."
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
numerical_feature_info = {}
|
|
417
|
+
categorical_feature_info = {}
|
|
418
|
+
|
|
419
|
+
embedding_feature_info = (
|
|
420
|
+
{
|
|
421
|
+
key: {"preprocessing": None, "dimension": dim, "categories": None}
|
|
422
|
+
for key, dim in self.embedding_dimensions.items()
|
|
423
|
+
}
|
|
424
|
+
if self.embeddings
|
|
425
|
+
else {}
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
for (
|
|
429
|
+
name,
|
|
430
|
+
transformer_pipeline,
|
|
431
|
+
columns,
|
|
432
|
+
) in self.column_transformer.transformers_:
|
|
433
|
+
steps = [step[0] for step in transformer_pipeline.steps]
|
|
434
|
+
|
|
435
|
+
for feature_name in columns:
|
|
436
|
+
preprocessing_type = " -> ".join(steps)
|
|
437
|
+
dimension = None
|
|
438
|
+
categories = None
|
|
439
|
+
|
|
440
|
+
if "discretizer" in steps or any(
|
|
441
|
+
step in steps
|
|
442
|
+
for step in [
|
|
443
|
+
"standardization",
|
|
444
|
+
"minmax",
|
|
445
|
+
"quantile",
|
|
446
|
+
"polynomial",
|
|
447
|
+
"splines",
|
|
448
|
+
"box-cox",
|
|
449
|
+
]
|
|
450
|
+
):
|
|
451
|
+
last_step = transformer_pipeline.steps[-1][1]
|
|
452
|
+
if hasattr(last_step, "transform"):
|
|
453
|
+
dummy_input = np.zeros((1, 1)) + 1e-05
|
|
454
|
+
try:
|
|
455
|
+
transformed_feature = last_step.transform(dummy_input)
|
|
456
|
+
dimension = transformed_feature.shape[1]
|
|
457
|
+
except Exception:
|
|
458
|
+
dimension = None
|
|
459
|
+
numerical_feature_info[feature_name] = {
|
|
460
|
+
"preprocessing": preprocessing_type,
|
|
461
|
+
"dimension": dimension,
|
|
462
|
+
"categories": None,
|
|
463
|
+
}
|
|
464
|
+
if verbose:
|
|
465
|
+
print(
|
|
466
|
+
f"Numerical Feature: {feature_name}, Info: {numerical_feature_info[feature_name]}"
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
elif "continuous_ordinal" in steps:
|
|
470
|
+
step = transformer_pipeline.named_steps["continuous_ordinal"]
|
|
471
|
+
categories = len(step.mapping_[columns.index(feature_name)])
|
|
472
|
+
dimension = 1
|
|
473
|
+
categorical_feature_info[feature_name] = {
|
|
474
|
+
"preprocessing": preprocessing_type,
|
|
475
|
+
"dimension": dimension,
|
|
476
|
+
"categories": categories,
|
|
477
|
+
}
|
|
478
|
+
if verbose:
|
|
479
|
+
print(
|
|
480
|
+
f"Categorical Feature (Ordinal): {feature_name}, Info: {categorical_feature_info[feature_name]}"
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
elif "onehot" in steps:
|
|
484
|
+
step = transformer_pipeline.named_steps["onehot"]
|
|
485
|
+
if hasattr(step, "categories_"):
|
|
486
|
+
categories = sum(len(cat) for cat in step.categories_)
|
|
487
|
+
dimension = categories
|
|
488
|
+
categorical_feature_info[feature_name] = {
|
|
489
|
+
"preprocessing": preprocessing_type,
|
|
490
|
+
"dimension": dimension,
|
|
491
|
+
"categories": categories,
|
|
492
|
+
}
|
|
493
|
+
if verbose:
|
|
494
|
+
print(
|
|
495
|
+
f"Categorical Feature (One-Hot): {feature_name}, Info: {categorical_feature_info[feature_name]}"
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
else:
|
|
499
|
+
last_step = transformer_pipeline.steps[-1][1]
|
|
500
|
+
if hasattr(last_step, "transform"):
|
|
501
|
+
dummy_input = np.zeros((1, 1))
|
|
502
|
+
try:
|
|
503
|
+
transformed_feature = last_step.transform(dummy_input)
|
|
504
|
+
dimension = transformed_feature.shape[1]
|
|
505
|
+
except Exception:
|
|
506
|
+
dimension = None
|
|
507
|
+
if "cat" in name:
|
|
508
|
+
categorical_feature_info[feature_name] = {
|
|
509
|
+
"preprocessing": preprocessing_type,
|
|
510
|
+
"dimension": dimension,
|
|
511
|
+
"categories": None,
|
|
512
|
+
}
|
|
513
|
+
else:
|
|
514
|
+
numerical_feature_info[feature_name] = {
|
|
515
|
+
"preprocessing": preprocessing_type,
|
|
516
|
+
"dimension": dimension,
|
|
517
|
+
"categories": None,
|
|
518
|
+
}
|
|
519
|
+
if verbose:
|
|
520
|
+
print(
|
|
521
|
+
f"Feature: {feature_name}, Info: {preprocessing_type}, Dimension: {dimension}"
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
if verbose:
|
|
525
|
+
print("-" * 50)
|
|
526
|
+
|
|
527
|
+
if verbose and self.embeddings:
|
|
528
|
+
print("Embeddings:")
|
|
529
|
+
for key, value in embedding_feature_info.items():
|
|
530
|
+
print(f" Feature: {key}, Dimension: {value['dimension']}")
|
|
531
|
+
|
|
532
|
+
return numerical_feature_info, categorical_feature_info, embedding_feature_info
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from .binning import CustomBinTransformer
|
|
2
|
+
from .embeddings import LanguageEmbeddingTransformer
|
|
3
|
+
from .feature_maps import (
|
|
4
|
+
RBFExpansionTransformer,
|
|
5
|
+
ReLUExpansionTransformer,
|
|
6
|
+
SigmoidExpansionTransformer,
|
|
7
|
+
TanhExpansionTransformer,
|
|
8
|
+
)
|
|
9
|
+
from .onehot import OneHotFromOrdinalTransformer
|
|
10
|
+
from .ple import PLETransformer
|
|
11
|
+
from .splines import (
|
|
12
|
+
CubicSplineTransformer,
|
|
13
|
+
ThinPlateSplineTransformer,
|
|
14
|
+
TensorProductSplineTransformer,
|
|
15
|
+
NaturalCubicSplineTransformer,
|
|
16
|
+
PSplineTransformer,
|
|
17
|
+
)
|
|
18
|
+
from .temporal import (
|
|
19
|
+
CyclicalTimeTransformer,
|
|
20
|
+
LagFeatureTransformer,
|
|
21
|
+
RollingStatsTransformer,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"CustomBinTransformer",
|
|
26
|
+
"LanguageEmbeddingTransformer",
|
|
27
|
+
"RBFExpansionTransformer",
|
|
28
|
+
"ReLUExpansionTransformer",
|
|
29
|
+
"SigmoidExpansionTransformer",
|
|
30
|
+
"TanhExpansionTransformer",
|
|
31
|
+
"OneHotFromOrdinalTransformer",
|
|
32
|
+
"PLETransformer",
|
|
33
|
+
"CubicSplineTransformer",
|
|
34
|
+
"ThinPlateSplineTransformer",
|
|
35
|
+
"TensorProductSplineTransformer",
|
|
36
|
+
"NaturalCubicSplineTransformer",
|
|
37
|
+
"PSplineTransformer",
|
|
38
|
+
"CyclicalTimeTransformer",
|
|
39
|
+
"LagFeatureTransformer",
|
|
40
|
+
"RollingStatsTransformer",
|
|
41
|
+
]
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from sklearn.base import BaseEstimator, TransformerMixin
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CustomBinTransformer(TransformerMixin, BaseEstimator):
|
|
7
|
+
"""
|
|
8
|
+
Custom binning transformer for one-dimensional numerical features.
|
|
9
|
+
|
|
10
|
+
This transformer bins continuous values into discrete intervals, using either a fixed number of equal-width bins
|
|
11
|
+
or a user-provided array of bin edges. It is compatible with scikit-learn pipelines.
|
|
12
|
+
|
|
13
|
+
Parameters
|
|
14
|
+
----------
|
|
15
|
+
bins : int or array-like
|
|
16
|
+
If int, defines the number of equal-width bins. If array-like, defines the bin edges to use directly.
|
|
17
|
+
|
|
18
|
+
Attributes
|
|
19
|
+
----------
|
|
20
|
+
n_features_in_ : int
|
|
21
|
+
The number of input features. Always set to 1 for this transformer.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, bins):
|
|
25
|
+
# bins can be a scalar (number of bins) or array-like (bin edges)
|
|
26
|
+
self.bins = bins
|
|
27
|
+
|
|
28
|
+
def fit(self, X, y=None):
|
|
29
|
+
"""
|
|
30
|
+
Fit the transformer on the data.
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
X : array-like of shape (n_samples, 1)
|
|
35
|
+
Input data.
|
|
36
|
+
|
|
37
|
+
y : Ignored
|
|
38
|
+
Not used, present here for API consistency by convention.
|
|
39
|
+
|
|
40
|
+
Returns
|
|
41
|
+
-------
|
|
42
|
+
self : object
|
|
43
|
+
Fitted transformer.
|
|
44
|
+
"""
|
|
45
|
+
# Fit doesn't need to do anything as we are directly using provided bins
|
|
46
|
+
self.n_features_in_ = 1
|
|
47
|
+
return self
|
|
48
|
+
|
|
49
|
+
def transform(self, X):
|
|
50
|
+
"""
|
|
51
|
+
Transform the data using the specified binning strategy.
|
|
52
|
+
|
|
53
|
+
Parameters
|
|
54
|
+
----------
|
|
55
|
+
X : array-like of shape (n_samples, 1)
|
|
56
|
+
Input data to transform.
|
|
57
|
+
|
|
58
|
+
Returns
|
|
59
|
+
-------
|
|
60
|
+
X_binned : ndarray of shape (n_samples, 1)
|
|
61
|
+
Binned data with integer bin indices.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
X = np.asarray(X) # Ensures squeeze works and consistent input
|
|
65
|
+
if X.ndim != 2 or X.shape[1] != 1:
|
|
66
|
+
raise ValueError("Input must be a 2D array with shape (n_samples, 1).")
|
|
67
|
+
|
|
68
|
+
if X.shape[0] <= 2:
|
|
69
|
+
raise ValueError("Input must have more than 2 observations.")
|
|
70
|
+
|
|
71
|
+
if isinstance(self.bins, int):
|
|
72
|
+
# Calculate equal width bins based on the range of the data and number of bins
|
|
73
|
+
_, bins = pd.cut(X.squeeze(), bins=self.bins, retbins=True)
|
|
74
|
+
else:
|
|
75
|
+
# Use predefined bins
|
|
76
|
+
bins = self.bins
|
|
77
|
+
|
|
78
|
+
# Apply the bins to the data
|
|
79
|
+
binned_data = pd.cut( # type: ignore
|
|
80
|
+
X.squeeze(),
|
|
81
|
+
bins=np.sort(np.unique(bins)), # type: ignore
|
|
82
|
+
labels=False,
|
|
83
|
+
include_lowest=True,
|
|
84
|
+
)
|
|
85
|
+
return np.expand_dims(np.array(binned_data), 1)
|
|
86
|
+
|
|
87
|
+
def get_feature_names_out(self, input_features=None):
|
|
88
|
+
"""Returns the names of the transformed features.
|
|
89
|
+
|
|
90
|
+
Parameters:
|
|
91
|
+
input_features (list of str): The names of the input features.
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
input_features (array of shape (n_features,)): The names of the output features after transformation.
|
|
95
|
+
"""
|
|
96
|
+
if input_features is None:
|
|
97
|
+
raise ValueError("input_features must be specified")
|
|
98
|
+
return input_features
|