Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/core_concepts/resolution_and_placement.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 11 additions & 2 deletions pretab/core/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand Down
54 changes: 54 additions & 0 deletions tests/core/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading