Skip to content

Add an option to OrdinalEncoder to sort encoding by decreasing frequencies #32161

Open

Description

@ogrisel

Describe the workflow you want to enable

At the moment, when no categories are provided, the default ordering of categories for a given categorical column is based on the lexicographical ordering of the categories observed in the training set.

However, this is quite arbitrary and one could instead provide an option to encode such values based on their observed frequency in the training set.

The motivation would be to nudge the inductive bias of tree-based models (and models that favor axis aligned decision functions) into separating nominal from rare values more easily (e.g. fewer splits in a tree). This might be especially useful for outlier detection models such as IsolationForest.

Related to #15796.

Describe your proposed solution

Extend the categories option to have:

  • categories="lexigraphical" (default for backward compat);
  • categories=user_provided_list (same as today);
  • categories="frequency" (the new option).

If categories="frequency", then the generated category encodings would be:

  • 0 would encode the most frequent category observed in the training set,
  • 1 the second most frequent,
  • ...
  • and so on until the least frequent categories.

Tie breaking could be based on the lexicographical order to ensure that the behavior of OrdinalEncoder remains invariant under a shuffling of the rows of the training set.

EDIT: we could name this option "decreasing_frequency" instead of "frequency" to be more explicit that values closest to 0 mean higher frequency categories. And this would allow to also add "increasing_frequency" if we want, but I am not sure if it would be needed/useful to have both options.

Describe alternatives you've considered, if relevant

  • Use TargetEncoder that leverages some frequency info (mixed with the mean value of the target variable), but this is a supervised method and would therefore not be suitable for unsupervised anomaly detection tasks, for instance.

  • Introduce a new dedicated class, e.g. FrequencyEncoder.

    • pro: allow using the observed relative frequency (between 0 and 1) as value (but would collapse equally frequent categories into the same numerical value).
    • con: introduces yet another estimator class in our public API.

Additional context

No response

Activity

  1. added
    Needs Decision - Include Feature
    on Sep 11, 2025
  2. ogrisel commented on Sep 11, 2025

    @ogrisel
    MemberAuthor

    Note to contributors: please wait for maintainers to reach a consensus on whether we want this new feature (I do) and how to implement it (if we decide its inclusion) before asking for guidance or contributing a PR.

  3. krisbiradar commented on Sep 13, 2025

    @krisbiradar
  4. joaosferreira commented on Sep 13, 2025

    @joaosferreira

    This looks like a great addition! I don't think I ever used the "auto" option TBH.

    I was thinking if these options could be used with #32179 in the future. That would allow combining explicit categories for some columns with frequency-based (or other) ordering for other columns in the same encoder.

    Here is an example:

    enc = OrdinalEncoder(categories={
        "color": "frequency",
        "size": ["S", "M", "L"],
    })
  5. ogrisel commented on Sep 15, 2025

    @ogrisel
    MemberAuthor

    Actually, it would be convenient to have an easy way to set the default strategy for keys not part of the explicit list-based or dict-based category mapping.

    Maybe, once both #32179 and this PR are merged, we could consider the inclusion of an extra parameter such as:

    enc = OrdinalEncoder(
        categories={
            "size": ["S", "M", "L"],
            ...  # other explicit category mappings
        },
        other_categories="frequency",  # default mapping strategy
    )

    with possible values:

        other_categories : {"error", "frequency", "lexicographical"}, default="error"
    

    If we don't want the extra parameter, users could still get something similar by:

    from collections import default_dict
    
    enc = OrdinalEncoder(
        categories=defaultdict(
            lambda: "frequency",  # default mapping strategy
            {
                "size": ["S", "M", "L"],
                ...  # explicit category mappings
            }
        )
    )

    The advantage of this approach is that we don't need to expand the public API any further but this is at the cost of slightly more complex to read and write user code.

  6. Shubham1193 commented on Sep 22, 2025

    @Shubham1193
  7. aryandhawan commented on Oct 7, 2025

    @aryandhawan
  8. aryandhawan commented on Oct 7, 2025

    @aryandhawan
  9. adam2392 commented on Mar 6, 2026

    @adam2392
    Member

    Per some discussion in a separate unrelated PR: #33354 (comment)

    tldr: frequency encoding is a useful heuristic

  10. cakedev0 commented on Mar 9, 2026

    @cakedev0
    Member

    Note: I reworked a bit on Adam's code from PR #33354 and I don't get to the same conclusion for now about the gain of frequency encoding on this example.
    I think @adam2392 you got this impression from the way encode_rare_categories is implemented: collapse the last n_cats - max_categories - 1 categories into one category, so you loose a lot of information if those last categories are not the least frequent ones. Note that OrdinalEncoder does this "collapse the least frequent ones" piece, even if for the "frequent" categories it sorts them lexicographically and not by frequency.

    I'll share more results on that when I have time.

  11. lorentzenchr commented on Mar 15, 2026

    @lorentzenchr
    Member

    Is there another use case besides the possible improvement in model performance?

    For tree based models, as @cakedev0, I don’t anticipate a performance improvement over native categorical support. But I can be convinced by examples.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs Decision - Include FeatureNew Feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions