Skip to content

[32161] Added frequency option to ordinaryEncoder - #33702

Draft
vulkomilev wants to merge 3 commits into
scikit-learn:mainfrom
valkomilev:main
Draft

vulkomilev wants to merge 3 commits into
scikit-learn:mainfrom
valkomilev:main

Conversation

@vulkomilev

@vulkomilev vulkomilev commented Apr 6, 2026 •

Copy link
Copy Markdown

Reference Issues/PRs

closes #32161

What does this implement/fix? Explain your changes.

I have added an option for encoding of the inputs based on their frequency instead of their alphabetical order

AI usage disclosure

None

Any other comments?

No

@github-actions github-actions Bot added module:preprocessing CI:Linter failure The linter CI is failing on this PR labels Apr 6, 2026
@github-actions

github-actions Bot commented Apr 6, 2026 •

Copy link
Copy Markdown

❌ Linting issues

This PR is introducing linting issues. Here's a summary of the issues. Note that you can avoid having linting issues by enabling pre-commit hooks. Instructions to enable them can be found here.

You can see the details of the linting issues under the lint job here


ruff check

ruff detected issues. Please run ruff check --fix --output-format=full locally, fix the remaining issues, and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.12.2.

Details

sklearn/preprocessing/_encoders.py:181:1: W293 [*] Blank line contains whitespace
    |
180 |             self.categories_.append(cats)
181 |         
    | ^^^^^^^^ W293
182 |         output = {"n_samples": n_samples}
183 |         if return_counts:
    |
    = help: Remove whitespace from blank line

sklearn/preprocessing/tests/test_encoders.py:212:1: W293 [*] Blank line contains whitespace
    |
211 | def test_frequency_same():
212 |     
    | ^^^^ W293
213 |     enc = OrdinalEncoder(
214 |         handle_unknown="use_encoded_value",categories='frequency', unknown_value=-2
    |
    = help: Remove whitespace from blank line

sklearn/preprocessing/tests/test_encoders.py:255:1: W293 [*] Blank line contains whitespace
    |
253 |         ], dtype="int64",
254 |     )
255 |     
    | ^^^^ W293
256 |     assert_array_equal(X_trans_enc, exp)
257 |     X_trans_inv = enc.inverse_transform(X_trans_enc)
    |
    = help: Remove whitespace from blank line

sklearn/preprocessing/tests/test_encoders.py:274:1: W293 [*] Blank line contains whitespace
    |
273 | def test_diferent_order():
274 |     
    | ^^^^ W293
275 |     enc = OrdinalEncoder(
276 |         handle_unknown="use_encoded_value", categories="frequency", unknown_value=-2
    |
    = help: Remove whitespace from blank line

sklearn/preprocessing/tests/test_encoders.py:293:1: W293 [*] Blank line contains whitespace
    |
291 |     X_trans_enc = enc.transform(X_trans)
292 |     X_trans_enc_second = enc_second.transform(X_trans_second)
293 |     
    | ^^^^ W293
294 |     assert_array_equal(X_trans_enc_second, X_trans_enc)
    |
    = help: Remove whitespace from blank line

sklearn/preprocessing/tests/test_encoders.py:769:89: E501 Line too long (90 > 88)
    |
767 | #test bunch of ties for frequency
768 | # test for no ties
769 | #encoder  dont encode in any particular order . it has auto of alphabetical OrdinalEncoder
    |                                                                                         ^^ E501
770 | #after this this encoding is fed to the fit functions
771 | #we have to test if the fit is behaiving normally with the new encoding which will be ordered. 
    |

sklearn/preprocessing/tests/test_encoders.py:771:89: E501 Line too long (95 > 88)
    |
769 | #encoder  dont encode in any particular order . it has auto of alphabetical OrdinalEncoder
770 | #after this this encoding is fed to the fit functions
771 | #we have to test if the fit is behaiving normally with the new encoding which will be ordered. 
    |                                                                                         ^^^^^^^ E501
772 | def test_ordinal_encoder_frequency():
    |

sklearn/preprocessing/tests/test_encoders.py:771:95: W291 [*] Trailing whitespace
    |
769 | #encoder  dont encode in any particular order . it has auto of alphabetical OrdinalEncoder
770 | #after this this encoding is fed to the fit functions
771 | #we have to test if the fit is behaiving normally with the new encoding which will be ordered. 
    |                                                                                               ^ W291
772 | def test_ordinal_encoder_frequency():
    |
    = help: Remove trailing whitespace

sklearn/preprocessing/tests/test_encoders.py:773:1: W293 [*] Blank line contains whitespace
    |
771 | #we have to test if the fit is behaiving normally with the new encoding which will be ordered. 
772 | def test_ordinal_encoder_frequency():
773 |     
    | ^^^^ W293
774 |     enc = OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-2)
775 |     X_fit = np.array([["a", "x"], ["b", "y"], ["c", "z"]], dtype=object)
    |
    = help: Remove whitespace from blank line

