Skip to content
Merged
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
37 changes: 23 additions & 14 deletions pretab/compose/feature_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
sequence of delegations rather than inlining the classification heuristic.
"""

import numbers
from collections import Counter

import numpy as np
Expand Down Expand Up @@ -126,10 +127,12 @@ def detect_column_types(X, *, cat_cutoff, treat_all_integers_as_numerical, estim
"""Classify each column of ``X`` as numerical or categorical.

An integer column is treated as categorical when its cardinality falls below
``cat_cutoff`` -- interpreted as a unique-ratio cutoff when a float, or an
absolute unique-count cutoff when an int. Non-numeric dtypes, including
``bool`` and pandas' nullable ``boolean``, are always categorical;
``treat_all_integers_as_numerical`` bypasses the heuristic for integer columns.
``cat_cutoff`` -- interpreted as an absolute unique-count cutoff when an
integer, or a unique-ratio cutoff when any other real number. Python and
NumPy scalars are accepted alike; a boolean is not a cutoff and is rejected.
Non-numeric dtypes, including ``bool`` and pandas' nullable ``boolean``, are
always categorical; ``treat_all_integers_as_numerical`` bypasses the
heuristic for integer columns.

Returns
-------
Expand All @@ -140,10 +143,23 @@ def detect_column_types(X, *, cat_cutoff, treat_all_integers_as_numerical, estim

Raises
------
InvalidParamError
If ``cat_cutoff`` is not a real number, or is a boolean.
EmptyDataError
If ``X`` has columns but no rows: a column's kind is decided from its
values, so there is nothing to detect (or to fit) without a sample.
"""
# numbers.Integral / numbers.Real also cover NumPy scalars (np.int64 from
# np.arange in a parameter grid, np.float32); bool is an Integral but no cutoff.
if isinstance(cat_cutoff, (bool, np.bool_)) or not isinstance(cat_cutoff, numbers.Real):
raise invalid_param_error(
estimator_name,
"cat_cutoff",
cat_cutoff,
"must be a float (unique-ratio cutoff) or an int (absolute unique-count cutoff)",
)
count_cutoff = isinstance(cat_cutoff, numbers.Integral)
cutoff = int(cat_cutoff) if count_cutoff else float(cat_cutoff)
X = to_dataframe(X)
if X.shape[0] == 0 and X.shape[1] > 0:
raise EmptyDataError(
Expand All @@ -161,17 +177,10 @@ def detect_column_types(X, *, cat_cutoff, treat_all_integers_as_numerical, estim
if treat_all_integers_as_numerical and X[col].dtype.kind in "iu":
numerical_features.append(col)
else:
if isinstance(cat_cutoff, float):
cutoff_condition = (num_unique_values / total_samples) < cat_cutoff
elif isinstance(cat_cutoff, int):
cutoff_condition = num_unique_values < cat_cutoff
if count_cutoff:
cutoff_condition = num_unique_values < cutoff
else:
raise invalid_param_error(
estimator_name,
"cat_cutoff",
cat_cutoff,
"must be a float (unique-ratio cutoff) or an int (absolute unique-count cutoff)",
)
cutoff_condition = (num_unique_values / total_samples) < cutoff

if X[col].dtype.kind not in "iufc" or (X[col].dtype.kind in "iu" and cutoff_condition):
categorical_features.append(col)
Expand Down
3 changes: 2 additions & 1 deletion pretab/preprocessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,8 @@ class Preprocessor(TransformerMixin, BaseEstimator):
cat_cutoff : float or int, default=0.03
Threshold deciding whether an integer column is treated as categorical. A float is a
unique-ratio cutoff (``n_unique / n_rows < cat_cutoff`` -> categorical); an int is an
absolute unique-count cutoff (``n_unique < cat_cutoff`` -> categorical).
absolute unique-count cutoff (``n_unique < cat_cutoff`` -> categorical). NumPy scalars
such as ``np.int64`` or ``np.float32`` are read the same way; a boolean is rejected.
treat_all_integers_as_numerical : bool, default=False
If True, every integer-typed column is treated as numerical regardless of cardinality,
bypassing the ``cat_cutoff`` heuristic.
Expand Down
28 changes: 28 additions & 0 deletions tests/compose/test_feature_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,34 @@ def test_invalid_cat_cutoff_type_raises():
detect_column_types(df, cat_cutoff="bad", treat_all_integers_as_numerical=False)


@pytest.mark.parametrize(
"cat_cutoff, expected_categorical",
[
(np.int64(4), ["x"]),
(np.int32(2), []),
(np.uint8(4), ["x"]),
(np.float32(0.6), ["x"]),
(np.float16(0.4), []),
],
ids=["int64-count", "int32-count", "uint8-count", "float32-ratio", "float16-ratio"],
)
def test_numpy_scalar_cutoffs_follow_their_python_counterparts(cat_cutoff, expected_categorical):
"""np.int64 (e.g. from np.arange in a parameter grid) was rejected as neither
a float nor an int; NumPy integers count values and NumPy floats are ratios."""
df = pd.DataFrame({"x": [1, 2, 3, 1, 2, 3]}) # 3 unique of 6 -> ratio 0.5
_, categorical = detect_column_types(df, cat_cutoff=cat_cutoff, treat_all_integers_as_numerical=False)
assert categorical == expected_categorical


@pytest.mark.parametrize("cat_cutoff", [True, np.bool_(False), None])
def test_non_numeric_cat_cutoff_raises_even_without_integer_columns(cat_cutoff):
"""A boolean was silently read as the count 1 or 0; validation no longer
depends on the frame containing an integer column."""
df = pd.DataFrame({"f": [0.5, 1.5, 2.5]})
with pytest.raises(InvalidParamError, match="cat_cutoff"):
detect_column_types(df, cat_cutoff=cat_cutoff, treat_all_integers_as_numerical=False)


@pytest.mark.parametrize("cat_cutoff", [0.03, 5])
def test_detect_column_types_rejects_input_without_rows(cat_cutoff):
"""The unique-ratio cutoff divides by the row count; 0 rows raised ZeroDivisionError."""
Expand Down
22 changes: 22 additions & 0 deletions tests/integration/test_preprocessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1168,3 +1168,25 @@ def test_boxcox_survives_cross_validation():
X, y = data[0], data[1]
scores = cross_val_score(make_pipeline(Preprocessor(numerical_method="box-cox"), Ridge()), X, y, cv=5)
assert np.isfinite(scores).all()


def test_grid_search_accepts_numpy_cat_cutoff_values():
"""np.arange yields np.int64 grid values, which fit rejected as neither a float nor an int."""
rng = np.random.default_rng(0)
frame = pd.DataFrame({"num": rng.normal(size=60), "code": rng.integers(0, 6, 60)})
target = frame["num"].to_numpy() + rng.normal(scale=0.1, size=60)
processor = Preprocessor(numerical_method="minmax", target_aware=False, placement_strategy="uniform")
search = GridSearchCV(
Pipeline([("pre", processor), ("model", Ridge())]),
{"pre__cat_cutoff": np.arange(4, 10, 4)},
cv=2,
)
search.set_params(error_score="raise")
search.fit(frame, target)

assert all(isinstance(value, np.integer) for value in search.cv_results_["param_pre__cat_cutoff"])
# 6 distinct codes: categorical below a count cutoff of 8, numerical below 4.
assert search.best_estimator_.named_steps["pre"].cat_cutoff in (4, 8)
fitted = Preprocessor(numerical_method="minmax", target_aware=False, placement_strategy="uniform")
assert fitted.set_params(cat_cutoff=np.int64(8)).fit(frame).categorical_features_ == ["code"]
assert fitted.set_params(cat_cutoff=np.int64(4)).fit(frame).categorical_features_ == []
Loading