8000 [MRG] FIX ColumnTransformer: raise error on reordered columns with remainder by schuderer · Pull Request #14237 · scikit-learn/scikit-learn · GitHub
[go: up one dir, main page]

Skip to content

[MRG] FIX ColumnTransformer: raise error on reordered columns with remainder #14237

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
Show all changes
19 commits
Select commit Hold shift + click to select a range
6cfc722
FIX Raise error on reordered columns in ColumnTransformer with remainder
schuderer Jul 2, 2019
d06b27a
FIX Check for different length of X.columns to avoid exception
schuderer Jul 2, 2019
16cef75
FIX linter, line too long
schuderer Jul 2, 2019
4feb366
Merge remote-tracking branch 'upstream/master' into coltrans_fix_rema…
schuderer Jul 3, 2019
6421cb1
FIX import _check_key_type from its new location utils
schuderer Jul 3, 2019
8d2a18d
Merge remote-tracking branch 'upstream/master' into coltrans_fix_rema…
schuderer Jul 5, 2019
d709be1
ENH Adjust doc, allow added columns
schuderer Jul 5, 2019
096b58d
Merge remote-tracking branch 'upstream/master' into coltrans_fix_rema…
schuderer Jul 5, 2019
8bfc3ce
Fix comment typo as suggested, remove non-essential exposition in doc
schuderer Jul 7, 2019
d4ae600
Merge remote-tracking branch 'upstream/master' into coltrans_fix_rema…
schuderer Jul 7, 2019
47b645d
Add PR 14237 to what's new
schuderer Jul 7, 2019
39360de
Merge remote-tracking branch 'upstream/master' into coltrans_fix_rema…
schuderer Jul 9, 2019
3b404d8
Avoid AttributeError in favor of ValueError "column names only for DF"
schuderer Jul 9, 2019
011a2a2
ENH Add check for n_features_ for array-likes and DataFrames
schuderer Jul 10, 2019
c61143c
Rename self.n_features to self._n_features
schuderer Jul 10, 2019
5f0b92b
Replaced backslash line continuation with parenthesis
schuderer Jul 11, 2019
d8e1fc0
Merge remote-tracking branch 'upstream/master' into coltrans_fix_rema…
schuderer Jul 11, 2019
e1434c2
Merge remote-tracking branch 'upstream/master' into coltrans_fix_rema…
schuderer Jul 13, 2019
6c28e4d
Style changes
schuderer Jul 13, 2019
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
9 changes: 9 additions & 0 deletions doc/whats_new/v0.21.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ Changelog
``tol`` required too strict types. :pr:`14092` by
:user:`Jérémie du Boisberranger <jeremiedbb>`.

:mod:`sklearn.compose`
.....................

- |Fix| Fixed an issue in :class:`compose.ColumnTransformer` where using
DataFrames whose column order differs between :func:``fit`` and
:func:``transform`` could lead to silently passing incorrect columns to the
``remainder`` transformer.
:pr:`14237` by `Andreas Schuderer <schuderer>`.

.. _changes_0_21_2:

Version 0.21.2
Expand Down
34 changes: 31 additions & 3 deletions sklearn/compose/_column_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from ..utils import Bunch
from ..utils import safe_indexing
from ..utils import _get_column_indices
from ..utils import _check_key_type
from ..utils.metaestimators import _BaseComposition
from ..utils.validation import check_array, check_is_fitted

Expand Down Expand Up @@ -80,6 +81,8 @@ class ColumnTransformer(_BaseComposition, TransformerMixin):
By setting ``remainder`` to be an estimator, the remaining
non-specified columns will use the ``remainder`` estimator. The
estimator must support :term:`fit` and :term:`transform`.
Note that using this feature requires that the DataFrame columns
input at :term:`fit` and :term:`transform` have identical order.

sparse_threshold : float, default = 0.3
If the output of the different transformers contains sparse matrices,
Expand Down Expand Up @@ -303,11 +306,17 @@ def _validate_remainder(self, X):
"'passthrough', or estimator. '%s' was passed instead" %
self.remainder)

n_columns = X.shape[1]
# Make it possible to check for reordered named columns on transform
if (hasattr(X, 'columns') and
any(_check_key_type(cols, str) for cols in self._columns)):
self._df_columns = X.columns