Found 9 errors.
[*] 7 fixable with the `--fix` option.

ruff format

ruff detected issues. Please run ruff format locally and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.12.2.

Details

--- sklearn/preprocessing/_encoders.py
+++ sklearn/preprocessing/_encoders.py
@@ -178,7 +178,7 @@
                     category_counts.append(_get_counts(Xi, cats))
 
             self.categories_.append(cats)
-        
+
         output = {"n_samples": n_samples}
         if return_counts:
             output["category_counts"] = category_counts

--- sklearn/preprocessing/tests/test_encoders.py
+++ sklearn/preprocessing/tests/test_encoders.py
@@ -208,10 +208,10 @@
     with pytest.raises(TypeError, match=err_msg):
         enc.get_feature_names_out()
 
+
 def test_frequency_same():
-    
     enc = OrdinalEncoder(
-        handle_unknown="use_encoded_value",categories='frequency', unknown_value=-2
+        handle_unknown="use_encoded_value", categories="frequency", unknown_value=-2
     )
 
     X_fit = np.array(
@@ -222,7 +222,7 @@
             ["a", "x"],
             ["b", "y"],
             ["b", "y"],
-            ["a", "z"]
+            ["a", "z"],
         ],
         dtype=object,
     )
@@ -234,7 +234,7 @@
             ["a", "x"],
             ["b", "x"],
             ["b", "x"],
-            ["b", "x"]
+            ["b", "x"],
         ],
         dtype=object,
     )
@@ -243,16 +243,17 @@
     X_trans_enc = enc.transform(X_trans)
     exp = np.array(
         [
-            [ 0.0, -2.0],
-            [-2.0,  1.0],
-            [ 0.0,  0.0],
-            [ 0.0,  0.0],
-            [ 1.0,  0.0],
-            [ 1.0,  0.0],
-            [ 1.0,  0.0]
-        ], dtype="int64",
+            [0.0, -2.0],
+            [-2.0, 1.0],
+            [0.0, 0.0],
+            [0.0, 0.0],
+            [1.0, 0.0],
+            [1.0, 0.0],
+            [1.0, 0.0],
+        ],
+        dtype="int64",
     )
-    
+
     assert_array_equal(X_trans_enc, exp)
     X_trans_inv = enc.inverse_transform(X_trans_enc)
     inv_exp = np.array(
@@ -263,15 +264,15 @@
             ["a", "x"],
             ["b", "x"],
             ["b", "x"],
-            ["b" ,"x"]
+            ["b", "x"],
         ],
         dtype=object,
     )
 
     assert_array_equal(X_trans_inv, inv_exp)
 
+
 def test_diferent_order():
-    
     enc = OrdinalEncoder(
         handle_unknown="use_encoded_value", categories="frequency", unknown_value=-2
     )
@@ -280,7 +281,7 @@
     )
 
     X_fit = np.array(
-        [["a", "x"],["a", "x"], ["b", "y"], ["b", "y"], ["c", "z"]], dtype=object
+        [["a", "x"], ["a", "x"], ["b", "y"], ["b", "y"], ["c", "z"]], dtype=object
     )
 
     X_trans = np.array([["c", "xy"], ["bla", "y"], ["a", "x"]], dtype=object)
@@ -290,9 +291,10 @@
 
     X_trans_enc = enc.transform(X_trans)
     X_trans_enc_second = enc_second.transform(X_trans_second)
-    
+
     assert_array_equal(X_trans_enc_second, X_trans_enc)
 
+
 def test_one_hot_encoder_set_params():
     X = np.array([[1, 2]]).T
     oh = OneHotEncoder()
@@ -764,13 +766,13 @@
     with pytest.raises(ValueError, match=msg):
         enc.inverse_transform(X_tr)
 
-#test bunch of ties for frequency
+
+# test bunch of ties for frequency
 # test for no ties
-#encoder  dont encode in any particular order . it has auto of alphabetical OrdinalEncoder
-#after this this encoding is fed to the fit functions
-#we have to test if the fit is behaiving normally with the new encoding which will be ordered. 
+# encoder  dont encode in any particular order . it has auto of alphabetical OrdinalEncoder
+# after this this encoding is fed to the fit functions
+# we have to test if the fit is behaiving normally with the new encoding which will be ordered.
 def test_ordinal_encoder_frequency():
-    
     enc = OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-2)
     X_fit = np.array([["a", "x"], ["b", "y"], ["c", "z"]], dtype=object)
     X_trans = np.array([["c", "xy"], ["bla", "y"], ["a", "x"]], dtype=object)
