diff --git a/docs/core_concepts/configuration.md b/docs/core_concepts/configuration.md index 8fbb584..3e008a7 100644 --- a/docs/core_concepts/configuration.md +++ b/docs/core_concepts/configuration.md @@ -132,7 +132,9 @@ regression and classification differently. | `"adaptive"` | task-dependent | `"int"` | - | `True` | `7` | `15` | `numerical_method` resolves to `"bspline"` when `task="regression"` (the default) and to -`"ple"` when `task="classification"`, for every preset: +`"ple"` when `task="classification"`, for every preset. `task` is matched exactly: any other +value, such as `"Regression"`, raises an `InvalidParamError` from `fit` and +`get_resolved_config()` instead of falling back to the classification preset. ```python standard_regression = Preprocessor(preset="standard", task="regression") @@ -195,7 +197,8 @@ The resolution order is deterministic. Later layers win. ```{warning} Configuration is validated at `fit` time, not silently coerced. An invalid combination, such -as a method that requires the target used with `target_aware=False`, raises a typed error. +as a method that requires the target used with `target_aware=False`, or a `task` other than +`"regression"` / `"classification"`, raises a typed error. This is intentional: it surfaces mistakes early rather than producing a quietly wrong representation. ``` diff --git a/pretab/compose/config.py b/pretab/compose/config.py index a9c5ff2..4408cb2 100644 --- a/pretab/compose/config.py +++ b/pretab/compose/config.py @@ -3,10 +3,10 @@ :class:`PreprocessorConfig` is the frozen, canonical view of the user-supplied Preprocessor parameters. It normalizes the global method names (resolving aliases and separator/case variants, mapping ``None`` to ``"none"``) and -validates the global ``target_aware`` / ``placement_strategy`` contract up front. -The user's original constructor arguments stay untouched on the estimator (as -scikit-learn requires); this object is the internal, normalized counterpart the -composition layer consumes. +validates the global ``target_aware`` / ``placement_strategy`` contract and the +``task`` up front. The user's original constructor arguments stay untouched on +the estimator (as scikit-learn requires); this object is the internal, normalized +counterpart the composition layer consumes. Per-column overrides in ``feature_preprocessing`` are kept verbatim because the namespace they resolve in (numerical vs categorical) depends on the column type, @@ -18,7 +18,7 @@ from dataclasses import dataclass -from ..core.parameters import validate_placement +from ..core.parameters import validate_placement, validate_task from ..exceptions import invalid_param_error from .registry import ( CATEGORICAL_ALIASES, @@ -47,8 +47,8 @@ class PreprocessorConfig: """Frozen, normalized configuration derived from Preprocessor parameters. Built via :meth:`from_params`, which normalizes the global method names and - validates the placement contract. All other knobs are carried through as-is - for the factory and orchestration layers. + validates the placement contract and the task. All other knobs are carried + through as-is for the factory and orchestration layers. """ numerical_method: str @@ -103,9 +103,12 @@ def from_params( ------ InvalidParamError If the ``target_aware`` / ``placement_strategy`` combination is - invalid (via :func:`~pretab.core.parameters.validate_placement`). + invalid (via :func:`~pretab.core.parameters.validate_placement`), or + ``task`` is not ``"regression"`` / ``"classification"`` (via + :func:`~pretab.core.parameters.validate_task`). """ validate_placement(target_aware, placement_strategy) + validate_task(task, "Preprocessor") if missing_policy is not None and missing_policy not in MISSING_POLICIES: raise invalid_param_error( "Preprocessor", diff --git a/pretab/core/parameters.py b/pretab/core/parameters.py index 990183e..6d495a7 100644 --- a/pretab/core/parameters.py +++ b/pretab/core/parameters.py @@ -17,7 +17,8 @@ import warnings from typing import Any, ClassVar -from ..exceptions import InvalidParamError +from ..exceptions import InvalidParamError, invalid_param_error +from ._typing import Task class _Unset: @@ -76,6 +77,50 @@ def validate_placement(target_aware: bool, placement_strategy: str) -> None: raise InvalidParamError("When target_aware=False, placement_strategy must be 'uniform' or 'quantile'.") +#: Supervised tasks accepted by every ``task`` parameter. +TASKS: tuple[Task, ...] = ("regression", "classification") + + +def validate_task(task, estimator: str, *, allow_none: bool = False) -> Task | None: + """Check that ``task`` names a supported supervised task and return it. + + The match is exact, so a near miss such as ``"Regression"`` is rejected + instead of being treated as classification by the target-aware placement. + Like :func:`validate_placement`, this is called at ``fit`` time, not at + construction. + + Parameters + ---------- + task : object + The ``task`` value to check. + estimator : str + Name of the estimator owning the parameter, used in the error message. + allow_none : bool, default=False + Whether ``None`` is accepted (the spline families and location selectors + treat it as ``"regression"``). + + Returns + ------- + {"regression", "classification"} or None + The validated ``task``. + + Raises + ------ + InvalidParamError + If ``task`` is not ``"regression"`` or ``"classification"`` (or ``None`` + when ``allow_none`` is True). + """ + if task is None and allow_none: + return None + if isinstance(task, str) and task in TASKS: + return task + if allow_none: + constraint = "must be 'regression', 'classification', or None (treated as 'regression')" + else: + constraint = "must be 'regression' or 'classification'" + raise invalid_param_error(estimator, "task", task, constraint, valid=TASKS) + + #: Shared parameter names with a short description of what each one controls. CANONICAL_PARAMS: dict[str, str] = { "output_dim": "Number of non-bias output columns produced per input feature.", diff --git a/pretab/core/selectors.py b/pretab/core/selectors.py index f4cef30..484d122 100644 --- a/pretab/core/selectors.py +++ b/pretab/core/selectors.py @@ -27,6 +27,7 @@ from ..exceptions import IncompatibleParamsError, OptionalDependencyError from .knots import quantile_knots, select_knots +from .parameters import validate_task Task = Literal["regression", "classification"] @@ -68,8 +69,8 @@ def select( Input feature values for one feature. y : np.ndarray of shape (n_samples,) Target values. Required -- these selectors are target aware. - task : {"regression", "classification"}, optional - Type of prediction task. Defaults to ``"regression"``. + task : {"regression", "classification"} or None, default="regression" + Type of prediction task. ``None`` is treated as ``"regression"``. min_count : int Minimum number of locations to return. max_count : int @@ -79,10 +80,15 @@ def select( ------- locations : np.ndarray Sorted array of selected locations. + + Raises + ------ + InvalidParamError + If ``task`` is not ``"regression"``, ``"classification"`` or ``None``. """ if y is None: raise IncompatibleParamsError(f"{type(self).__name__} requires y to select locations.") - task = task or "regression" + task = validate_task(task, type(self).__name__, allow_none=True) or "regression" x = np.asarray(x) if x.ndim == 1: @@ -206,20 +212,13 @@ def __init__( self.min_samples_floor = min_samples_split def _ordered_candidates(self, x_valid: np.ndarray, y_valid: np.ndarray, task: Task) -> tuple[list[float], object]: - if task == "regression": - tree = DecisionTreeRegressor( - max_depth=self.max_tree_depth, - min_samples_split=self.min_samples_split, - min_samples_leaf=self.min_samples_leaf, - random_state=self.random_state, - ) - else: - tree = DecisionTreeClassifier( - max_depth=self.max_tree_depth, - min_samples_split=self.min_samples_split, - min_samples_leaf=self.min_samples_leaf, - random_state=self.random_state, - ) + tree_class = DecisionTreeClassifier if task == "classification" else DecisionTreeRegressor + tree = tree_class( + max_depth=self.max_tree_depth, + min_samples_split=self.min_samples_split, + min_samples_leaf=self.min_samples_leaf, + random_state=self.random_state, + ) tree.fit(x_valid, y_valid) split_points = self._extract_split_points(tree, x_valid) @@ -339,8 +338,8 @@ def _ordered_candidates(self, x_valid: np.ndarray, y_valid: np.ndarray, task: Ta lgb = self._import_lightgbm() params = { - "objective": "regression" if task == "regression" else "binary", - "metric": "rmse" if task == "regression" else "binary_logloss", + "objective": "binary" if task == "classification" else "regression", + "metric": "binary_logloss" if task == "classification" else "rmse", "num_leaves": 2**self.max_depth, "max_depth": self.max_depth, "learning_rate": self.learning_rate, diff --git a/pretab/core/supervised.py b/pretab/core/supervised.py index f6aca3b..99132a5 100644 --- a/pretab/core/supervised.py +++ b/pretab/core/supervised.py @@ -30,6 +30,7 @@ PretabDataError, ) from ._typing import TransformerLike +from .parameters import validate_task from .representation import RepresentationSpecMixin __all__ = ["CrossFittedTransformer", "in_controlled_context", "warn_target_leakage"] @@ -139,8 +140,7 @@ def _fit_full(self, X, y): raise IncompatibleParamsError("CrossFittedTransformer requires y at fit time; got y=None.") if not isinstance(self.n_folds, (int, np.integer)) or self.n_folds < 2: raise InvalidParamError(f"n_folds must be an integer >= 2; got {self.n_folds!r}.") - if self.task not in ("regression", "classification"): - raise InvalidParamError(f"task must be 'regression' or 'classification'; got {self.task!r}.") + validate_task(self.task, type(self).__name__) X_arr = np.asarray(X) if X_arr.ndim == 1: X_arr = X_arr.reshape(-1, 1) diff --git a/pretab/encoding/numerical/ple.py b/pretab/encoding/numerical/ple.py index 81a639c..a8b75d0 100644 --- a/pretab/encoding/numerical/ple.py +++ b/pretab/encoding/numerical/ple.py @@ -13,7 +13,7 @@ from sklearn.utils.validation import check_array, check_is_fitted from ...core.adaptive import AdaptiveResolutionMixin -from ...core.parameters import UNSET, AliasResolverMixin +from ...core.parameters import UNSET, AliasResolverMixin, validate_task from ...core.representation import RepresentationSpecMixin from ...core.supervised import warn_target_leakage from ...exceptions import ( @@ -182,8 +182,7 @@ def fit(self, X, y=None): max_bins_req = self._resolve_param("max_output_dim", default=None) min_bins, max_bins = self._resolve_bin_bounds(n_bins, min_bins_req, max_bins_req) - if self.task not in ("regression", "classification"): - raise InvalidParamError(f"Unsupported task: {self.task}. Use 'regression' or 'classification'.") + task = validate_task(self.task, type(self).__name__) if self.placement_strategy not in ("cart", "lightgbm"): raise InvalidParamError( @@ -198,7 +197,7 @@ def fit(self, X, y=None): # exactly ``output_dim`` bins, adaptive clamps it into ``[min, max]``. adapter = PLEPlacementAdapter( placement_strategy=self.placement_strategy, - task=self.task, + task=task, random_state=self.random_state, ) min_thresholds = max(0, min_bins - 1) diff --git a/pretab/expansion/functional/base.py b/pretab/expansion/functional/base.py index 95432f9..bb8a107 100644 --- a/pretab/expansion/functional/base.py +++ b/pretab/expansion/functional/base.py @@ -13,7 +13,7 @@ from sklearn.utils.validation import check_is_fitted from ...core.base import BasePreTabTransformer -from ...core.parameters import UNSET, validate_placement +from ...core.parameters import UNSET, validate_placement, validate_task from ...core.supervised import warn_target_leakage from ...exceptions import ( IncompatibleParamsError, @@ -84,8 +84,7 @@ def fit(self, X, y=None): warn_target_leakage(self, y) placement_strategy = self._resolve_placement_strategy() validate_placement(self.target_aware, placement_strategy) - if self.task not in ("regression", "classification"): - raise InvalidParamError(f"Invalid task. Choose 'regression' or 'classification'. Got {self.task!r}.") + task = validate_task(self.task, type(self).__name__) n_centers = self._resolve_param("output_dim", default=6) min_req = self._resolve_param("min_output_dim", default=None) max_req = self._resolve_param("max_output_dim", default=None) @@ -105,7 +104,7 @@ def fit(self, X, y=None): adapter = RBFPlacementAdapter( target_aware=self.target_aware, placement_strategy=placement_strategy, - task=self.task, + task=task, random_state=self.random_state, ) if self.target_aware and self.adaptive: diff --git a/pretab/expansion/spline/base.py b/pretab/expansion/spline/base.py index ab365bf..1f05f36 100644 --- a/pretab/expansion/spline/base.py +++ b/pretab/expansion/spline/base.py @@ -27,7 +27,7 @@ select_knots, uniform_knots, ) -from ...core.parameters import UNSET, validate_placement +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 ...exceptions import ( @@ -78,7 +78,9 @@ class BaseSplineTransformer(BasePreTabTransformer): evenly across the range, ``"quantile"`` places them at data quantiles. task : {"regression", "classification"} or None, default=None - Task passed to the target-aware selector when ``target_aware=True``. + Task passed to the target-aware selector when ``target_aware=True``. ``None`` is + treated as ``"regression"``; any other value raises + :class:`~pretab.exceptions.InvalidParamError` at ``fit``. adaptive : bool, default=False If True, the per-feature output dimension may vary within @@ -266,6 +268,7 @@ def fit(self, X, y=None): """Determine per-feature knot vectors.""" warn_target_leakage(self, y) validate_placement(self.target_aware, self.placement_strategy) + validate_task(self.task, type(self).__name__, allow_none=True) n_basis = self._resolve_param("output_dim", default=6) min_basis_req = self._resolve_param("min_output_dim", default=None) max_basis_req = self._resolve_param("max_output_dim", default=None) diff --git a/pretab/expansion/spline/cubic_regression.py b/pretab/expansion/spline/cubic_regression.py index 392a99d..70d8c7b 100644 --- a/pretab/expansion/spline/cubic_regression.py +++ b/pretab/expansion/spline/cubic_regression.py @@ -4,7 +4,7 @@ from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import check_is_fitted -from ...core.parameters import UNSET, validate_placement +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 ...exceptions import InvalidParamError @@ -56,7 +56,9 @@ class CubicRegressionSplineTransformer(SplineBasisMixin, TransformerMixin, BaseE across the range, ``"quantile"`` places them at evenly spaced data quantiles. task : {"regression", "classification"} or None, default=None - Task forwarded to the target-aware selector when ``target_aware=True``. + Task forwarded to the target-aware selector when ``target_aware=True``. ``None`` is + treated as ``"regression"``; any other value raises + :class:`~pretab.exceptions.InvalidParamError` at ``fit``. adaptive : bool, default=False If True (with ``target_aware=True``), the per-feature output dimension may @@ -166,6 +168,7 @@ def _bspline_basis(self, x, knots): def fit(self, X, y=None): warn_target_leakage(self, y) validate_placement(self.target_aware, self.placement_strategy) + validate_task(self.task, type(self).__name__, allow_none=True) X = self._validate_allow_nan(X, reset=True) output_dim = self._resolve_param("output_dim", default=6) diff --git a/pretab/expansion/spline/natural_cubic.py b/pretab/expansion/spline/natural_cubic.py index 21c3f45..89309fe 100644 --- a/pretab/expansion/spline/natural_cubic.py +++ b/pretab/expansion/spline/natural_cubic.py @@ -3,7 +3,7 @@ from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import check_is_fitted -from ...core.parameters import UNSET, validate_placement +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 ...exceptions import InvalidParamError @@ -58,7 +58,9 @@ class NaturalCubicSplineTransformer(SplineBasisMixin, TransformerMixin, BaseEsti data quantiles. task : {"regression", "classification"} or None, default=None - Task forwarded to the target-aware selector when ``target_aware=True``. + Task forwarded to the target-aware selector when ``target_aware=True``. ``None`` is + treated as ``"regression"``; any other value raises + :class:`~pretab.exceptions.InvalidParamError` at ``fit``. adaptive : bool, default=False If True (with ``target_aware=True``), the per-feature output dimension may @@ -176,6 +178,7 @@ def d(k): def fit(self, X, y=None): warn_target_leakage(self, y) validate_placement(self.target_aware, self.placement_strategy) + validate_task(self.task, type(self).__name__, allow_none=True) X = self._validate_allow_nan(X, reset=True) output_dim = self._resolve_param("output_dim", default=6) diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index ef44ca8..817ed96 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -34,7 +34,7 @@ ) from .compose.serialize import SCHEMA_VERSION, preprocessor_from_spec, preprocessor_to_spec from .core.logging import configure_logging, get_logger -from .core.parameters import UNSET +from .core.parameters import UNSET, validate_task from .core.policy import RepresentationPolicy, apply_constant_policy from .exceptions import ( ConfigWarning, @@ -81,7 +81,8 @@ def _preset_numerical_method(task) -> str: """Return the preset numerical method for a given ``task``. Splines (``"bspline"``) are the preset default for regression, and piecewise-linear - encoding (``"ple"``) remains the default for classification. + encoding (``"ple"``) remains the default for classification. ``task`` must already + be validated (see :meth:`Preprocessor._resolved_params`). """ return "bspline" if task == "regression" else "ple" @@ -182,7 +183,9 @@ class Preprocessor(TransformerMixin, BaseEstimator): Multivariate tensor-product and thin-plate splines are available as standalone transformers. task : str, default="regression" Supervised task (``"regression"`` or ``"classification"``) used by target-aware methods to - place basis units / knots against ``y``. Only consulted when ``target_aware`` is True. + place basis units / knots against ``y``. Only consulted when ``target_aware`` is True (and + by ``preset`` to pick ``numerical_method``). Matched exactly: any other value, e.g. + ``"Regression"``, raises :class:`~pretab.exceptions.InvalidParamError` at ``fit``. adaptive : bool, default=False Whether adaptive-capable methods size each feature's output dimension from the data (within ``[min_output_dim, max_output_dim]``) instead of using the fixed ``output_dim``. @@ -822,10 +825,17 @@ def _resolved_params(self): back to the preset's value, or to their ordinary default when no preset supplies one. The ``preset`` key is dropped from the returned mapping. + + Raises + ------ + InvalidParamError + If ``task`` or ``preset`` is invalid. ``task`` is validated before a + preset derives ``numerical_method`` from it. """ params = self.get_params(deep=False) preset = params.pop("preset", None) resolved = {key: (_PRESET_PARAM_DEFAULTS[key] if value is UNSET else value) for key, value in params.items()} + validate_task(resolved["task"], type(self).__name__) if preset is None: return resolved if preset not in PRESETS: @@ -857,6 +867,11 @@ def get_resolved_config(self): ------- dict The resolved parameter mapping. + + Raises + ------ + InvalidParamError + If ``task`` or ``preset`` is invalid, exactly as ``fit`` would raise. """ return self._resolved_params() diff --git a/tests/compose/test_config.py b/tests/compose/test_config.py index e3a4c46..657be4f 100644 --- a/tests/compose/test_config.py +++ b/tests/compose/test_config.py @@ -23,6 +23,12 @@ def test_invalid_placement_combo_raises(make_config): make_config(target_aware=False, placement_strategy="cart") +@pytest.mark.parametrize("task", ["Regression", "classif", None]) +def test_invalid_task_raises(make_config, task): + with pytest.raises(InvalidParamError, match=r"Preprocessor\.task = .* is invalid"): + make_config(task=task) + + def test_feature_preprocessing_is_copied(make_config): fp = {"age": "standardization"} cfg = make_config(feature_preprocessing=fp) diff --git a/tests/core/test_location_selectors.py b/tests/core/test_location_selectors.py index e1e6e7f..75353d6 100644 --- a/tests/core/test_location_selectors.py +++ b/tests/core/test_location_selectors.py @@ -6,7 +6,7 @@ CARTLocationSelector, LightGBMLocationSelector, ) -from pretab.exceptions import IncompatibleParamsError +from pretab.exceptions import IncompatibleParamsError, InvalidParamError from pretab.placement.adapters import SplinePlacementAdapter @@ -45,6 +45,23 @@ def test_cart_requires_y(data): CARTLocationSelector().select(X, None, min_count=2, max_count=5) +@pytest.mark.parametrize("selector_cls", [CARTLocationSelector, LightGBMLocationSelector]) +@pytest.mark.parametrize("task", ["Regression", "regresion", "", 1]) +def test_selectors_reject_an_unknown_task(data, selector_cls, task): + """Any task other than "regression" used to fall through to a classifier.""" + X, y = data + with pytest.raises(InvalidParamError, match="task"): + selector_cls().select(X, y, task=task, min_count=2, max_count=10) + + +def test_cart_task_none_means_regression(data): + X, y = data + np.testing.assert_array_equal( + CARTLocationSelector().select(X, y, task=None, min_count=2, max_count=10), + CARTLocationSelector().select(X, y, task="regression", min_count=2, max_count=10), + ) + + def test_cart_reproducible(data): X, y = data a = CARTLocationSelector().select(X, y, min_count=3, max_count=10) diff --git a/tests/encoding/numerical/test_ple_transformer.py b/tests/encoding/numerical/test_ple_transformer.py index e5c7cfa..b50e792 100644 --- a/tests/encoding/numerical/test_ple_transformer.py +++ b/tests/encoding/numerical/test_ple_transformer.py @@ -48,7 +48,7 @@ def test_ple_transformer_multi_feature_shape(X_multi_feature, y_regression): def test_ple_invalid_task_raises(X_single_feature): - with pytest.raises(ValueError, match="Unsupported task"): + with pytest.raises(ValueError, match=r"PLETransformer\.task = 'unsupported' is invalid"): transformer = PLETransformer(task="unsupported") # type: ignore[arg-type] transformer.fit(X_single_feature, np.linspace(0, 1, 10)) diff --git a/tests/expansion/functional/test_rbfexpansion_transformer.py b/tests/expansion/functional/test_rbfexpansion_transformer.py index 2f9028b..9b178d6 100644 --- a/tests/expansion/functional/test_rbfexpansion_transformer.py +++ b/tests/expansion/functional/test_rbfexpansion_transformer.py @@ -55,7 +55,7 @@ def test_rbf_invalid_strategy(): def test_rbf_invalid_task(): - with pytest.raises(ValueError, match="Invalid task"): + with pytest.raises(ValueError, match=r"RBFExpansionTransformer\.task = 'invalid' is invalid"): RBFExpansionTransformer(task="invalid").fit(np.random.rand(5, 1)) diff --git a/tests/expansion/functional/test_reluexpansion_transformer.py b/tests/expansion/functional/test_reluexpansion_transformer.py index 8004c5f..301f78d 100644 --- a/tests/expansion/functional/test_reluexpansion_transformer.py +++ b/tests/expansion/functional/test_reluexpansion_transformer.py @@ -55,7 +55,7 @@ def test_relu_invalid_strategy(): def test_relu_invalid_task(): - with pytest.raises(ValueError, match="Invalid task"): + with pytest.raises(ValueError, match=r"ReLUExpansionTransformer\.task = 'nonsense' is invalid"): ReLUExpansionTransformer(task="nonsense").fit(np.random.rand(5, 1)) diff --git a/tests/expansion/functional/test_sigmoidexpansion_transformer.py b/tests/expansion/functional/test_sigmoidexpansion_transformer.py index 9c21275..c592d72 100644 --- a/tests/expansion/functional/test_sigmoidexpansion_transformer.py +++ b/tests/expansion/functional/test_sigmoidexpansion_transformer.py @@ -58,7 +58,7 @@ def test_sigmoid_invalid_strategy(): def test_sigmoid_invalid_task(): - with pytest.raises(ValueError, match="Invalid task"): + with pytest.raises(ValueError, match=r"SigmoidExpansionTransformer\.task = 'nonsense' is invalid"): SigmoidExpansionTransformer(task="nonsense").fit(np.random.rand(5, 1)) diff --git a/tests/expansion/functional/test_tanh_transformer.py b/tests/expansion/functional/test_tanh_transformer.py index a72e879..7301688 100644 --- a/tests/expansion/functional/test_tanh_transformer.py +++ b/tests/expansion/functional/test_tanh_transformer.py @@ -50,5 +50,5 @@ def test_tanh_invalid_strategy_raises(): def test_tanh_invalid_task_raises(): - with pytest.raises(ValueError, match="Invalid task"): + with pytest.raises(ValueError, match=r"TanhExpansionTransformer\.task = 'invalid' is invalid"): TanhExpansionTransformer(task="invalid").fit(np.random.rand(5, 1)) diff --git a/tests/integration/test_exceptions.py b/tests/integration/test_exceptions.py index d0d0be0..3838bc3 100644 --- a/tests/integration/test_exceptions.py +++ b/tests/integration/test_exceptions.py @@ -15,6 +15,7 @@ from sklearn.exceptions import NotFittedError from pretab import Preprocessor, PretabWarning +from pretab.compose.registry import TRANSFORMER_REGISTRY from pretab.core.adaptive import AdaptiveResolutionMixin from pretab.core.knots import generate_internal_knots from pretab.exceptions import ( @@ -172,10 +173,37 @@ def test_bspline_error_is_catchable_as_pretab_error(xy): def test_ple_unsupported_task(xy): X, y = xy - with pytest.raises(InvalidParamError, match="Unsupported task"): + with pytest.raises(InvalidParamError, match=r"PLETransformer\.task = 'bogus' is invalid"): PLETransformer(output_dim=5, task="bogus").fit(X, y) # type: ignore[arg-type] +# Every registered method that takes a ``task`` parameter. +_TASK_METHODS = sorted(name for name, spec in TRANSFORMER_REGISTRY.items() if "task" in spec.allowed_args) + + +@pytest.mark.parametrize("method", _TASK_METHODS) +def test_unknown_task_raises_at_fit(method): + """A near-miss ``task`` used to switch the knot splines to classification placement.""" + spec = TRANSFORMER_REGISTRY[method] + X = np.linspace(0, 10, 200).reshape(-1, 1) + y = np.round(X[:, 0] ** 2) # integer-valued regression target, so a classifier would also fit + params: dict[str, object] = {"task": "Regression"} + if spec.target_usage == "optional": + params.update(target_aware=True, placement_strategy="cart") + transformer = spec.transformer_cls(**params) # validated at fit, not at construction + with pytest.raises(InvalidParamError, match=rf"{spec.transformer_cls.__name__}\.task = 'Regression' is invalid"): + transformer.fit(X, y) + + +def test_spline_task_none_places_knots_for_regression(xy): + X, y = xy + knots = { + task: BSplineTransformer(target_aware=True, placement_strategy="cart", task=task).fit(X, y).knots_[0] + for task in (None, "regression") + } + np.testing.assert_array_equal(knots[None], knots["regression"]) + + def test_ple_length_mismatch_is_data_error(xy): X, y = xy with pytest.raises(PretabDataError) as exc: @@ -220,6 +248,15 @@ def test_preprocessor_unknown_numerical_method(): assert isinstance(exc.value, ValueError) +@pytest.mark.parametrize("method", ["bspline", "naturalspline", "rbf", "ple", "minmax"]) +def test_preprocessor_unknown_task(method): + """Before, ``task="Regression"`` gave classification knots, or failed deep in scikit-learn.""" + df = pd.DataFrame({"a": np.linspace(0, 10, 200)}) + y = np.sin(df["a"].to_numpy()) + with pytest.raises(InvalidParamError, match=r"Preprocessor\.task = 'Regression' is invalid"): + Preprocessor(numerical_method=method, task="Regression").fit(df, y) + + def test_preprocessor_unknown_categorical_method(): df = pd.DataFrame({"c": ["a", "b", "a", "c"] * 10}) y = np.arange(40) diff --git a/tests/integration/test_presets.py b/tests/integration/test_presets.py index 827e8a3..646d3d8 100644 --- a/tests/integration/test_presets.py +++ b/tests/integration/test_presets.py @@ -96,6 +96,14 @@ def test_invalid_preset_raises(): Preprocessor(preset="nope").get_resolved_config() +@pytest.mark.parametrize("preset", [None, "standard", "expanded", "adaptive"]) +def test_invalid_task_raises_instead_of_resolving(preset): + """``task="Regression"`` used to resolve the classification preset method "ple".""" + pre = Preprocessor(preset=preset, task="Regression") # validated lazily, like fit + with pytest.raises(InvalidParamError, match=r"Preprocessor\.task = 'Regression' is invalid"): + pre.get_resolved_config() + + def test_presets_fit_with_distinct_widths(data): X, y = data widths = {}