diff --git a/docs/core_concepts/missing_values.md b/docs/core_concepts/missing_values.md index 249f8ab..f2a3e4e 100644 --- a/docs/core_concepts/missing_values.md +++ b/docs/core_concepts/missing_values.md @@ -36,8 +36,9 @@ consistently with imputation. Disabling imputation lets `NaN` reach the transformer directly. Scalers, splines, and the feature maps (`rbf`, `relu`, `sigmoid`, `tanh`) propagate it: the affected row's output columns for that feature are `NaN` (a spline's optional bias column stays `1`); finite-only methods (PLE, numeric binning, periodic encoding, Fourier -features, `rff`, `nystroem`) raise a typed error instead, since expanding an undefined value -has no meaning for them. `add_missing_indicator=True` still works with imputation disabled: it +features, `rff`, `nystroem`) raise a typed error instead (`PretabDataError`, naming the +affected columns), since expanding an undefined value has no meaning for them. Infinite values +raise the same error for every method. `add_missing_indicator=True` still works with imputation disabled: it routes through the same `__missing` branch `missing_policy="separate_state"` uses below. ``` diff --git a/pretab/core/validation.py b/pretab/core/validation.py index 68ee5cc..24e6be4 100644 --- a/pretab/core/validation.py +++ b/pretab/core/validation.py @@ -243,6 +243,52 @@ def polars_to_pandas(X) -> pd.DataFrame: return pd.DataFrame(columns) +def reject_non_finite(X: np.ndarray, *, allow_nan: bool, estimator) -> None: + """Raise :class:`~pretab.exceptions.PretabDataError` for non-finite values in ``X``. + + Infinite values always raise; NaN raises unless ``allow_nan``. The message names + the estimator and the affected columns (by ``feature_names_in_`` when the + estimator has them, else by position). ``PretabDataError`` subclasses + ``ValueError``, the error scikit-learn's own finiteness check raises. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Validated float input. + allow_nan : bool + Whether missing values (NaN) are accepted. + estimator : object + The calling transformer, named in the message. + + Raises + ------ + PretabDataError + If ``X`` contains infinite values, or NaN when ``allow_nan`` is False. + """ + name = type(estimator).__name__ + labels = getattr(estimator, "feature_names_in_", None) + + def columns(mask: np.ndarray) -> list: + positions = np.flatnonzero(mask.any(axis=0)).tolist() + return [str(labels[j]) for j in positions] if labels is not None else positions + + infinite = np.isinf(X) + if infinite.any(): + raise PretabDataError( + f"{name} received infinite values in column(s) {columns(infinite)}, which have no " + "finite representation. Clean or clip the input first." + ) + if not allow_nan: + missing = np.isnan(X) + if missing.any(): + raise PretabDataError( + f"{name} received missing values (NaN) in column(s) {columns(missing)}, but it needs " + "finite input: expanding an undefined value has no meaning for this representation. " + "Impute them first, for example with the Preprocessor's imputation parameters or " + "missing_policy='impute'." + ) + + def validate_2d_allow_nan(X, *, allow_nan: bool = True, reset: bool, estimator): """Coerce ``X`` to a 2D float array, optionally letting NaNs pass through. @@ -252,7 +298,9 @@ def validate_2d_allow_nan(X, *, allow_nan: bool = True, reset: bool, estimator): Input data. allow_nan : bool, default=True When True, missing values are preserved so a later imputer can handle - them; when False, NaN/inf values raise as usual. + them; when False, NaN raises. Infinite values always raise. Both raise a + :class:`~pretab.exceptions.PretabDataError` (a ``ValueError``) naming the + columns, see :func:`reject_non_finite`. reset : bool When True (during ``fit``) record ``estimator.n_features_in_`` and, for a DataFrame, ``estimator.feature_names_in_``; when False (during @@ -271,13 +319,13 @@ def validate_2d_allow_nan(X, *, allow_nan: bool = True, reset: bool, estimator): _check_feature_names(estimator, X, reset=reset) input_shape = getattr(X, "shape", None) original_dim = input_shape[1] if input_shape is not None and len(input_shape) == 2 else None - ensure_all_finite: Literal["allow-nan"] | bool = "allow-nan" if allow_nan else True X = check_array( X, dtype=np.float64, # type: ignore ensure_2d=True, - ensure_all_finite=ensure_all_finite, # type: ignore + ensure_all_finite=False, # type: ignore ) + reject_non_finite(X, allow_nan=allow_nan, estimator=estimator) if original_dim is not None and X.shape[1] < original_dim: warnings.warn( "Some input features were dropped during check_array validation.", diff --git a/pretab/encoding/numerical/ple.py b/pretab/encoding/numerical/ple.py index d0b6c74..dd64ae7 100644 --- a/pretab/encoding/numerical/ple.py +++ b/pretab/encoding/numerical/ple.py @@ -16,7 +16,7 @@ from ...core.parameters import UNSET, AliasResolverMixin, validate_task from ...core.representation import RepresentationSpecMixin from ...core.supervised import warn_target_leakage -from ...core.validation import resolve_input_features, single_target +from ...core.validation import reject_non_finite, resolve_input_features, single_target from ...exceptions import ( IncompatibleParamsError, InvalidParamError, @@ -180,8 +180,9 @@ def fit(self, X, y=None): X, dtype=np.float64, # type: ignore ensure_2d=True, - ensure_all_finite=True, # type: ignore + ensure_all_finite=False, # type: ignore ) + reject_non_finite(X, allow_nan=False, estimator=self) y = single_target( y, type(self).__name__, @@ -254,8 +255,9 @@ def transform(self, X): X, dtype=np.float64, # type: ignore ensure_2d=True, - ensure_all_finite=True, # type: ignore + ensure_all_finite=False, # type: ignore ) + reject_non_finite(X, allow_nan=False, estimator=self) if X.shape[1] != self.n_features_in_: raise PretabDataError( diff --git a/tests/integration/test_edge_case_contract.py b/tests/integration/test_edge_case_contract.py index 2baea85..6e6aebb 100644 --- a/tests/integration/test_edge_case_contract.py +++ b/tests/integration/test_edge_case_contract.py @@ -221,6 +221,60 @@ def test_infinite_values_are_rejected(name, rng): _factory(name).fit(X, y) +@pytest.mark.parametrize("name", ALL_FAMILIES) +def test_infinite_values_raise_a_typed_error_naming_the_column(name, rng): + X = pd.DataFrame({"age": rng.normal(size=40), "income": rng.normal(size=40)}) + X.loc[0, "income"] = np.inf + y = rng.normal(size=40) + with pytest.raises(PretabDataError, match="infinite values") as failure: + _factory(name).fit(X, y) + if name != "Binning": # binning validates its input itself, without column names + assert "column(s) ['income']" in str(failure.value) + + +def _finite_only(): + from pretab.transformers import ( + FourierFeatureTransformer, + NystroemFeaturesTransformer, + PeriodicEncodingTransformer, + RandomFourierFeaturesTransformer, + ) + + return { + "PLE": lambda: PLETransformer(output_dim=4), + "Binning": lambda: NumericBinningTransformer(output_dim=4), + "Periodic": lambda: PeriodicEncodingTransformer(period=10.0), + "Fourier": lambda: FourierFeatureTransformer(), + "RFF": lambda: RandomFourierFeaturesTransformer(random_state=0), + "Nystroem": lambda: NystroemFeaturesTransformer(n_components=10, random_state=0), + } + + +@pytest.mark.parametrize("name", list(_finite_only())) +@pytest.mark.parametrize("stage", ["fit", "transform"]) +def test_missing_values_into_a_finite_only_method_raise_a_typed_error(name, stage, rng): + """The docs promise a typed error; only binning raised PretabDataError, the others + let scikit-learn's check_array raise a plain ValueError("Input contains NaN.").""" + X = pd.DataFrame({"age": rng.uniform(0, 10, 40), "income": rng.uniform(0, 10, 40)}) + y = rng.normal(size=40) + broken = X.copy() + broken.loc[3, "income"] = np.nan + transformer = _finite_only()[name]() + if stage == "transform": + transformer.fit(X, y) + with pytest.raises(PretabDataError, match=r"NaN") as failure: + transformer.fit(broken, y) if stage == "fit" else transformer.transform(broken) + if name != "Binning": + assert "['income']" in str(failure.value) + + +def test_preprocessor_without_imputation_raises_a_typed_error_for_ple(rng): + X = pd.DataFrame({"age": rng.normal(size=40)}) + X.loc[0, "age"] = np.nan + with pytest.raises(PretabDataError, match=r"PLETransformer received missing values \(NaN\)"): + Preprocessor(numerical_imputation=None).fit(X, rng.normal(size=40)) + + # --------------------------------------------------------------------------- # # Out-of-range values at transform time stay finite (clip / clamp / evaluate) # --------------------------------------------------------------------------- #