@@ -784,6 +786,7 @@
     inv_exp = np.array([["c", None], [None, "y"], ["a", "x"]], dtype=object)
     assert_array_equal(X_trans_inv, inv_exp)
 
+
 def test_ordinal_encoder_handle_unknowns_string():
     enc = OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-2)
     X_fit = np.array([["a", "x"], ["b", "y"], ["c", "z"]], dtype=object)

2 files would be reformatted, 930 files already formatted

Generated for commit: 38d8da8. Link to the linter CI: here

Comment thread sklearn/preprocessing/_encoders.py Outdated
cats = result
elif self.categories == "frequency":
for element in Xi:
if hash(element) not in list(X_list_dict.keys()):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The hash is unnecessary imo, but maybe open to being convinced if there's an example you're thinking of that requires that.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Hashing removed

Comment thread sklearn/preprocessing/_encoders.py Outdated
for element in Xi:
if hash(element) not in list(X_list_dict.keys()):
X_list_dict[hash(element)] = []
X_list_dict[hash(element)].append(element)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is maintaining a dictionary of lists? Why do you need the list? Wouldn't this be:

input: 'x', 'x', 'x', 'y'
X_list_dict = {
   hash(x): [x, x, x],
   hash(y): [y]
}

?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Hashing removed

with pytest.raises(TypeError, match=err_msg):
enc.get_feature_names_out()

def test_frequency_same():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Name should be more explicit. Perhaps

test_ordinal_encoding_when_frequency_is_same_

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A concise descriptive docstring for the unt-tests are also nice to have.


assert_array_equal(X_trans_inv, inv_exp)

def test_diferent_order():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same here

#encoder dont encode in any particular order . it has auto of alphabetical OrdinalEncoder
#after this this encoding is fed to the fit functions
#we have to test if the fit is behaiving normally with the new encoding which will be ordered.
def test_ordinal_encoder_frequency():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same

@@ -170,7 +178,7 @@
category_counts.append(_get_counts(Xi, cats))

self.categories_.append(cats)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Unnecessary diff

@@ -182,7 +190,6 @@
# `nan` values can only be placed in the latest position
missing_indices[feature_idx] = categories_for_idx.size - 1
output["missing_indices"] = missing_indices

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Unnecessary diff

Comment thread sklearn/preprocessing/_encoders.py Outdated
category_counts = []
compute_counts = return_counts or self._infrequent_enabled

X_list_counter = {}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Although I'm not sure if the _unique maintains ordinal ordering, which is the goal here.

Comment thread sklearn/preprocessing/_encoders.py Outdated

self.categories_ = []
category_counts = []
X_list_dict = {}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What is this for?

Comment thread sklearn/preprocessing/_encoders.py Outdated
# I dont think that this can be placed anywhere else
# because it requires X_list
for i in range(n_features):
result = _unique(X_list[i], return_counts=compute_counts)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

for i in range(n_features):
    unique_vals, counts = _unique(X_list[i], return_counts=True)

   # construct a two-way dictionary mapping unique values to their ordinal encoding and ordincal encoding to their encoded values
   # for example:
   #  - we have {'A': 10, 'B': 10, 'C': 11} are the unique values and their corresponding counts
   # we want to map this as follows:
   # {'C': 0, 'A': 1, 'B': 2}
   
   # first apply argsort
   count_sort_idx = np.argsort(counts)
   sorted_unique_vals = unique_vals[count_sort_idx]

   # second construct two-way dictionary mapping
    encoder_mapping = dict()
    decoder_mapping = dict()
   for idx, val in enumerate(sorted_unique_vals):
         encoder_mapping[val] = idx
         decoder_mapping[idx] = val

# extra stuff to make it work within the scikit-learn design
self.categories_ = set(encoder_mapping.keys())



def test_ordinal_encoder_tie():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It would be useful to add a sentence in the docstring of each unit-test on what exactly is the behavior you're testing

X_trans_inv = enc.inverse_transform(X_trans_enc)
assert_array_equal(X_trans_inv, X_trans)

def test_ordinal_encoder_tie_inv_fit():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same comment as above. What's the behavior here that we're trying to test?

X_trans_inv = enc.inverse_transform(X_trans_enc)
assert_array_equal(X_trans_inv, X_trans)

def test_ordinal_encoder_none():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't understand this test. What is "ordinal_encoder_none" referring to?

assert_array_equal(X_trans_enc, exp)


def test_ordinal_encoder_multy_letters():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Unnecessary test imo. Multiple letters vs characters are both strings.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Linter failure The linter CI is failing on this PR module:preprocessing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add an option to OrdinalEncoder to sort encoding by decreasing frequencies

2 participants