self._n_features = X.shape[1]
cols = []
for columns in self._columns:
cols.extend(_get_column_indices(X, columns))
remaining_idx = sorted(list(set(range(n_columns)) - set(cols))) or None
remaining_idx = list(set(range(self._n_features)) - set(cols))
remaining_idx = sorted(remaining_idx) or None

self._remainder = ('remainder', self.remainder, remaining_idx)

Expand Down Expand Up @@ -508,8 +517,27 @@ def transform(self, X):

"""
check_is_fitted(self, 'transformers_')

X = _check_X(X)

if self._n_features > X.shape[1]:
raise ValueError('Number of features of the input must be equal '
'to or greater than that of the fitted '
'transformer. Transformer n_features is {0} '
'and input n_features is {1}.'
.format(self._n_features, X.shape[1]))

# No column reordering allowed for named cols combined with remainder
if (self._remainder[2] is not None and
hasattr(self, '_df_columns') and
hasattr(X, 'columns')):
n_cols_fit = len(self._df_columns)
n_cols_transform = len(X.columns)
Copy link
Member
@thomasjpfan thomasjpfan Jul 7, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will raise an error if X is a numpy array. Check if X is a pandas array before heading into this path?

In future PR, we can use _df_columns to signal that X was a dataframe during fit and raise an error, if during transform X is not a dataframe.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A good point, @thomasjpfan

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks! Duck-typing check ok?

if self._remainder[2] is not None and hasattr(self, '_df_columns') and hasattr(X, 'columns'):

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, though ideally we should also be checking the number of columns when X is not a DataFrame. Not sure if that needs to be in this pull request

Copy link
Contributor Author
@schuderer schuderer Jul 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

8000

Interpreting the last suggestion loosely, I looked into also checking column order for structured numpy arrays (np arrays with named columns) in an analogous way as now for DataFrames and I found that this would change the PR a lot. ColumnTransformer currently explicitly does not allow named columns for non-DataFrames and raises an error if one tries. I now think that this was not the intended suggestion, but wanted to clearly state my (maybe misguided) interpretations. If this train of thought is relevant, we can continue this discussion in RFC #14251.

When reading the suggestion literally, i.e. only checking the number of columns for non-DataFrames -- this condition is only in the code originally to avoid an exception when referencing X.columns. If this check is a goal of the PR itself, I can change the conditionals (and it would become a somewhat separate check with a separate error message as _df_columns only exists for DataFrames combined with column names). I can gladly do this if it's found useful.

For now, I'll only commit the suggested code change from my previous comment (plus test assertion), but that does not mean that I wouldn't do the other one at all. I'll wait for a yay or nay on the numpy-num-of-cols-check. :)

Copy link
Contributor Author
@schuderer schuderer Jul 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PS to the commit: Note that when passing an np array to transform, an error will still be raised -- not here, but in the correct location (ColumnTransformer checks if named columns are used with non-DataFrames and raises a ValueError if this is not the case).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We explicitly decided not to support struct arrays. The proposal here was to make sure we continue to allow fitting on DataFrame and transforming on numpy array, if that is currently supported.

The check for the number of columns in an array is because we provide that security in every other estimator, raising an error if the input has changed shape. Here it is also applicable but not currently done. It's not really necessary for this pull request

Copy link
Contributor Author
@schuderer schuderer Jul 10, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @jnothman! I interpret your last sentence as you leaving it for me to decide. :)

I added a general self.n_features_ check in analogy to the one here

if self.n_features_ != X.shape[1]:
but tweaked it to allow for added columns (as discussed above). I expanded the tests to be explicit about accepting more columns and rejecting fewer columns.

Referencing relevant PR #13603 as ColumnTransformer now also has n_features_

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but tweaked it to allow for added columns (as discussed above)

Things get a little hairy here. I feel like for numpy arrays we should not be that lenient, since they are arrays not columnar frames...

But I can accept this for the version 0.20-21 fix.

Referencing relevant PR #13603 as ColumnTransformer now also has n_features_

Similarly, since I'm trying to include this in a patch release, make this _n_features to keep the patch API compatible. This also avoids making more deprecation work in #13603 or subsequent to it.

Copy link
Contributor Author
@schuderer schuderer Jul 10, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but tweaked it to allow for added columns (as discussed above)

Things get a little hairy here. I feel like for numpy arrays we should not be that lenient, since they are arrays not columnar frames...

But I can accept this for the version 0.20-21 fix.

Ok, if it is acceptable as it is for this fix, I'm leaving it unchanged (both arrays as well as DFs are checked leniently, accepting added columns, but not removed columns). That way I'm also confident that this PR doesn't break any relied-on behavior. Looking forward to other PRs like #14251 and #13603 for helping in making checks more obvious for first-time contributors like me (and users, of course). I found this PR to be quite the unexpected rabbit hole: every time I thought I understood how the pieces work together, there was still more to discover. :D I learned a lot, though. 👍 Hope than this PR is still a net win for the maintainers regarding time spent vs contribution, despite the communication overhead and my occasional chattiness.

Referencing relevant PR #13603 as ColumnTransformer now also has n_features_

Similarly, since I'm trying to include this in a patch release, make this _n_features to keep the patch API compatible. This also avoids making more deprecation work in #13603 or subsequent to it.

I see, thanks! I renamed it to _n_features. This is the only change in the latest commit.

if (n_cols_transform >= n_cols_fit and
any(X.columns[:n_cols_fit] != self._df_columns)):
raise ValueError('Column ordering must be equal for fit '
'and for transform when using the '
'remainder keyword')

Xs = self._fit_transform(X, None, _transform_one, fitted=True)
self._validate_output(Xs)

Expand Down
48 changes: 48 additions & 0 deletions sklearn/compose/tests/test_column_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,17 @@ def test_column_transformer_invalid_columns(remainder):
assert_raise_message(ValueError, "Specifying the columns",
ct.fit, X_array)

# transformed n_features does not match fitted n_features
col = [0, 1]
ct = ColumnTransformer([('trans', Trans(), col)], remainder=remainder)
ct.fit(X_array)
X_array_more = np.array([[0, 1, 2], [2, 4, 6], [3, 6, 9]]).T
ct.transform(X_array_more) # Should accept added columns
X_array_fewer = np.array([[0, 1, 2], ]).T
err_msg = 'Number of features'
with pytest.raises(ValueError, match=err_msg):
ct.transform(X_array_fewer)


def test_column_transformer_invalid_transformer():

Expand Down Expand Up @@ -1060,3 +1071,40 @@ def test_column_transformer_negative_column_indexes():
tf_1 = ColumnTransformer([('ohe', ohe, [-1])], remainder='passthrough')
tf_2 = ColumnTransformer([('ohe', ohe, [2])], remainder='passthrough')
assert_array_equal(tf_1.fit_transform(X), tf_2.fit_transform(X))


@pytest.mark.parametrize("explicit_colname", ['first', 'second'])
def test_column_transformer_reordered_column_names_remainder(explicit_colname):
"""Regression test for issue #14223: 'Named col indexing fails with
ColumnTransformer remainder on changing DataFrame column ordering'

Should raise error on changed order combined with remainder.
Should allow for added columns in `transform` input DataFrame
as long as all preceding columns match.
"""
pd = pytest.importorskip('pandas')

X_fit_array = np.array([[0, 1, 2], [2, 4, 6]]).T
X_fit_df = pd.DataFrame(X_fit_array, columns=['first', 'second'])

X_trans_array = np.array([[2, 4, 6], [0, 1, 2]]).T
X_trans_df = pd.DataFrame(X_trans_array, columns=['second', 'first'])

tf = ColumnTransformer([('bycol', Trans(), explicit_colname)],
remainder=Trans())

tf.fit(X_fit_df)
err_msg = 'Column ordering must be equal'
with pytest.raises(ValueError, match=err_msg):
tf.transform(X_trans_df)

# No error for added columns if ordering is identical
X_extended_df = X_fit_df.copy()
X_extended_df['third'] = [3, 6, 9]
tf.transform(X_extended_df) # No error should be raised

# No 'columns' AttributeError when transform input is a numpy array
X_array = X_fit_array.copy()
err_msg = 'Specifying the columns'
with pytest.raises(ValueError, match=err_msg):
tf.transform(X_array)
0