neurotabular 1.0.2__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 neurotabular might be problematic. Click here for more details.
- neurotabular/__init__.py +7 -0
- neurotabular/_base.py +630 -0
- neurotabular/_version.py +3 -0
- neurotabular/_warnings.py +32 -0
- neurotabular/classifier.py +247 -0
- neurotabular/device.py +219 -0
- neurotabular/network.py +383 -0
- neurotabular/preprocessing.py +528 -0
- neurotabular/regressor.py +177 -0
- neurotabular/tasks.py +65 -0
- neurotabular/training.py +646 -0
- neurotabular-1.0.2.dist-info/METADATA +421 -0
- neurotabular-1.0.2.dist-info/RECORD +16 -0
- neurotabular-1.0.2.dist-info/WHEEL +5 -0
- neurotabular-1.0.2.dist-info/licenses/LICENSE +21 -0
- neurotabular-1.0.2.dist-info/top_level.txt +1 -0
neurotabular/__init__.py
ADDED
neurotabular/_base.py
ADDED
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
"""Shared estimator fit mechanics; task semantics live in the public estimators."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import random
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from copy import copy
|
|
9
|
+
from numbers import Integral, Real
|
|
10
|
+
from time import perf_counter
|
|
11
|
+
from typing import Hashable
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import pandas as pd
|
|
15
|
+
import torch
|
|
16
|
+
from sklearn.base import BaseEstimator
|
|
17
|
+
from sklearn.model_selection import train_test_split
|
|
18
|
+
from sklearn.utils.validation import check_is_fitted
|
|
19
|
+
|
|
20
|
+
from ._version import __version__
|
|
21
|
+
from .device import resolve_device
|
|
22
|
+
from .network import TabularNetwork
|
|
23
|
+
from .preprocessing import TabularPreprocessor
|
|
24
|
+
from .tasks import BINARY_TASK
|
|
25
|
+
from .training import (
|
|
26
|
+
predict_outputs,
|
|
27
|
+
resolve_batch_size,
|
|
28
|
+
train_fixed_epochs,
|
|
29
|
+
train_model,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _BaseNeuroTabularEstimator(BaseEstimator):
|
|
34
|
+
"""Shared validation, preprocessing, transactional fit and device mechanics."""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
hidden_dim: int = 64,
|
|
39
|
+
n_blocks: int = 2,
|
|
40
|
+
dropout: float = 0.1,
|
|
41
|
+
lr: float = 3e-3,
|
|
42
|
+
weight_decay: float = 1e-5,
|
|
43
|
+
batch_size: int | str = "auto",
|
|
44
|
+
max_epochs: int = 30,
|
|
45
|
+
validation_fraction: float = 0.2,
|
|
46
|
+
patience: int = 4,
|
|
47
|
+
min_delta: float = 1e-4,
|
|
48
|
+
eval_frequency: int = 1,
|
|
49
|
+
eval_metric: str = "loss",
|
|
50
|
+
class_weight: str | None = None,
|
|
51
|
+
categorical_features: Sequence[Hashable] | None = None,
|
|
52
|
+
min_category_count: int = 2,
|
|
53
|
+
numerical_embedding: str = "scalar",
|
|
54
|
+
use_category_frequency: bool = True,
|
|
55
|
+
feature_gating: bool = False,
|
|
56
|
+
full_data_refit: bool = False,
|
|
57
|
+
device: str = "auto",
|
|
58
|
+
random_state: int = 42,
|
|
59
|
+
verbose: int = 0,
|
|
60
|
+
) -> None:
|
|
61
|
+
self.hidden_dim = hidden_dim
|
|
62
|
+
self.n_blocks = n_blocks
|
|
63
|
+
self.dropout = dropout
|
|
64
|
+
self.lr = lr
|
|
65
|
+
self.weight_decay = weight_decay
|
|
66
|
+
self.batch_size = batch_size
|
|
67
|
+
self.max_epochs = max_epochs
|
|
68
|
+
self.validation_fraction = validation_fraction
|
|
69
|
+
self.patience = patience
|
|
70
|
+
self.min_delta = min_delta
|
|
71
|
+
self.eval_frequency = eval_frequency
|
|
72
|
+
self.eval_metric = eval_metric
|
|
73
|
+
self.class_weight = class_weight
|
|
74
|
+
self.categorical_features = categorical_features
|
|
75
|
+
self.min_category_count = min_category_count
|
|
76
|
+
self.numerical_embedding = numerical_embedding
|
|
77
|
+
self.use_category_frequency = use_category_frequency
|
|
78
|
+
self.feature_gating = feature_gating
|
|
79
|
+
self.full_data_refit = full_data_refit
|
|
80
|
+
self.device = device
|
|
81
|
+
self.random_state = random_state
|
|
82
|
+
self.verbose = verbose
|
|
83
|
+
|
|
84
|
+
def fit(
|
|
85
|
+
self,
|
|
86
|
+
X: pd.DataFrame,
|
|
87
|
+
y: object,
|
|
88
|
+
sample_weight: object | None = None,
|
|
89
|
+
eval_set: tuple[pd.DataFrame, object] | None = None,
|
|
90
|
+
) -> _BaseNeuroTabularEstimator:
|
|
91
|
+
"""Fit the estimator transactionally and restore caller RNG state.
|
|
92
|
+
|
|
93
|
+
When ``eval_set`` is omitted, fitting creates an internal split,
|
|
94
|
+
stratified for classification and random for regression.
|
|
95
|
+
Preprocessing is learned from training rows only. Rows
|
|
96
|
+
with zero ``sample_weight`` are ignored completely. A failed re-fit leaves
|
|
97
|
+
an already fitted estimator usable.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
python_random_state = random.getstate()
|
|
101
|
+
numpy_random_state = np.random.get_state()
|
|
102
|
+
torch_random_state = torch.random.get_rng_state()
|
|
103
|
+
cuda_random_states = (
|
|
104
|
+
torch.cuda.get_rng_state_all() if torch.cuda.is_initialized() else None
|
|
105
|
+
)
|
|
106
|
+
candidate = copy(self)
|
|
107
|
+
candidate._clear_fitted_state()
|
|
108
|
+
try:
|
|
109
|
+
candidate._fit_impl(X, y, sample_weight=sample_weight, eval_set=eval_set)
|
|
110
|
+
finally:
|
|
111
|
+
random.setstate(python_random_state)
|
|
112
|
+
np.random.set_state(numpy_random_state)
|
|
113
|
+
torch.random.set_rng_state(torch_random_state)
|
|
114
|
+
if cuda_random_states is not None:
|
|
115
|
+
torch.cuda.set_rng_state_all(cuda_random_states)
|
|
116
|
+
self.__dict__.clear()
|
|
117
|
+
self.__dict__.update(candidate.__dict__)
|
|
118
|
+
return self
|
|
119
|
+
|
|
120
|
+
def _fit_impl(
|
|
121
|
+
self,
|
|
122
|
+
X: pd.DataFrame,
|
|
123
|
+
y: object,
|
|
124
|
+
sample_weight: object | None = None,
|
|
125
|
+
eval_set: tuple[pd.DataFrame, object] | None = None,
|
|
126
|
+
) -> None:
|
|
127
|
+
"""Build a complete fitted candidate before :meth:`fit` commits it."""
|
|
128
|
+
|
|
129
|
+
fit_started = perf_counter()
|
|
130
|
+
self._validate_hyperparameters()
|
|
131
|
+
X = self._validate_X(X)
|
|
132
|
+
original_sample_count = len(X)
|
|
133
|
+
raw_target = self._target_array(y, original_sample_count, allow_missing=True)
|
|
134
|
+
all_sample_weight = self._validate_sample_weight(
|
|
135
|
+
sample_weight, original_sample_count
|
|
136
|
+
)
|
|
137
|
+
if all_sample_weight is not None:
|
|
138
|
+
positive_weight = all_sample_weight > 0.0
|
|
139
|
+
X = X.iloc[np.flatnonzero(positive_weight)]
|
|
140
|
+
raw_target = raw_target[positive_weight]
|
|
141
|
+
all_sample_weight = all_sample_weight[positive_weight]
|
|
142
|
+
y_array = self._validate_target(raw_target, len(X))
|
|
143
|
+
self.n_effective_samples_ = len(X)
|
|
144
|
+
self.n_ignored_samples_ = original_sample_count - len(X)
|
|
145
|
+
device = self._resolve_device()
|
|
146
|
+
self.device_ = str(device)
|
|
147
|
+
self._set_random_state(device)
|
|
148
|
+
|
|
149
|
+
if eval_set is None:
|
|
150
|
+
indices = np.arange(len(X))
|
|
151
|
+
try:
|
|
152
|
+
train_indices, validation_indices = train_test_split(
|
|
153
|
+
indices,
|
|
154
|
+
test_size=self.validation_fraction,
|
|
155
|
+
random_state=self.random_state,
|
|
156
|
+
shuffle=True,
|
|
157
|
+
stratify=None if self._task_.name == "regression" else y_array,
|
|
158
|
+
)
|
|
159
|
+
except ValueError as exc:
|
|
160
|
+
if self._task_.name == "regression":
|
|
161
|
+
raise ValueError(
|
|
162
|
+
"Unable to create a validation split; provide more rows or adjust validation_fraction."
|
|
163
|
+
) from exc
|
|
164
|
+
raise ValueError(
|
|
165
|
+
"Unable to create a stratified validation split. Provide more "
|
|
166
|
+
"samples per class or adjust validation_fraction."
|
|
167
|
+
) from exc
|
|
168
|
+
X_train = X.iloc[train_indices]
|
|
169
|
+
X_validation = X.iloc[validation_indices]
|
|
170
|
+
y_train = y_array[train_indices]
|
|
171
|
+
y_validation = y_array[validation_indices]
|
|
172
|
+
train_sample_weight = (
|
|
173
|
+
None if all_sample_weight is None else all_sample_weight[train_indices]
|
|
174
|
+
)
|
|
175
|
+
validation_weight = (
|
|
176
|
+
np.ones(len(validation_indices), dtype=np.float64)
|
|
177
|
+
if all_sample_weight is None
|
|
178
|
+
else all_sample_weight[validation_indices]
|
|
179
|
+
)
|
|
180
|
+
else:
|
|
181
|
+
X_validation, raw_validation_target = self._validate_eval_set(eval_set)
|
|
182
|
+
y_validation = self._validate_validation_target(
|
|
183
|
+
raw_validation_target, len(X_validation)
|
|
184
|
+
)
|
|
185
|
+
X_train = X
|
|
186
|
+
y_train = y_array
|
|
187
|
+
train_sample_weight = all_sample_weight
|
|
188
|
+
validation_weight = np.ones(len(X_validation), dtype=np.float64)
|
|
189
|
+
if (
|
|
190
|
+
self._task_.name == "regression"
|
|
191
|
+
and self.eval_metric == "r2"
|
|
192
|
+
and len(y_validation) < 2
|
|
193
|
+
):
|
|
194
|
+
raise ValueError("eval_metric='r2' requires at least two validation rows.")
|
|
195
|
+
if self.eval_metric == "roc_auc" and np.unique(y_validation).size < 2:
|
|
196
|
+
raise ValueError(
|
|
197
|
+
"eval_metric='roc_auc' requires both target classes in validation."
|
|
198
|
+
)
|
|
199
|
+
if not np.any(validation_weight > 0.0):
|
|
200
|
+
raise ValueError("Validation must contain at least one positive weight.")
|
|
201
|
+
|
|
202
|
+
preprocessing_started = perf_counter()
|
|
203
|
+
self._preprocessor_ = TabularPreprocessor(
|
|
204
|
+
categorical_features=self.categorical_features,
|
|
205
|
+
min_category_count=self.min_category_count,
|
|
206
|
+
use_category_frequency=self.use_category_frequency,
|
|
207
|
+
max_categories=getattr(self, "_experimental_max_categories", None),
|
|
208
|
+
hash_buckets=int(getattr(self, "_experimental_hash_buckets", 0)),
|
|
209
|
+
)
|
|
210
|
+
self._preprocessor_.fit(X_train)
|
|
211
|
+
fit_preprocessing_profile = dict(self._preprocessor_.fit_profile_)
|
|
212
|
+
train_data = self._preprocessor_.transform(X_train)
|
|
213
|
+
train_transform_profile = dict(self._preprocessor_.last_transform_profile_)
|
|
214
|
+
validation_data = self._preprocessor_.transform(X_validation)
|
|
215
|
+
validation_transform_profile = dict(self._preprocessor_.last_transform_profile_)
|
|
216
|
+
self.preprocessing_time_ = perf_counter() - preprocessing_started
|
|
217
|
+
|
|
218
|
+
self.n_features_in_ = X.shape[1]
|
|
219
|
+
if all(isinstance(name, str) for name in X.columns):
|
|
220
|
+
self.feature_names_in_ = np.asarray(X.columns, dtype=object)
|
|
221
|
+
elif hasattr(self, "feature_names_in_"):
|
|
222
|
+
del self.feature_names_in_
|
|
223
|
+
self.numeric_features_ = list(self._preprocessor_.numeric_features_)
|
|
224
|
+
self.categorical_features_ = list(self._preprocessor_.categorical_features_)
|
|
225
|
+
|
|
226
|
+
target_started = perf_counter()
|
|
227
|
+
self._prepare_target(y_train, train_sample_weight)
|
|
228
|
+
y_train_encoded = self._encode_target(y_train)
|
|
229
|
+
y_validation_encoded = self._encode_target(y_validation)
|
|
230
|
+
if self.eval_metric == "roc_auc" and any(
|
|
231
|
+
not np.any(validation_weight[y_validation_encoded == class_id] > 0.0)
|
|
232
|
+
for class_id in (0.0, 1.0)
|
|
233
|
+
):
|
|
234
|
+
raise ValueError(
|
|
235
|
+
"eval_metric='roc_auc' requires positive validation weight for "
|
|
236
|
+
"both target classes."
|
|
237
|
+
)
|
|
238
|
+
validation_weight = self._normalize_weight(
|
|
239
|
+
validation_weight, name="validation sample weight"
|
|
240
|
+
)
|
|
241
|
+
train_weight = self._combined_training_weight(
|
|
242
|
+
y_train_encoded, train_sample_weight
|
|
243
|
+
)
|
|
244
|
+
target_preparation_time = perf_counter() - target_started
|
|
245
|
+
self._model_ = self._new_model(self._preprocessor_)
|
|
246
|
+
self._set_prior_bias(self._model_, y_train_encoded, train_weight)
|
|
247
|
+
self.n_parameters_ = self._model_.parameter_count
|
|
248
|
+
self.embedding_dimensions_ = list(self._model_.embedding_dimensions)
|
|
249
|
+
self.batch_size_ = resolve_batch_size(
|
|
250
|
+
self.batch_size,
|
|
251
|
+
n_samples=len(X_train),
|
|
252
|
+
n_numeric_inputs=self._model_.input_width,
|
|
253
|
+
categorical_cardinalities=(self._preprocessor_.categorical_cardinalities_),
|
|
254
|
+
hidden_dim=self.hidden_dim,
|
|
255
|
+
n_blocks=self.n_blocks,
|
|
256
|
+
device=device,
|
|
257
|
+
)
|
|
258
|
+
self.inference_batch_size_ = max(1_024, self.batch_size_)
|
|
259
|
+
|
|
260
|
+
training_result = train_model(
|
|
261
|
+
self._model_,
|
|
262
|
+
train_data,
|
|
263
|
+
y_train_encoded,
|
|
264
|
+
train_weight,
|
|
265
|
+
validation_data,
|
|
266
|
+
y_validation_encoded,
|
|
267
|
+
validation_weight,
|
|
268
|
+
device=device,
|
|
269
|
+
batch_size=self.batch_size_,
|
|
270
|
+
max_epochs=self.max_epochs,
|
|
271
|
+
patience=self.patience,
|
|
272
|
+
min_delta=float(self.min_delta),
|
|
273
|
+
eval_frequency=self.eval_frequency,
|
|
274
|
+
eval_metric=self.eval_metric,
|
|
275
|
+
lr=float(self.lr),
|
|
276
|
+
weight_decay=float(self.weight_decay),
|
|
277
|
+
random_state=self.random_state,
|
|
278
|
+
verbose=self.verbose,
|
|
279
|
+
use_amp=bool(self.device_info_["amp_enabled"]),
|
|
280
|
+
task=self._task_,
|
|
281
|
+
)
|
|
282
|
+
self.best_epoch_ = training_result.best_epoch
|
|
283
|
+
self.best_score_ = training_result.best_score
|
|
284
|
+
self.best_validation_loss_ = training_result.best_validation_loss
|
|
285
|
+
self.n_iter_ = training_result.n_iter
|
|
286
|
+
self.history_ = training_result.history
|
|
287
|
+
self.training_time_ = float(training_result.profile["training_compute_seconds"])
|
|
288
|
+
self.validation_time_ = float(training_result.profile["validation_seconds"])
|
|
289
|
+
refit_profile = None
|
|
290
|
+
self.full_data_refit_ = False
|
|
291
|
+
if self.full_data_refit and eval_set is None:
|
|
292
|
+
refit_started = perf_counter()
|
|
293
|
+
refit_preprocessor = TabularPreprocessor(
|
|
294
|
+
categorical_features=self.categorical_features,
|
|
295
|
+
min_category_count=self.min_category_count,
|
|
296
|
+
use_category_frequency=self.use_category_frequency,
|
|
297
|
+
max_categories=getattr(self, "_experimental_max_categories", None),
|
|
298
|
+
hash_buckets=int(getattr(self, "_experimental_hash_buckets", 0)),
|
|
299
|
+
).fit(X)
|
|
300
|
+
refit_fit_profile = dict(refit_preprocessor.fit_profile_)
|
|
301
|
+
refit_data = refit_preprocessor.transform(X)
|
|
302
|
+
refit_transform_profile = dict(refit_preprocessor.last_transform_profile_)
|
|
303
|
+
self._prepare_target(y_array, all_sample_weight)
|
|
304
|
+
full_target = self._encode_target(y_array)
|
|
305
|
+
full_weight = self._combined_training_weight(full_target, all_sample_weight)
|
|
306
|
+
self._set_random_state(device)
|
|
307
|
+
refit_model = self._new_model(refit_preprocessor)
|
|
308
|
+
self._set_prior_bias(refit_model, full_target, full_weight)
|
|
309
|
+
refit_batch_size = resolve_batch_size(
|
|
310
|
+
self.batch_size,
|
|
311
|
+
n_samples=len(X),
|
|
312
|
+
n_numeric_inputs=refit_model.input_width,
|
|
313
|
+
categorical_cardinalities=(
|
|
314
|
+
refit_preprocessor.categorical_cardinalities_
|
|
315
|
+
),
|
|
316
|
+
hidden_dim=self.hidden_dim,
|
|
317
|
+
n_blocks=self.n_blocks,
|
|
318
|
+
device=device,
|
|
319
|
+
)
|
|
320
|
+
refit_training_profile = train_fixed_epochs(
|
|
321
|
+
refit_model,
|
|
322
|
+
refit_data,
|
|
323
|
+
full_target,
|
|
324
|
+
full_weight,
|
|
325
|
+
device=device,
|
|
326
|
+
batch_size=refit_batch_size,
|
|
327
|
+
epochs=self.best_epoch_,
|
|
328
|
+
lr=float(self.lr),
|
|
329
|
+
weight_decay=float(self.weight_decay),
|
|
330
|
+
random_state=self.random_state,
|
|
331
|
+
use_amp=bool(self.device_info_["amp_enabled"]),
|
|
332
|
+
task=self._task_,
|
|
333
|
+
)
|
|
334
|
+
self._preprocessor_ = refit_preprocessor
|
|
335
|
+
self._model_ = refit_model
|
|
336
|
+
self.batch_size_ = refit_batch_size
|
|
337
|
+
self.inference_batch_size_ = max(1_024, refit_batch_size)
|
|
338
|
+
self.n_parameters_ = refit_model.parameter_count
|
|
339
|
+
self.embedding_dimensions_ = list(refit_model.embedding_dimensions)
|
|
340
|
+
self.full_data_refit_ = True
|
|
341
|
+
self.training_time_ += float(refit_training_profile["engine_total_seconds"])
|
|
342
|
+
refit_profile = {
|
|
343
|
+
"preprocessing_fit": refit_fit_profile,
|
|
344
|
+
"transform": refit_transform_profile,
|
|
345
|
+
"training": refit_training_profile,
|
|
346
|
+
"total_seconds": perf_counter() - refit_started,
|
|
347
|
+
}
|
|
348
|
+
self.profile_ = {
|
|
349
|
+
"preprocessing": {
|
|
350
|
+
"fit": fit_preprocessing_profile,
|
|
351
|
+
"train_transform": train_transform_profile,
|
|
352
|
+
"validation_transform": validation_transform_profile,
|
|
353
|
+
"total_seconds": self.preprocessing_time_,
|
|
354
|
+
},
|
|
355
|
+
"training": training_result.profile,
|
|
356
|
+
"target_preparation_seconds": target_preparation_time,
|
|
357
|
+
"device": dict(self.device_info_),
|
|
358
|
+
}
|
|
359
|
+
if refit_profile is not None:
|
|
360
|
+
self.profile_["full_data_refit"] = refit_profile
|
|
361
|
+
# Detached diagnostic metadata describes the final training-only encoder.
|
|
362
|
+
# Prediction never reads this snapshot; no rows or vocabulary are copied.
|
|
363
|
+
cardinalities = dict(
|
|
364
|
+
zip(
|
|
365
|
+
self._preprocessor_.categorical_features_,
|
|
366
|
+
self._preprocessor_.categorical_cardinalities_,
|
|
367
|
+
strict=True,
|
|
368
|
+
)
|
|
369
|
+
)
|
|
370
|
+
schema = []
|
|
371
|
+
for name, dtype in X.dtypes.items():
|
|
372
|
+
entry = {
|
|
373
|
+
"name": name,
|
|
374
|
+
"dtype": str(dtype),
|
|
375
|
+
"kind": "categorical" if name in cardinalities else "numeric",
|
|
376
|
+
}
|
|
377
|
+
if name in cardinalities:
|
|
378
|
+
rare_count = len(self._preprocessor_.rare_categories_[name])
|
|
379
|
+
entry.update(
|
|
380
|
+
n_known_categories=(
|
|
381
|
+
len(self._preprocessor_.category_vocabs_[name]) + rare_count
|
|
382
|
+
),
|
|
383
|
+
n_rare_categories=rare_count,
|
|
384
|
+
encoded_cardinality=cardinalities[name],
|
|
385
|
+
)
|
|
386
|
+
schema.append(entry)
|
|
387
|
+
self.input_schema_ = tuple(schema)
|
|
388
|
+
# Diagnostic provenance only; never consulted by prediction or loading.
|
|
389
|
+
self._fitted_neurotabular_version_ = __version__
|
|
390
|
+
self.fit_time_ = perf_counter() - fit_started
|
|
391
|
+
|
|
392
|
+
def _predict_values(self, X: pd.DataFrame) -> np.ndarray:
|
|
393
|
+
check_is_fitted(self, ["_model_", "_preprocessor_"])
|
|
394
|
+
prediction_started = perf_counter()
|
|
395
|
+
X = self._validate_X(X, fitting=False)
|
|
396
|
+
data = self._preprocessor_.transform(X)
|
|
397
|
+
probabilities = predict_outputs(
|
|
398
|
+
self._model_,
|
|
399
|
+
data,
|
|
400
|
+
device=torch.device(self.device_),
|
|
401
|
+
batch_size=self.inference_batch_size_,
|
|
402
|
+
task=getattr(self, "_task_", BINARY_TASK),
|
|
403
|
+
)
|
|
404
|
+
self.last_prediction_time_ = perf_counter() - prediction_started
|
|
405
|
+
return probabilities
|
|
406
|
+
|
|
407
|
+
def _new_model(self, preprocessor: TabularPreprocessor) -> TabularNetwork:
|
|
408
|
+
return TabularNetwork(
|
|
409
|
+
n_numeric_features=preprocessor.n_numeric_outputs_,
|
|
410
|
+
categorical_cardinalities=preprocessor.categorical_cardinalities_,
|
|
411
|
+
hidden_dim=self.hidden_dim,
|
|
412
|
+
n_blocks=self.n_blocks,
|
|
413
|
+
dropout=self.dropout,
|
|
414
|
+
n_continuous_features=preprocessor.n_continuous_features_,
|
|
415
|
+
numerical_knots=torch.from_numpy(preprocessor.numeric_knots_),
|
|
416
|
+
numerical_embedding=self.numerical_embedding,
|
|
417
|
+
dataset_size=preprocessor.fit_sample_count_,
|
|
418
|
+
feature_gating=self.feature_gating,
|
|
419
|
+
categorical_dropout=float(
|
|
420
|
+
getattr(self, "_experimental_categorical_dropout", 0.0)
|
|
421
|
+
),
|
|
422
|
+
embedding_dropout=float(
|
|
423
|
+
getattr(self, "_experimental_embedding_dropout", 0.0)
|
|
424
|
+
),
|
|
425
|
+
output_dim=self._task_.output_dim,
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
@staticmethod
|
|
429
|
+
def _target_array(
|
|
430
|
+
y: object,
|
|
431
|
+
n_samples: int,
|
|
432
|
+
*,
|
|
433
|
+
name: str = "y",
|
|
434
|
+
allow_missing: bool = False,
|
|
435
|
+
) -> np.ndarray:
|
|
436
|
+
y_array = np.asarray(y)
|
|
437
|
+
if y_array.ndim != 1:
|
|
438
|
+
raise ValueError(f"{name} must be one-dimensional.")
|
|
439
|
+
if len(y_array) != n_samples:
|
|
440
|
+
raise ValueError(f"X and {name} contain different numbers of samples.")
|
|
441
|
+
if not allow_missing and pd.isna(y_array).any():
|
|
442
|
+
raise ValueError(f"{name} must not contain missing values.")
|
|
443
|
+
return y_array
|
|
444
|
+
|
|
445
|
+
@staticmethod
|
|
446
|
+
def _normalize_weight(weight: np.ndarray, *, name: str) -> np.ndarray:
|
|
447
|
+
"""Scale weights to mean one without overflowing their float32 tensor."""
|
|
448
|
+
|
|
449
|
+
values = np.asarray(weight, dtype=np.float64)
|
|
450
|
+
positive = values > 0.0
|
|
451
|
+
if not np.any(positive):
|
|
452
|
+
raise ValueError(f"{name} must contain at least one positive value.")
|
|
453
|
+
maximum = float(values[positive].max())
|
|
454
|
+
scaled = values / maximum
|
|
455
|
+
if np.any(positive & (scaled == 0.0)):
|
|
456
|
+
raise ValueError(f"{name} has a dynamic range too large for training.")
|
|
457
|
+
normalized = scaled / float(np.mean(scaled, dtype=np.float64))
|
|
458
|
+
float32 = np.finfo(np.float32)
|
|
459
|
+
positive_normalized = normalized[positive]
|
|
460
|
+
if (
|
|
461
|
+
not np.isfinite(normalized).all()
|
|
462
|
+
or float(normalized.max()) > float32.max
|
|
463
|
+
or float(positive_normalized.min()) < float32.tiny
|
|
464
|
+
):
|
|
465
|
+
raise ValueError(f"{name} cannot be represented safely in float32.")
|
|
466
|
+
return normalized
|
|
467
|
+
|
|
468
|
+
@staticmethod
|
|
469
|
+
def _validate_sample_weight(
|
|
470
|
+
sample_weight: object | None, n_samples: int
|
|
471
|
+
) -> np.ndarray | None:
|
|
472
|
+
if sample_weight is None:
|
|
473
|
+
return None
|
|
474
|
+
try:
|
|
475
|
+
weights = np.asarray(sample_weight, dtype=np.float64)
|
|
476
|
+
except (TypeError, ValueError) as exc:
|
|
477
|
+
raise ValueError("sample_weight must contain numeric values.") from exc
|
|
478
|
+
if weights.ndim != 1:
|
|
479
|
+
raise ValueError("sample_weight must be one-dimensional.")
|
|
480
|
+
if len(weights) != n_samples:
|
|
481
|
+
raise ValueError(
|
|
482
|
+
"X and sample_weight contain different numbers of samples."
|
|
483
|
+
)
|
|
484
|
+
if not np.isfinite(weights).all():
|
|
485
|
+
raise ValueError("sample_weight must contain only finite values.")
|
|
486
|
+
if np.any(weights < 0.0):
|
|
487
|
+
raise ValueError("sample_weight values must be non-negative.")
|
|
488
|
+
if not np.any(weights > 0.0):
|
|
489
|
+
raise ValueError("sample_weight must contain at least one positive value.")
|
|
490
|
+
return weights
|
|
491
|
+
|
|
492
|
+
def _validate_eval_set(self, eval_set: object) -> tuple[pd.DataFrame, object]:
|
|
493
|
+
if not isinstance(eval_set, (tuple, list)) or len(eval_set) != 2:
|
|
494
|
+
raise TypeError("eval_set must be a single (X_valid, y_valid) pair.")
|
|
495
|
+
X_validation = self._validate_X(eval_set[0], fitting=False)
|
|
496
|
+
return X_validation, eval_set[1]
|
|
497
|
+
|
|
498
|
+
@staticmethod
|
|
499
|
+
def _validate_X(X: pd.DataFrame, *, fitting: bool = True) -> pd.DataFrame:
|
|
500
|
+
if not isinstance(X, pd.DataFrame):
|
|
501
|
+
raise TypeError(
|
|
502
|
+
"X must be a pandas.DataFrame. Convert the input to a DataFrame "
|
|
503
|
+
"with the same named columns for fit and predict."
|
|
504
|
+
)
|
|
505
|
+
if len(X) == 0:
|
|
506
|
+
raise ValueError("X must contain at least one row.")
|
|
507
|
+
if X.shape[1] == 0:
|
|
508
|
+
raise ValueError("X must contain at least one feature column.")
|
|
509
|
+
if not X.columns.is_unique:
|
|
510
|
+
duplicates = X.columns[X.columns.duplicated()].tolist()
|
|
511
|
+
raise ValueError(
|
|
512
|
+
f"X must have unique column names; duplicates: {duplicates!r}. "
|
|
513
|
+
"Rename or remove duplicate columns."
|
|
514
|
+
)
|
|
515
|
+
return X
|
|
516
|
+
|
|
517
|
+
def _validate_hyperparameters(self) -> None:
|
|
518
|
+
self._positive_integer(self.hidden_dim, "hidden_dim")
|
|
519
|
+
self._positive_integer(self.n_blocks, "n_blocks")
|
|
520
|
+
self._unit_interval(self.dropout, "dropout", upper_inclusive=False)
|
|
521
|
+
self._positive_real(self.lr, "lr")
|
|
522
|
+
self._non_negative_real(self.weight_decay, "weight_decay")
|
|
523
|
+
if self.batch_size != "auto":
|
|
524
|
+
self._positive_integer(self.batch_size, "batch_size")
|
|
525
|
+
self._positive_integer(self.max_epochs, "max_epochs")
|
|
526
|
+
self._unit_interval(
|
|
527
|
+
self.validation_fraction,
|
|
528
|
+
"validation_fraction",
|
|
529
|
+
lower_inclusive=False,
|
|
530
|
+
upper_inclusive=False,
|
|
531
|
+
)
|
|
532
|
+
self._positive_integer(self.patience, "patience")
|
|
533
|
+
self._non_negative_real(self.min_delta, "min_delta")
|
|
534
|
+
self._positive_integer(self.eval_frequency, "eval_frequency")
|
|
535
|
+
self._positive_integer(self.min_category_count, "min_category_count")
|
|
536
|
+
if self.numerical_embedding not in {
|
|
537
|
+
"scalar",
|
|
538
|
+
"affine",
|
|
539
|
+
"periodic",
|
|
540
|
+
"piecewise",
|
|
541
|
+
}:
|
|
542
|
+
raise ValueError(
|
|
543
|
+
"numerical_embedding must be 'scalar', 'affine', 'periodic', "
|
|
544
|
+
"or 'piecewise'."
|
|
545
|
+
)
|
|
546
|
+
if not isinstance(self.use_category_frequency, bool):
|
|
547
|
+
raise TypeError("use_category_frequency must be a boolean.")
|
|
548
|
+
if not isinstance(self.feature_gating, bool):
|
|
549
|
+
raise TypeError("feature_gating must be a boolean.")
|
|
550
|
+
if not isinstance(self.full_data_refit, bool):
|
|
551
|
+
raise TypeError("full_data_refit must be a boolean.")
|
|
552
|
+
if self.eval_metric not in self._supported_metrics:
|
|
553
|
+
raise ValueError(
|
|
554
|
+
f"eval_metric must be one of {sorted(self._supported_metrics)!r}."
|
|
555
|
+
)
|
|
556
|
+
if self.class_weight not in (None, "balanced"):
|
|
557
|
+
raise ValueError("class_weight must be None or 'balanced'.")
|
|
558
|
+
if not isinstance(self.random_state, Integral) or isinstance(
|
|
559
|
+
self.random_state, bool
|
|
560
|
+
):
|
|
561
|
+
raise TypeError("random_state must be an integer.")
|
|
562
|
+
if self.verbose not in {0, 1}:
|
|
563
|
+
raise ValueError("verbose must be 0 or 1.")
|
|
564
|
+
if not isinstance(self.device, str):
|
|
565
|
+
raise TypeError("device must be 'auto', 'cpu', or a CUDA device string.")
|
|
566
|
+
if self.device not in {"auto", "cpu", "cuda"} and not self.device.startswith(
|
|
567
|
+
"cuda:"
|
|
568
|
+
):
|
|
569
|
+
raise ValueError("device must be 'auto', 'cpu', or a CUDA device string.")
|
|
570
|
+
|
|
571
|
+
def _resolve_device(self) -> torch.device:
|
|
572
|
+
device, info = resolve_device(self.device)
|
|
573
|
+
self.device_info_ = info
|
|
574
|
+
return device
|
|
575
|
+
|
|
576
|
+
def _clear_fitted_state(self) -> None:
|
|
577
|
+
for name in tuple(self.__dict__):
|
|
578
|
+
if name.endswith("_"):
|
|
579
|
+
del self.__dict__[name]
|
|
580
|
+
|
|
581
|
+
def _set_random_state(self, device: torch.device) -> None:
|
|
582
|
+
seed = int(self.random_state)
|
|
583
|
+
random.seed(seed)
|
|
584
|
+
np.random.seed(seed)
|
|
585
|
+
torch.random.default_generator.manual_seed(seed)
|
|
586
|
+
if device.type == "cuda":
|
|
587
|
+
torch.cuda.manual_seed_all(seed)
|
|
588
|
+
|
|
589
|
+
@staticmethod
|
|
590
|
+
def _positive_integer(value: object, name: str) -> None:
|
|
591
|
+
if not isinstance(value, Integral) or isinstance(value, bool) or value < 1:
|
|
592
|
+
raise ValueError(f"{name} must be a positive integer.")
|
|
593
|
+
|
|
594
|
+
@staticmethod
|
|
595
|
+
def _positive_real(value: object, name: str) -> None:
|
|
596
|
+
if (
|
|
597
|
+
not isinstance(value, Real)
|
|
598
|
+
or isinstance(value, bool)
|
|
599
|
+
or not math.isfinite(float(value))
|
|
600
|
+
or value <= 0.0
|
|
601
|
+
):
|
|
602
|
+
raise ValueError(f"{name} must be a finite positive number.")
|
|
603
|
+
|
|
604
|
+
@staticmethod
|
|
605
|
+
def _non_negative_real(value: object, name: str) -> None:
|
|
606
|
+
if (
|
|
607
|
+
not isinstance(value, Real)
|
|
608
|
+
or isinstance(value, bool)
|
|
609
|
+
or not math.isfinite(float(value))
|
|
610
|
+
or value < 0.0
|
|
611
|
+
):
|
|
612
|
+
raise ValueError(f"{name} must be a finite non-negative number.")
|
|
613
|
+
|
|
614
|
+
@staticmethod
|
|
615
|
+
def _unit_interval(
|
|
616
|
+
value: object,
|
|
617
|
+
name: str,
|
|
618
|
+
*,
|
|
619
|
+
lower_inclusive: bool = True,
|
|
620
|
+
upper_inclusive: bool = True,
|
|
621
|
+
) -> None:
|
|
622
|
+
if not isinstance(value, Real) or isinstance(value, bool):
|
|
623
|
+
raise ValueError(f"{name} must be a real number in the unit interval.")
|
|
624
|
+
lower_ok = value >= 0.0 if lower_inclusive else value > 0.0
|
|
625
|
+
upper_ok = value <= 1.0 if upper_inclusive else value < 1.0
|
|
626
|
+
if not math.isfinite(float(value)) or not lower_ok or not upper_ok:
|
|
627
|
+
raise ValueError(f"{name} must be in the required unit interval.")
|
|
628
|
+
|
|
629
|
+
def _prepare_target(self, y: np.ndarray, weight: np.ndarray | None) -> None:
|
|
630
|
+
"""Optional train-only target statistics hook."""
|
neurotabular/_version.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Internal, dormant infrastructure for future announced API deprecations."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import warnings
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _warn_deprecated(feature, *, since, remove_in, replacement, stacklevel=2):
|
|
8
|
+
"""Emit the canonical FutureWarning; no current feature calls this helper.
|
|
9
|
+
|
|
10
|
+
The numeric floor does not replace an actual full minor release of notice,
|
|
11
|
+
migration documentation or a maintainer-approved removal announcement.
|
|
12
|
+
"""
|
|
13
|
+
if not all(
|
|
14
|
+
isinstance(value, str) and value.strip() for value in (feature, replacement)
|
|
15
|
+
):
|
|
16
|
+
raise ValueError("feature and replacement must be nonempty strings.")
|
|
17
|
+
versions = []
|
|
18
|
+
for value in (since, remove_in):
|
|
19
|
+
if not isinstance(value, str) or not re.fullmatch(r"\d+\.\d+\.\d+", value):
|
|
20
|
+
raise ValueError("Deprecation versions must use MAJOR.MINOR.PATCH.")
|
|
21
|
+
versions.append(tuple(map(int, value.split("."))))
|
|
22
|
+
first, last = versions
|
|
23
|
+
if last <= first or (last[0] == first[0] and last[1] < first[1] + 2):
|
|
24
|
+
raise ValueError(
|
|
25
|
+
"Removal requires at least one complete minor series of notice."
|
|
26
|
+
)
|
|
27
|
+
warnings.warn(
|
|
28
|
+
f"NeuroTabular: {feature} is deprecated since {since}; "
|
|
29
|
+
f"removal no earlier than {remove_in}. Use {replacement} instead.",
|
|
30
|
+
FutureWarning,
|
|
31
|
+
stacklevel=stacklevel,
|
|
32
|
+
)
|