Skip to content

FIX Adds more informative error message for OHE #26931

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
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
7 changes: 7 additions & 0 deletions doc/whats_new/v1.4.rst
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,13 @@ Changelog
metric parameter `p` is in the range `0 < p < 1`, regardless of the `dtype` of `X`.
:pr:`26760` by :user:`Shreesha Kumar Bhat <Shreesha3112>`.

:mod:`sklearn.preprocessing`
............................

- |Fix| :class:`preprocessing.OneHotEncoder` shows a more informative error message
when `sparse_output=True` and the output is configured to be pandas.
:pr:`26931` by `Thomas Fan`_.

:mod:`sklearn.tree`
...................

Expand Down
9 changes: 9 additions & 0 deletions sklearn/preprocessing/_encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from ..utils._encode import _check_unknown, _encode, _get_counts, _unique
from ..utils._mask import _get_mask
from ..utils._param_validation import Hidden, Interval, RealNotInt, StrOptions
from ..utils._set_output import _get_output_config
from ..utils.validation import _check_feature_names_in, check_is_fitted

__all__ = ["OneHotEncoder", "OrdinalEncoder"]
Expand Down Expand Up @@ -1008,6 +1009,14 @@ def transform(self, X):
returned.
"""
check_is_fitted(self)
transform_output = _get_output_config("transform", estimator=self)["dense"]
if transform_output == "pandas" and self.sparse_output:
raise ValueError(
"Pandas output does not support sparse data. Set sparse_output=False to"
" output pandas DataFrames or disable pandas output via"
' `ohe.set_output(transform="default").'
)

# validation of X happens in _check_X called by _transform
warn_on_unknown = self.drop is not None and self.handle_unknown in {
"ignore",
Expand Down
20 changes: 20 additions & 0 deletions sklearn/preprocessing/tests/test_encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -1588,6 +1588,26 @@ def test_ohe_drop_first_explicit_categories(handle_unknown):
assert_allclose(X_trans, X_expected)


def test_ohe_more_informative_error_message():
"""Raise informative error message when pandas output and sparse_output=True."""
pd = pytest.importorskip("pandas")
df = pd.DataFrame({"a": [1, 2, 3], "b": ["z", "b", "b"]}, columns=["a", "b"])

ohe = OneHotEncoder(sparse_output=True)
ohe.set_output(transform="pandas")

msg = (
"Pandas output does not support sparse data. Set "
"sparse_output=False to output pandas DataFrames or disable pandas output"
)
with pytest.raises(ValueError, match=msg):
ohe.fit_transform(df)

ohe.fit(df)
with pytest.raises(ValueError, match=msg):
ohe.transform(df)


def test_ordinal_encoder_passthrough_missing_values_float_errors_dtype():
"""Test ordinal encoder with nan passthrough fails when dtype=np.int32."""

Expand Down
4 changes: 2 additions & 2 deletions sklearn/utils/estimator_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -4587,7 +4587,7 @@ def check_set_output_transform_pandas(name, transformer_orig):
outputs_pandas = _output_from_fit_transform(transformer_pandas, name, X, df, y)
except ValueError as e:
# transformer does not support sparse data
assert str(e) == "Pandas output does not support sparse data.", e
assert "Pandas output does not support sparse data." in str(e), e
return

for case in outputs_default:
Expand Down Expand Up @@ -4633,7 +4633,7 @@ def check_global_output_transform_pandas(name, transformer_orig):
)
except ValueError as e:
# transformer does not support sparse data
assert str(e) == "Pandas output does not support sparse data.", e
assert "Pandas output does not support sparse data." in str(e), e
return

for case in outputs_default:
Expand Down