From 8cc5120b489f5207d354f702fa81845f70fdae91 Mon Sep 17 00:00:00 2001 From: ChrisW09 <50968720+ChrisW09@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:21:10 +0100 Subject: [PATCH] fix(preprocessor): accept NumPy scalars for cat_cutoff detect_column_types checked cat_cutoff with isinstance(..., float) and isinstance(..., int), so np.int64 (as produced by np.arange in a GridSearchCV grid) and np.float32 raised InvalidParamError, while True was silently read as the count 1. The check also ran only inside the column loop. cat_cutoff is now validated once, before the loop: any numbers.Integral is a unique-count cutoff, any other numbers.Real a unique-ratio cutoff, and bool / np.bool_ are rejected. Fixes #153 --- pretab/compose/feature_detection.py | 37 +++++++++++++++---------- pretab/preprocessor.py | 3 +- tests/compose/test_feature_detection.py | 28 +++++++++++++++++++ tests/integration/test_preprocessor.py | 22 +++++++++++++++ 4 files changed, 75 insertions(+), 15 deletions(-) diff --git a/pretab/compose/feature_detection.py b/pretab/compose/feature_detection.py index 82ca19a..6161f92 100644 --- a/pretab/compose/feature_detection.py +++ b/pretab/compose/feature_detection.py @@ -5,6 +5,7 @@ sequence of delegations rather than inlining the classification heuristic. """ +import numbers from collections import Counter import numpy as np @@ -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 ------- @@ -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( @@ -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) diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index 59879a7..bdfd737 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -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. diff --git a/tests/compose/test_feature_detection.py b/tests/compose/test_feature_detection.py index 2cc3a37..834d03d 100644 --- a/tests/compose/test_feature_detection.py +++ b/tests/compose/test_feature_detection.py @@ -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.""" diff --git a/tests/integration/test_preprocessor.py b/tests/integration/test_preprocessor.py index 2e806be..ec2d582 100644 --- a/tests/integration/test_preprocessor.py +++ b/tests/integration/test_preprocessor.py @@ -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_ == []