From 249b81ece6f9ba36e30aab19a8e133a116bf4d1e Mon Sep 17 00:00:00 2001 From: ChrisW09 <50968720+ChrisW09@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:43:19 +0100 Subject: [PATCH] fix(validation): check task consistency for a polars Series target _validate_task_target inspected only NumPy, pandas, list and tuple targets, so with a polars Series y the task_validation diagnostic was skipped in Preprocessor, CrossFittedTransformer and RepresentationSearchCV: "warn" reported nothing and "raise" let scikit-learn's own error surface instead of InvalidParamError. A polars Series, detected without importing polars, is now inspected through its NumPy values. Fixes #181 --- .../core_concepts/resolution_and_placement.md | 3 ++ pretab/core/validation.py | 13 ++++- tests/core/test_validation.py | 54 +++++++++++++++++++ 3 files changed, 68 insertions(+), 2 deletions(-) diff --git a/docs/core_concepts/resolution_and_placement.md b/docs/core_concepts/resolution_and_placement.md index 1685600..42a8a8f 100644 --- a/docs/core_concepts/resolution_and_placement.md +++ b/docs/core_concepts/resolution_and_placement.md @@ -136,6 +136,9 @@ Use `task_validation` to catch a clear mismatch before fitting the target-aware - `"raise"` stops the fit with `InvalidParamError`. Use it when a clear mismatch should fail the pipeline. +The check reads a NumPy array, a list, a pandas Series or DataFrame column, or a polars +Series. It skips targets it cannot classify unambiguously, such as ones with missing values. + For example, a classifier for sale status should receive class labels, not sale prices: ```python diff --git a/pretab/core/validation.py b/pretab/core/validation.py index 68ee5cc..ca23586 100644 --- a/pretab/core/validation.py +++ b/pretab/core/validation.py @@ -10,7 +10,7 @@ import warnings from contextlib import contextmanager from contextvars import ContextVar -from typing import Literal, cast +from typing import Any, Literal, cast import numpy as np import pandas as pd @@ -148,8 +148,11 @@ def _validate_task_target( """Diagnose clear mismatches for a validated task, mode and target-consuming role. Inspect only supported single-output targets. The caller retains ownership - of target validation and passes the original target on to fitting. + of target validation and passes the original target on to fitting. A polars + Series is inspected through its NumPy values. """ + if _is_polars_series(y): + y = cast(Any, y).to_numpy() if mode == "off" or not isinstance(y, (np.ndarray, pd.Series, pd.DataFrame, pd.Index, list, tuple)): return try: @@ -202,6 +205,12 @@ def _validate_task_target( warnings.warn(f"{estimator}: {detail}; {fix}.", ConfigWarning, stacklevel=2) +def _is_polars_series(y) -> bool: + """Return True if ``y`` is a polars Series, without importing polars.""" + polars = sys.modules.get("polars") + return polars is not None and isinstance(y, polars.Series) + + def is_polars_frame(X) -> bool: """Return True if ``X`` is a polars DataFrame, without importing polars. diff --git a/tests/core/test_validation.py b/tests/core/test_validation.py index bed4650..b119cbe 100644 --- a/tests/core/test_validation.py +++ b/tests/core/test_validation.py @@ -97,3 +97,57 @@ def unexpected_inspection(target): monkeypatch.setattr(validation, "type_of_target", unexpected_inspection) validation._validate_task_target(target, task="classification", mode=mode, estimator="Example", role="placement") + + +@pytest.mark.parametrize( + ("values", "task", "observed"), + [ + pytest.param([0.1, 1.25, 3.5], "classification", "continuous", id="continuous"), + pytest.param(["private-a", "private-b", "private-a"], "regression", "binary", id="binary-text"), + ], +) +@pytest.mark.parametrize("mode", ["warn", "raise"]) +def test_task_target_inspects_a_polars_series(values, task, observed, mode): + """A polars Series was not in the inspected container types, so the diagnostic + and the warning never fired and scikit-learn's own error surfaced instead.""" + pl = pytest.importorskip("polars") + target = pl.Series(values) + suggested = "regression" if task == "classification" else "classification" + match = rf"(?s)Example.*placement.*task='{task}'.*'{observed}'.*task='{suggested}'" + + def inspect_target(): + validation._validate_task_target(target, task=task, mode=mode, estimator="Example", role="placement") + + if mode == "warn": + with pytest.warns(ConfigWarning, match=match): + inspect_target() + else: + with pytest.raises(InvalidParamError, match=match): + inspect_target() + assert target.to_list() == values + + +@pytest.mark.parametrize("values", [[0, 1, 0], [True, False, True], [0.1, None, 3.5]], ids=["binary", "bool", "null"]) +def test_task_target_leaves_consistent_or_missing_polars_targets_quiet(values): + pl = pytest.importorskip("polars") + with warnings.catch_warnings(): + warnings.simplefilter("error") + validation._validate_task_target( + pl.Series(values), task="classification", mode="raise", estimator="Example", role="placement" + ) + + +def test_preprocessor_task_validation_applies_to_a_polars_target(): + pl = pytest.importorskip("polars") + from pretab import CrossFittedTransformer, Preprocessor + + X = pd.DataFrame({"views": np.arange(32.0)}) + price = pl.Series(np.linspace(120_000.25, 450_000.75, 32)) + pre = Preprocessor(numerical_method="rbf", output_dim=3, task="classification", task_validation="raise") + with pytest.raises(InvalidParamError, match="'continuous'"): + pre.fit(X, price) + cross_fitted = CrossFittedTransformer( + Preprocessor(numerical_method="minmax"), n_folds=3, task="classification", task_validation="raise" + ) + with pytest.raises(InvalidParamError, match="'continuous'"): + cross_fitted.fit_transform(X, price)