Skip to content

[WIP] FrequencyEncoder #11805

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
wants to merge 2 commits into from
Closed
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
34 changes: 34 additions & 0 deletions sklearn/preprocessing/label.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
# Hamzeh Alsalhi <ha258@cornell.edu>
# License: BSD 3 clause

from collections import Counter
from collections import defaultdict
import itertools
import array
Expand Down Expand Up @@ -283,6 +284,39 @@ def inverse_transform(self, y):
return self.classes_[y]


class FrequencyEncoder(BaseEstimator, TransformerMixin):
"""If a value appears n times in data sent to fit, it is encoded as n."""

def fit(self, y):
"""Fit frequency encoder

Parameters
----------
y : array-like of shape (n_samples,)
Target values.

Returns
-------
self : returns an instance of self.
"""
y = column_or_1d(y, warn=True)
self._counts = Counter(y)
return self

def transform(self, y):
"""Transform labels to frequency encoding.
Parameters
----------
y : array-like of shape [n_samples]
Target values.

Returns
-------
y : array-like of shape [n_samples]
"""
return np.array([self._counts[v] for v in y])


class LabelBinarizer(BaseEstimator, TransformerMixin):
"""Binarize labels in a one-vs-all fashion

Expand Down