-
-
Notifications
You must be signed in to change notification settings - Fork 25.8k
[WIP] "other"/min_freq in OneHot and OrdinalEncoder #12264
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
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,6 +9,7 @@ | |
|
||
import numpy as np | ||
from scipy import sparse | ||
from collections import Counter | ||
|
||
from .. import get_config as _get_config | ||
from ..base import BaseEstimator, TransformerMixin | ||
|
@@ -73,13 +74,15 @@ def _fit(self, X, handle_unknown='error'): | |
if len(self._categories) != n_features: | ||
raise ValueError("Shape mismatch: if n_values is an array," | ||
" it has to be of shape (n_features,).") | ||
|
||
self.groups_ = [] | ||
self.categories_ = [] | ||
|
||
for i in range(n_features): | ||
Xi = X[:, i] | ||
if self._categories == 'auto': | ||
Xi, group = _group_values(Xi.copy(), min_freq=self.min_freq) | ||
cats = _encode(Xi) | ||
self.groups_.append(group) | ||
else: | ||
cats = np.array(self._categories[i], dtype=X.dtype) | ||
if self.handle_unknown == 'error': | ||
|
@@ -99,6 +102,10 @@ def _transform(self, X, handle_unknown='error'): | |
|
||
for i in range(n_features): | ||
Xi = X[:, i] | ||
try: | ||
Xi, _ = _group_values(Xi, group=self.groups_[i]) | ||
except IndexError: | ||
pass | ||
diff, valid_mask = _encode_check_unknown(Xi, self.categories_[i], | ||
return_mask=True) | ||
|
||
|
@@ -198,6 +205,9 @@ class OneHotEncoder(_BaseEncoder): | |
0.20 and will be removed in 0.22. | ||
You can use the ``ColumnTransformer`` instead. | ||
|
||
min_freq: float, default=0 | ||
group low frequent categories together | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. be more specific, please. This should describe what the parameter is. |
||
|
||
Attributes | ||
---------- | ||
categories_ : list of arrays | ||
|
@@ -272,13 +282,14 @@ class OneHotEncoder(_BaseEncoder): | |
|
||
def __init__(self, n_values=None, categorical_features=None, | ||
categories=None, sparse=True, dtype=np.float64, | ||
handle_unknown='error'): | ||
min_freq=0, handle_unknown='error'): | ||
self.categories = categories | ||
self.sparse = sparse | ||
self.dtype = dtype | ||
self.handle_unknown = handle_unknown | ||
self.n_values = n_values | ||
self.categorical_features = categorical_features | ||
self.min_freq = min_freq | ||
|
||
# Deprecated attributes | ||
|
||
|
@@ -759,9 +770,10 @@ class OrdinalEncoder(_BaseEncoder): | |
between 0 and n_classes-1. | ||
""" | ||
|
||
def __init__(self, categories='auto', dtype=np.float64): | ||
def __init__(self, categories='auto', dtype=np.float64, min_freq=0): | ||
self.categories = categories | ||
self.dtype = dtype | ||
self.min_freq = min_freq | ||
|
||
def fit(self, X, y=None): | ||
"""Fit the OrdinalEncoder to X. | ||
|
@@ -835,3 +847,46 @@ def inverse_transform(self, X): | |
X_tr[:, i] = self.categories_[i][labels] | ||
|
||
return X_tr | ||
|
||
|
||
def _group_values_python(values, min_freq=0, group=None): | ||
if min_freq and group: | ||
raise ValueError | ||
if min_freq: | ||
freqs = {key: counts/len(values) | ||
for key, counts in Counter(values).items()} | ||
low_freq_keys = (key for key, freq in freqs.items() if freq < min_freq) | ||
# sorting ensures first element in group is always the same | ||
group = np.array(sorted(set(low_freq_keys)), dtype=values.dtype) | ||
if group is not None: | ||
try: | ||
values[np.isin(values, group)] = group[0] | ||
except IndexError: | ||
pass | ||
return values, group | ||
else: | ||
return values, group | ||
|
||
|
||
def _group_values_numpy(values, min_freq=0, group=None): | ||
if min_freq and group: | ||
raise ValueError | ||
if min_freq: | ||
uniques, counts = np.unique(values, return_counts=True) | ||
mask = (counts/len(values) < min_freq) | ||
group = uniques[mask] | ||
if group is not None: | ||
try: | ||
values[np.isin(values, group)] = group[0] | ||
except IndexError: | ||
pass | ||
return values, group | ||
else: | ||
return values, None | ||
|
||
|
||
def _group_values(values, min_freq=0, group=None): | ||
if values.dtype == object: | ||
return _group_values_python(values, min_freq, group) | ||
else: | ||
return _group_values_numpy(values, min_freq, group) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
space before colon, please