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
4 changes: 4 additions & 0 deletions docs/core_concepts/outputs_and_inspection.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,10 @@ pre.set_output(transform="pandas").transform(df)
2 1.000000 1.0 0.0
```

Each DataFrame column keeps its own dtype, as with scikit-learn's `ColumnTransformer`: with
`categorical_method="none"`, the raw categories stay `object` while the numeric columns stay
numeric. The same holds for the dense blocks of `output_structure="blocks"`.

```{warning}
`set_output` always wins. If a downstream step unexpectedly receives a DataFrame instead of
the array or dict you configured, check whether `set_output` was called anywhere upstream
Expand Down
33 changes: 28 additions & 5 deletions pretab/compose/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,28 @@ def _require_polars():
return pl


def _infer_numeric_block(block: np.ndarray) -> np.ndarray:
"""Return an ``object`` block as a numeric array when every column holds numbers.

The stacked output is a single ``object`` array as soon as one block passes raw
categories through (e.g. ``categorical_method="none"``), which would make every
numeric block ``object`` too. A block that still holds strings is returned as is.
"""
if block.dtype != object:
return block
inferred = pd.DataFrame(block).infer_objects()
if all(dtype.kind in "biuf" for dtype in inferred.dtypes):
return inferred.to_numpy()
return block


def to_dataframe_output(array, columns, container, *, index=None):
"""Wrap a dense stacked array in a pandas or polars DataFrame.

Each column gets its own dtype, as in scikit-learn's ``ColumnTransformer``: when
the stacked array is ``object`` (raw categories passed through next to numeric
blocks), the numeric columns are re-inferred instead of staying ``object``.

Parameters
----------
array : numpy.ndarray or scipy.sparse matrix
Expand All @@ -175,10 +194,12 @@ def to_dataframe_output(array, columns, container, *, index=None):
if sp.issparse(array):
array = array.toarray()
if container == "pandas":
import pandas as pd

return pd.DataFrame(array, index=index, columns=pd.Index(columns))
frame = pd.DataFrame(array, index=index, columns=pd.Index(columns))
return frame.infer_objects() if array.dtype == object else frame
pl = _require_polars()
if array.dtype == object:
inferred = pd.DataFrame(array, columns=pd.Index(columns)).infer_objects()
return pl.DataFrame({column: inferred[column].to_numpy() for column in columns})
return pl.from_numpy(array, schema=columns)


Expand All @@ -187,15 +208,17 @@ def build_output_dict(transformed, slices, *, as_sparse=False) -> dict:

``slices`` is an ordered iterable of ``(name, start, width)`` describing each
transformer's contiguous span in the stacked output. When ``as_sparse`` is
True each block is returned as a SciPy CSR matrix.
True each block is returned as a SciPy CSR matrix. A dense numeric block of an
``object`` stacked array (raw categories passed through in another block) is
returned with its numeric dtype.
"""
result = {}
for name, start, width in slices:
block = transformed[:, start : start + width]
if as_sparse:
result[name] = block.tocsr(copy=False) if sp.issparse(block) else sp.csr_matrix(block)
else:
result[name] = block.toarray() if sp.issparse(block) else block
result[name] = block.toarray() if sp.issparse(block) else _infer_numeric_block(block)
return result


Expand Down
57 changes: 57 additions & 0 deletions tests/integration/test_output_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -556,3 +556,60 @@ def test_global_polars_output_config_is_honoured(mixed_frame, fit_before_config)
assert isinstance(out, pl.DataFrame)
assert out.columns == list(pre.get_feature_names_out()) # type: ignore
np.testing.assert_allclose(np.asarray(out), expected)


def _passthrough_frame():
return pd.DataFrame({"age": [21.0, 35.0, 48.0, 52.0, 60.0], "city": ["Oslo", "Lima", "Oslo", "Perth", "Lima"]})


def _passthrough_processor(**kwargs):
return Preprocessor(
numerical_method="bspline",
output_dim=5,
target_aware=False,
placement_strategy="uniform",
categorical_method="none",
**kwargs,
)


def test_pandas_output_keeps_numeric_dtypes_next_to_passed_through_categories():
"""The stacked array is object as soon as raw categories pass through, and every
pandas column was object too: select_dtypes("number") found nothing."""
frame = _passthrough_frame()
pre = _passthrough_processor().fit(frame)
out = pre.set_output(transform="pandas").transform(frame)

numeric = [name for name in out.columns if name.startswith("num_")]
assert list(out.select_dtypes("number").columns) == numeric
assert out["cat_city"].dtype == object
assert out["cat_city"].tolist() == frame["city"].tolist()
expected = pre.set_output(transform="default").transform(frame, return_array=True)
np.testing.assert_allclose(out[numeric].to_numpy(), expected[:, : len(numeric)].astype(float))


def test_polars_output_keeps_numeric_dtypes_next_to_passed_through_categories():
pl = pytest.importorskip("polars")
frame = _passthrough_frame()
out = _passthrough_processor().fit(frame).set_output(transform="polars").transform(frame)

assert all(out.schema[name] == pl.Float64 for name in out.columns if name.startswith("num_"))
assert out.schema["cat_city"] == pl.String
assert out["num_age_bs0"].mean() is not None


def test_dense_blocks_keep_numeric_dtypes_next_to_passed_through_categories():
frame = _passthrough_frame()
blocks = _passthrough_processor(output_structure="blocks").fit(frame).transform(frame)

assert blocks["num_age"].dtype == np.float64
assert blocks["cat_city"].dtype == object


@pytest.mark.parametrize("dtype", [None, np.float32])
def test_numeric_outputs_keep_their_dtype(dtype):
frame = _passthrough_frame()[["age"]]
pre = _passthrough_processor(dtype=dtype, output_structure="blocks").fit(frame)
expected = np.dtype(dtype or np.float64)
assert pre.transform(frame)["num_age"].dtype == expected
assert set(pre.set_output(transform="pandas").transform(frame).dtypes) == {expected}
Loading