Skip to content

FIX Error for sparse matrix in OrdinalEncoder.inverse_transform #19879

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 3 commits into from
Apr 13, 2021
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: 4 additions & 0 deletions doc/whats_new/v1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,10 @@ Changelog
`handle_unknown='ignore'` and dropping categories. :pr:`19041` by
`Thomas Fan`_.

- |Fix| :meth:`preprocessing.OrdinalEncoder.inverse_transform` is not
supporting sparse matrix and raise the appropriate error message.
:pr:`19879` by :user:`Guillaume Lemaitre <glemaitre>`.

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

Expand Down
4 changes: 2 additions & 2 deletions sklearn/preprocessing/_encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -846,7 +846,7 @@ def inverse_transform(self, X):

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
X : array-like of shape (n_samples, n_encoded_features)
The transformed data.

Returns
Expand All @@ -855,7 +855,7 @@ def inverse_transform(self, X):
Inverse transformed array.
"""
check_is_fitted(self)
X = check_array(X, accept_sparse='csr', force_all_finite='allow-nan')
X = check_array(X, force_all_finite='allow-nan')

n_samples, _ = X.shape
n_features = len(self.categories_)
Expand Down
22 changes: 22 additions & 0 deletions sklearn/preprocessing/tests/test_encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -1110,3 +1110,25 @@ def test_ordinal_encoder_handle_missing_and_unknown(
assert_allclose(X_trans, expected_X_trans)

assert_allclose(oe.transform(X_test), [[-1.0]])


def test_ordinal_encoder_sparse():
"""Check that we raise proper error with sparse input in OrdinalEncoder.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/19878
"""
X = np.array([[3, 2, 1], [0, 1, 1]])
X_sparse = sparse.csr_matrix(X)

encoder = OrdinalEncoder()

err_msg = "A sparse matrix was passed, but dense data is required"
with pytest.raises(TypeError, match=err_msg):
encoder.fit(X_sparse)
with pytest.raises(TypeError, match=err_msg):
encoder.fit_transform(X_sparse)

X_trans = encoder.fit_transform(X)
X_trans_sparse = sparse.csr_matrix(X_trans)
with pytest.raises(TypeError, match=err_msg):
encoder.inverse_transform(X_trans_sparse)