From 0ca83cc5117d8b65e99986b8e8c419ca9eaadba1 Mon Sep 17 00:00:00 2001 From: ChrisW09 <50968720+ChrisW09@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:31:45 +0100 Subject: [PATCH] fix(preprocessor): re-infer object array columns at fit to_dataframe wrapped an object ndarray (df.to_numpy() of mixed data, or the output of SimpleImputer on a mixed frame) with every column as object, so fit detected numeric columns as categorical and one-hot or ordinal encoded each distinct number. transform already called infer_objects() for arrays, so fit and transform disagreed. to_dataframe now re-infers the columns of input without labels, which covers fit, the feature-group validation and the task preflight as well as transform; _align_input no longer repeats it. Labelled frames keep their dtypes. Fixes #155 --- docs/core_concepts/configuration.md | 4 +- pretab/compose/feature_detection.py | 9 ++++- pretab/preprocessor.py | 5 ++- tests/compose/test_feature_detection.py | 13 +++++++ tests/core/test_cross_fitted.py | 10 ++++- tests/integration/test_preprocessor.py | 50 +++++++++++++++++++++++++ 6 files changed, 84 insertions(+), 7 deletions(-) diff --git a/docs/core_concepts/configuration.md b/docs/core_concepts/configuration.md index a22feb3..4119e03 100644 --- a/docs/core_concepts/configuration.md +++ b/docs/core_concepts/configuration.md @@ -40,7 +40,9 @@ or inference uses a positional input, keep column order and width consistent. `Preprocessor` also accepts a plain `numpy.ndarray`, not just a `DataFrame`. Columns are named `feature_0`, `feature_1`, ... in position order, then detected as numerical or -categorical exactly as they would be for a `DataFrame`. +categorical exactly as they would be for a `DataFrame`. The columns of an object array, such +as `df.to_numpy()` of mixed data or the output of `SimpleImputer(strategy="most_frequent")`, +are re-inferred first, so a column that holds only numbers stays numerical. ```python import numpy as np diff --git a/pretab/compose/feature_detection.py b/pretab/compose/feature_detection.py index 82ca19a..83536ff 100644 --- a/pretab/compose/feature_detection.py +++ b/pretab/compose/feature_detection.py @@ -31,7 +31,9 @@ def to_dataframe(X, *, copy: bool = False) -> pd.DataFrame: Dicts are wrapped in a fresh DataFrame and a polars DataFrame is converted to one with the same column names, order and (as far as possible) dtypes. Input without column labels -- a NumPy array, a list of rows -- is read as a 2D - array. An existing pandas DataFrame is returned as-is, or copied when + array, and the columns of an object array are re-inferred, so a column that + holds only numbers (such as ``df.to_numpy()`` of mixed data) gets a numeric + dtype. An existing pandas DataFrame is returned as-is, or copied when ``copy`` is True. Raises @@ -58,7 +60,10 @@ def to_dataframe(X, *, copy: bool = False) -> pd.DataFrame: f"Expected 2D input (a DataFrame or a 2D array), got an array with {X.ndim} dimension(s).\n" "Fix: reshape a single feature to one column, e.g. X.reshape(-1, 1)." ) - X = pd.DataFrame(X, columns=pd.Index([f"feature_{i}" for i in range(X.shape[1])])) + # An object array (df.to_numpy() of mixed data, an upstream imputer) holds every + # column as object; infer_objects gives numeric columns their numeric dtype, so + # fit detects the same column types as for the DataFrame and as transform. + X = pd.DataFrame(X, columns=pd.Index([f"feature_{i}" for i in range(X.shape[1])])).infer_objects() else: X = X.copy() if copy else X diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index 59879a7..580897f 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -574,7 +574,8 @@ def fit(self, X, y=None, embeddings=None): X : pandas.DataFrame, polars.DataFrame, numpy.ndarray, or dict The input features. A polars frame is converted to pandas with the same column names, order and dtypes (no ``pyarrow`` needed); an array (or a list of rows) has - its columns named ``feature_0``, ``feature_1``, .... + its columns named ``feature_0``, ``feature_1``, ...., and the numeric columns of + an object array are re-inferred before the column types are detected. A frame or dict is matched by column name, an array (or a list of rows) by position. y : array-like, default=None Target values (used for decision tree-based methods). @@ -1195,7 +1196,7 @@ def _align_input(self, X): ) if fitted_labels is not None and list(X.columns) != list(fitted_labels): X = X.set_axis(list(fitted_labels), axis=1) - return X.infer_objects() if is_array else X + return X @staticmethod def _column_transformer_input(X): diff --git a/tests/compose/test_feature_detection.py b/tests/compose/test_feature_detection.py index 2cc3a37..293e84d 100644 --- a/tests/compose/test_feature_detection.py +++ b/tests/compose/test_feature_detection.py @@ -23,6 +23,19 @@ def test_to_dataframe_wraps_dict(): assert list(df.columns) == ["a", "b"] +def test_to_dataframe_reinfers_the_columns_of_an_object_array(): + X = np.array([[1.5, "a", 3], [2.5, "b", 4]], dtype=object) + df = to_dataframe(X) + assert df["feature_0"].dtype == np.float64 + assert df["feature_1"].dtype == object + assert df["feature_2"].dtype.kind == "i" + + +def test_to_dataframe_keeps_the_dtypes_of_a_labelled_frame(): + frame = pd.DataFrame({"a": pd.Series([1.5, 2.5], dtype=object)}) + assert to_dataframe(frame)["a"].dtype == object + + def test_to_dataframe_returns_same_object_without_copy(): df = pd.DataFrame({"a": [1, 2]}) assert to_dataframe(df) is df diff --git a/tests/core/test_cross_fitted.py b/tests/core/test_cross_fitted.py index e73741e..14ef5b5 100644 --- a/tests/core/test_cross_fitted.py +++ b/tests/core/test_cross_fitted.py @@ -237,8 +237,14 @@ def test_fit_transform_keeps_strings_left_unchanged(object_array): from pretab import Preprocessor X, y = object_array - cross_fitted, out = _cross_fit(Preprocessor(categorical_method=None, random_state=0), X, y) - + # The float column of the object array is detected as numerical and passed + # through unchanged as well, so the whole output equals the input. + processor = Preprocessor(categorical_method=None, numerical_method="none", scaling="none", random_state=0) + cross_fitted, out = _cross_fit(processor, X, y) + fitted = cast(Preprocessor, cross_fitted.estimator_) + + assert fitted.numerical_features_ == ["feature_0"] + assert fitted.categorical_features_ == ["feature_1"] assert out.dtype == cross_fitted.transform(X).dtype == object np.testing.assert_array_equal(out, X) diff --git a/tests/integration/test_preprocessor.py b/tests/integration/test_preprocessor.py index 2e806be..a7be499 100644 --- a/tests/integration/test_preprocessor.py +++ b/tests/integration/test_preprocessor.py @@ -883,6 +883,56 @@ def test_a_list_of_rows_is_read_like_an_array(): np.testing.assert_allclose(np.asarray(pre.transform(rows)), np.asarray(pre.transform(np.asarray(rows)))) +def _mixed_frame(): + rng = np.random.default_rng(0) + frame = pd.DataFrame( + { + "age": rng.uniform(18, 70, 60).round(1), + "rooms": rng.integers(1, 40, 60), + "city": rng.choice(["Oslo", "Lima", "Perth"], 60), + } + ) + return frame, frame["age"].to_numpy() / 10 + rng.normal(size=60) + + +def _mixed_processor(): + return Preprocessor(numerical_method="minmax", categorical_method="one-hot") + + +def test_object_array_fit_detects_the_column_types_of_the_frame(): + """fit read every column of an object array (df.to_numpy() of mixed data) as + categorical, one-hot encoding each distinct number, while transform re-inferred + the numeric columns.""" + frame, y = _mixed_frame() + X = frame.to_numpy() + assert X.dtype == object + + from_frame = _mixed_processor().fit(frame, y) + from_array = _mixed_processor().fit(X, y) + + assert from_array.numerical_features_ == ["feature_0", "feature_1"] + assert from_array.categorical_features_ == ["feature_2"] + assert from_array.output_dims_ == dict( + zip(["feature_0", "feature_1", "feature_2"], from_frame.output_dims_.values(), strict=True) + ) + np.testing.assert_allclose( + np.asarray(from_array.transform(X), dtype=float), np.asarray(from_frame.transform(frame), dtype=float) + ) + + +def test_imputed_mixed_frame_keeps_its_numerical_columns(): + """SimpleImputer(strategy="most_frequent") returns an object array for mixed data.""" + frame, y = _mixed_frame() + frame.loc[3, "city"] = np.nan + pipe = Pipeline([("impute", SimpleImputer(strategy="most_frequent")), ("pre", _mixed_processor())]) + + pre = pipe.fit(frame, y).named_steps["pre"] + + assert pre.numerical_features_ == ["feature_0", "feature_1"] + assert pre.categorical_features_ == ["feature_2"] + assert pre.total_output_dim_ == 2 + 3 + + def test_a_list_of_rows_is_matched_by_position_after_a_frame_fit(named_numeric): frame, y = named_numeric pre = Preprocessor(numerical_method="minmax").fit(frame, y)