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
4 changes: 3 additions & 1 deletion docs/core_concepts/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions pretab/compose/feature_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,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
Expand All @@ -59,7 +61,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

Expand Down
5 changes: 3 additions & 2 deletions pretab/preprocessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -575,7 +575,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).
Expand Down Expand Up @@ -1196,7 +1197,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):
Expand Down
13 changes: 13 additions & 0 deletions tests/compose/test_feature_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions tests/core/test_cross_fitted.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

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