diff --git a/docs/core_concepts/target_awareness.md b/docs/core_concepts/target_awareness.md index 9b393e0..0f8c2d4 100644 --- a/docs/core_concepts/target_awareness.md +++ b/docs/core_concepts/target_awareness.md @@ -34,7 +34,8 @@ multi-output `y` of shape `(n_samples, k)` with `k > 1` raises `IncompatiblePara `ple` and for an `optional` method with `target_aware=True`; a column vector of shape `(n_samples, 1)` counts as a single target. With `target_aware=False` the `optional` methods ignore `y`, so they also fit inside a multi-output pipeline. Explicit spline -`knot_locations` also ignore `y`, because no target-aware selector runs. +`knot_locations` also ignore `y`, because no target-aware selector runs. A `y` whose length +differs from the number of rows of `X` raises `PretabDataError` for every target-aware fit. ## The fitted-usage flag diff --git a/pretab/core/selectors.py b/pretab/core/selectors.py index 7e61a59..4d6cb28 100644 --- a/pretab/core/selectors.py +++ b/pretab/core/selectors.py @@ -30,7 +30,7 @@ from ..exceptions import IncompatibleParamsError, OptionalDependencyError from .knots import quantile_knots, select_knots, uniform_knots from .parameters import validate_task -from .validation import single_target +from .validation import check_target_length, single_target Task = Literal["regression", "classification"] @@ -110,6 +110,7 @@ def select( if x.ndim == 1: x = x.reshape(-1, 1) y = single_target(y, type(self).__name__) + check_target_length(len(x), y, type(self).__name__) # Only float targets can carry NaN; for integer / object (e.g. string # class label) targets, leave the target validation to the fitted model. diff --git a/pretab/core/validation.py b/pretab/core/validation.py index 68ee5cc..4c87bbd 100644 --- a/pretab/core/validation.py +++ b/pretab/core/validation.py @@ -42,6 +42,34 @@ def resolve_input_features(estimator, input_features) -> list: return [str(name) for name in names] +def check_target_length(n_samples: int, y, estimator: str) -> None: + """Raise :class:`~pretab.exceptions.PretabDataError` unless ``y`` has one row per sample. + + Target-aware placement pairs each value of ``X`` with its target, so a target of + another length cannot be aligned with the input rows. + + Parameters + ---------- + n_samples : int + Number of rows of ``X``. + y : array-like + Target values. + estimator : str + Class name used in the error message. + + Raises + ------ + PretabDataError + If ``y`` does not have ``n_samples`` rows. + """ + n_targets = len(y) + if n_targets != n_samples: + raise PretabDataError( + f"{estimator}: X and y must have same length. Got {n_samples} and {n_targets}; target-aware " + "placement pairs every row of X with its target." + ) + + def single_target(y, estimator: str, *, fix: str | None = None) -> np.ndarray: """Return the target that target-aware placement fits on, as a 1D array. diff --git a/pretab/expansion/functional/base.py b/pretab/expansion/functional/base.py index 80c7d69..b02a72d 100644 --- a/pretab/expansion/functional/base.py +++ b/pretab/expansion/functional/base.py @@ -15,6 +15,7 @@ from ...core.base import BasePreTabTransformer from ...core.parameters import UNSET, validate_placement, validate_task from ...core.supervised import warn_target_leakage +from ...core.validation import check_target_length from ...exceptions import ( IncompatibleParamsError, InvalidParamError, @@ -95,6 +96,8 @@ def fit(self, X, y=None): if self.target_aware and y is None: raise IncompatibleParamsError("Target variable 'y' must be provided when target_aware=True.") + if self.target_aware: + check_target_length(X.shape[0], y, type(self).__name__) # Centers come from the placement subsystem: a target-aware selector # (CART / LightGBM) when ``target_aware``, otherwise quantile / uniform diff --git a/pretab/expansion/spline/base.py b/pretab/expansion/spline/base.py index 73424cc..e218063 100644 --- a/pretab/expansion/spline/base.py +++ b/pretab/expansion/spline/base.py @@ -30,7 +30,7 @@ from ...core.parameters import UNSET, validate_placement, validate_task from ...core.policy import RepresentationPolicy, resolve_out_of_range from ...core.supervised import warn_target_leakage -from ...core.validation import resolve_input_features +from ...core.validation import check_target_length, resolve_input_features from ...exceptions import ( DataWarning, InvalidParamError, @@ -326,7 +326,27 @@ def _validate_knot_locations(self) -> None: ) def fit(self, X, y=None): - """Determine per-feature knot vectors.""" + """Determine per-feature knot vectors. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. Missing values are skipped when placing the knots. + y : array-like of shape (n_samples,), default=None + Target values, read only by target-aware knot placement + (``target_aware=True`` without ``knot_locations``). + + Returns + ------- + self : object + Fitted transformer. + + Raises + ------ + PretabDataError + If a feature is entirely missing or has zero range, or if target-aware + placement gets a ``y`` whose length differs from the number of rows. + """ warn_target_leakage(self, y) validate_placement(self.target_aware, self.placement_strategy) validate_task(self.task, type(self).__name__, allow_none=True) @@ -361,6 +381,8 @@ def fit(self, X, y=None): # paths ignore it, so any target shape (e.g. multi-output) can pass through # a Pipeline. For the selector, y is sliced by rows like X, not flattened. y_arr = None if y is None or selector is None else np.asarray(y) + if y_arr is not None: + check_target_length(X.shape[0], y_arr, type(self).__name__) self.knots_ = [] for i in range(X.shape[1]): diff --git a/pretab/expansion/spline/mixins.py b/pretab/expansion/spline/mixins.py index c8abc75..b638c62 100644 --- a/pretab/expansion/spline/mixins.py +++ b/pretab/expansion/spline/mixins.py @@ -18,7 +18,7 @@ from ...core.base import BasePreTabTransformer from ...core.knots import generate_internal_knots, select_knots, spanning_knots, supplement_interior_knots -from ...core.validation import resolve_input_features +from ...core.validation import check_target_length, resolve_input_features from ...exceptions import IncompatibleParamsError, PretabDataError, PretabNotFittedError, invalid_param_error from .penalty import PenaltySpec @@ -153,6 +153,10 @@ def _place_spanning_knots(self, x, y, n_basis, strategy, selector, task, min_int adaptive selector path) the number of interior knots is clamped into that window before bracketing. """ + if selector is None: + y = None # only the target-aware selector reads y + elif y is not None: + check_target_length(len(x), y, type(self).__name__) x, y = self._finite_column(x, y) x_min, x_max = x.min(), x.max() if selector is not None: @@ -185,6 +189,10 @@ def _place_interior_knots(self, x, y, n_interior, strategy, selector, task, min_ :func:`pretab.core.knots.generate_internal_knots` and made unique and strictly interior (see :func:`pretab.core.knots.supplement_interior_knots`). """ + if selector is None: + y = None # only the target-aware selector reads y + elif y is not None: + check_target_length(len(x), y, type(self).__name__) x, y = self._finite_column(x, y) if selector is not None: if y is None: diff --git a/tests/core/test_location_selectors.py b/tests/core/test_location_selectors.py index ef0e93c..6f93add 100644 --- a/tests/core/test_location_selectors.py +++ b/tests/core/test_location_selectors.py @@ -331,3 +331,11 @@ def test_lightgbm_zero_split_sentinel_maps_to_the_bin_midpoint(): # The 0-vs-positive split is reported by LightGBM as threshold 1e-35. assert 0.5 in locations assert (np.abs(locations) > 1e-30).all() + + +def test_selector_rejects_a_target_of_another_length(): + from pretab.exceptions import PretabDataError + + x = np.linspace(0.0, 1.0, 100).reshape(-1, 1) + with pytest.raises(PretabDataError, match=r"CARTLocationSelector: X and y must have same length. Got 100 and 60"): + CARTLocationSelector().select(x, np.zeros(60), min_count=2, max_count=4) diff --git a/tests/expansion/spline/test_spline_expansions.py b/tests/expansion/spline/test_spline_expansions.py index 57110eb..60be368 100644 --- a/tests/expansion/spline/test_spline_expansions.py +++ b/tests/expansion/spline/test_spline_expansions.py @@ -9,6 +9,10 @@ ISplineTransformer, MSplineTransformer, NaturalCubicSplineTransformer, + RBFExpansionTransformer, + ReLUExpansionTransformer, + SigmoidExpansionTransformer, + TanhExpansionTransformer, ) @@ -549,3 +553,44 @@ def test_explicit_knots_size_metadata_penalties_and_missing_blocks_per_feature(c np.testing.assert_array_equal(missing_out[:, offset], 1.0) np.testing.assert_array_equal(penalty[0], 0.0) offset += size + + +_TARGET_AWARE = { + "bspline": lambda **kw: BSplineTransformer(output_dim=5, **kw), + "mspline": lambda **kw: MSplineTransformer(output_dim=5, **kw), + "ispline": lambda **kw: ISplineTransformer(output_dim=5, **kw), + "naturalspline": lambda **kw: NaturalCubicSplineTransformer(output_dim=5, **kw), + "cubicspline": lambda **kw: CubicRegressionSplineTransformer(output_dim=5, **kw), + "rbf": lambda **kw: RBFExpansionTransformer(output_dim=5, **kw), + "relu": lambda **kw: ReLUExpansionTransformer(output_dim=5, **kw), + "sigmoid": lambda **kw: SigmoidExpansionTransformer(output_dim=5, **kw), + "tanh": lambda **kw: TanhExpansionTransformer(output_dim=5, **kw), +} + + +@pytest.mark.parametrize("family", list(_TARGET_AWARE)) +@pytest.mark.parametrize("n_targets", [60, 120]) +def test_target_aware_fit_rejects_a_target_of_another_length(family, n_targets): + """A y of the wrong length failed with a raw IndexError (B/M/I) or a NumPy broadcast + ValueError naming no estimator; PLE already raised PretabDataError.""" + from pretab.exceptions import PretabDataError + + rng = np.random.default_rng(0) + X = rng.normal(size=(100, 1)) + y = rng.normal(size=n_targets) + transformer = _TARGET_AWARE[family](target_aware=True, placement_strategy="cart") + with pytest.raises(PretabDataError, match=rf"{type(transformer).__name__}: X and y must have same length"): + transformer.fit(X, y) + + +@pytest.mark.parametrize("family", list(_TARGET_AWARE)) +def test_unsupervised_fit_ignores_the_length_of_y(family): + """Only the target-aware selector reads y; with a missing value the natural and + cubic-regression splines still aligned an unused y and raised IndexError.""" + rng = np.random.default_rng(0) + X = rng.normal(size=(100, 1)) + X[3, 0] = np.nan + reference = _TARGET_AWARE[family](target_aware=False, placement_strategy="uniform").fit(X) + fitted = _TARGET_AWARE[family](target_aware=False, placement_strategy="uniform").fit(X, rng.normal(size=60)) + probe = np.linspace(-1.0, 1.0, 7).reshape(-1, 1) + np.testing.assert_array_equal(fitted.transform(probe), reference.transform(probe))