Skip to content

Commit b80f6a8

Browse files
jnothmanlarsmans
authored andcommitted
ENH allow SelectKBest to select all features in a parameter search
1 parent b4b3b1b commit b80f6a8

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

sklearn/feature_selection/tests/test_feature_select.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,18 @@ def test_select_kbest_classif():
189189
assert_array_equal(support, gtruth)
190190

191191

192+
def test_select_kbest_all():
193+
"""
194+
Test whether k="all" correctly returns all features.
195+
"""
196+
X, y = make_classification(n_samples=20, n_features=10,
197+
shuffle=False, random_state=0)
198+
199+
univariate_filter = SelectKBest(f_classif, k='all')
200+
X_r = univariate_filter.fit(X, y).transform(X)
201+
assert_array_equal(X, X_r)
202+
203+
192204
def test_select_fpr_classif():
193205
"""
194206
Test whether the relative univariate feature selection

sklearn/feature_selection/univariate_selection.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -401,8 +401,9 @@ class SelectKBest(_ScoreFilter):
401401
Function taking two arrays X and y, and returning a pair of arrays
402402
(scores, pvalues).
403403
404-
k : int, optional, default=10
404+
k : int or "all", optional, default=10
405405
Number of top features to select.
406+
The "all" option bypasses selection, for use in a parameter search.
406407
407408
Attributes
408409
----------
@@ -425,8 +426,11 @@ def __init__(self, score_func=f_classif, k=10):
425426

426427
def _get_support_mask(self):
427428
k = self.k
429+
if k == 'all':
430+
return np.ones(self.scores_.shape, dtype=bool)
428431
if k > len(self.scores_):
429-
raise ValueError("cannot select %d features among %d"
432+
raise ValueError("Cannot select %d features among %d. "
433+
"Use k='all' to return all features."
430434
% (k, len(self.scores_)))
431435

432436
scores = _clean_nans(self.scores_)

0 commit comments

Comments
 (0)