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: 3 additions & 1 deletion docs/api/search_and_cross_fitting.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ transforming new data with an all-data model.
A wrapped :class:`~pretab.Preprocessor` must use ``output_structure="matrix"``.
Cross-fitting accepts dense arrays, sparse matrices, and DataFrames as output,
but not dictionaries of feature blocks. Each fold must match the all-data
model's output width and, for DataFrames, its column names and order.
model's output width and, for DataFrames, its column names and order. When the
wrapped estimator provides no ``get_feature_names_out``, the first fold's width
and columns are the reference.

The wrapper's keyword-only ``task_validation`` checks its splitter's configured
task. It does not replace the wrapped estimator's policy. If a later pipeline
Expand Down
4 changes: 3 additions & 1 deletion docs/core_concepts/target_awareness.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,9 @@ otherwise it uses a fresh row index.
configured with `output_structure="blocks"` raises `IncompatibleParamsError`; use
`output_structure="matrix"` instead.
Each fold must return a 2D output with one row per held-out sample, a fixed width, and, for
DataFrames, the same column labels in the same order as the all-data fit.
DataFrames, the same column labels in the same order as the all-data fit. A wrapped estimator
that cannot name its output, such as a `Pipeline` with a `FunctionTransformer` step, is
compared with the first fold instead.

`output_format="dense"` makes block values dense; it does not turn a block dictionary into
a matrix. DeepTab's preprocessing factory requests dense blocks, so a preprocessor built by
Expand Down
32 changes: 26 additions & 6 deletions pretab/core/supervised.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,11 +314,15 @@ def fit_transform(self, X, y=None):
IncompatibleParamsError
If the wrapped transformer returns an unsupported dict of blocks,
or if a fold's output has an invalid shape, a different width, or
DataFrame columns other than the all-data fit's.
DataFrame columns other than the all-data fit's. When the wrapped
transformer provides no ``get_feature_names_out`` (for example a
``Pipeline`` with a ``FunctionTransformer`` step), the first fold's
width and columns are the reference instead.
"""
X_arr, y_arr, receipts = self._fit_full(X, y)
names = list(self.estimator_.get_feature_names_out())
width = len(names)
names = self._all_data_feature_names()
reference = "the all-data fit" if names is not None else "the first fold"
width = len(names) if names is not None else None
blocks, test_indices = [], []
splitter = self._make_splitter()
token = _cross_fit_active.set(True)
Expand All @@ -341,6 +345,8 @@ def fit_transform(self, X, y=None):
f"Cross-fitting received invalid output shape {fold_out.shape}; "
f"expected a 2D output with {len(test_idx)} rows, one per held-out sample."
)
if width is None:
width = fold_out.shape[1]
if fold_out.shape[1] != width:
raise IncompatibleParamsError(
"Cross-fitting requires a fixed output width across folds; expected "
Expand All @@ -352,12 +358,14 @@ def fit_transform(self, X, y=None):
# DataFrames are stacked by column label, so a fold that kept other
# columns at the same width (e.g. other top categories) cannot be aligned.
columns = getattr(fold_out, "columns", None)
if columns is not None and list(columns) != names:
if columns is not None and names is None:
names = list(columns)
elif columns is not None and names is not None and list(columns) != names:
differing = sorted(set(columns).symmetric_difference(names), key=str)
detail = (
f"columns differ from the all-data fit in {differing}"
f"columns differ from {reference} in {differing}"
if differing
else f"column order differs from the all-data fit: expected {names}, got {list(columns)}"
else f"column order differs from {reference}: expected {names}, got {list(columns)}"
)
raise IncompatibleParamsError(
f"Cross-fitting requires the same output columns across folds; a fold's {detail}. The wrapped "
Expand All @@ -370,6 +378,18 @@ def fit_transform(self, X, y=None):
_cross_fit_active.reset(token)
return _stack_folds(blocks, test_indices, X_arr)

def _all_data_feature_names(self) -> list | None:
"""Return the all-data fit's output names, or None when it cannot name them.

A ``Pipeline`` or ``ColumnTransformer`` raises ``AttributeError`` when one of
its steps has no ``get_feature_names_out`` (e.g. a ``FunctionTransformer``
without ``feature_names_out``); cross-fitting then only needs the width.
"""
try:
return list(self.estimator_.get_feature_names_out())
except AttributeError:
return None

def get_feature_names_out(self, input_features=None):
"""Delegate output feature names to the all-data ``estimator_``."""
check_is_fitted(self, "estimator_")
Expand Down
55 changes: 55 additions & 0 deletions tests/core/test_cross_fitted.py
Original file line number Diff line number Diff line change
Expand Up @@ -1694,3 +1694,58 @@ def cross_fit(frame):
expected = cross_fit(X.set_axis(["amount", "flag"], axis=1))
np.testing.assert_allclose(cross_fit(X), expected)
pd.testing.assert_frame_equal(X, original)


def _unnamed_pipeline():
from sklearn.preprocessing import FunctionTransformer

return make_pipeline(FunctionTransformer(np.log1p), PLETransformer(output_dim=5))


def test_fit_transform_works_without_output_feature_names(data):
"""The all-data fit's names were read only for the width and DataFrame columns, so a
Pipeline with a FunctionTransformer (no get_feature_names_out) raised AttributeError."""
X, y = data
X = np.abs(X)
cf = CrossFittedTransformer(_unnamed_pipeline(), n_folds=5, shuffle=True, random_state=0)
with pytest.raises(AttributeError):
cf.fit(X, y).get_feature_names_out()

Xt = cf.fit_transform(X, y)

assert Xt.shape == (X.shape[0], 5)
for train_idx, test_idx in KFold(n_splits=5, shuffle=True, random_state=0).split(X):
fold = _unnamed_pipeline().fit(X[train_idx], y[train_idx])
np.testing.assert_allclose(Xt[test_idx], fold.transform(X[test_idx]))


def test_column_transformer_without_output_feature_names_is_cross_fitted(data):
from sklearn.preprocessing import FunctionTransformer

_, y = data
X = np.random.default_rng(1).uniform(1.0, 5.0, size=(len(y), 2))
wrapped = ColumnTransformer([("ple", PLETransformer(output_dim=4), [0]), ("log", FunctionTransformer(np.log), [1])])
Xt = CrossFittedTransformer(wrapped, n_folds=4, random_state=0).fit_transform(X, y)

assert Xt.shape == (X.shape[0], 5)
np.testing.assert_allclose(Xt[:, 4], np.log(X[:, 1]))


class _FoldDependentWidth(TransformerMixin, BaseEstimator):
"""A transformer without names whose width depends on the rows it is fit on."""

def fit(self, X, y=None):
self.width_ = 2 + int(np.asarray(X)[0, 0] > 0)
return self

def transform(self, X):
return np.zeros((len(X), self.width_))


def test_fold_width_is_still_checked_without_output_feature_names():
# The first fold is fit on rows 6-11 (width 2), the second on rows 0-5 (width 3).
X = np.r_[[[1.0]], -np.ones((5, 1)), -np.ones((6, 1))]
y = np.arange(12, dtype=float)
cf = CrossFittedTransformer(_FoldDependentWidth(), n_folds=2, shuffle=False)
with pytest.raises(IncompatibleParamsError, match="fixed output width"):
cf.fit_transform(X, y)
Loading