Skip to content

PRF: Encoders (very) fast path for pandas/polars categoricals - #34393

Closed
cakedev0 wants to merge 41 commits into
scikit-learn:mainfrom
cakedev0:expe/encode_using_pd_cat
Closed

cakedev0 wants to merge 41 commits into
scikit-learn:mainfrom
cakedev0:expe/encode_using_pd_cat

Conversation

@cakedev0

@cakedev0 cakedev0 commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

WIP

Reference Issues/PRs

Solves partially #34383

This PR also contains changes from #34386 and #34392 to ease benchmarking.

It is inspired by the flamegraph of this script, where encoding shows to be a large chunk of time while it should really not.

Combined with #34386 and #34392, it makes a very visible difference on this script: something like ~1.3x speedup. For the same script but on the bigger California house price dataset (openml#46669), the speed-up is almost 2x compared to main 🤯

What does this implement/fix? Explain your changes.

Pandas and polars support categorical dtypes. For those dtypes, the work of finding uniques & unique inverse is already done internally by those librairies. This PR proposes to write a fast path that uses those internal encodings when available.

The idea is mine but the implementation is 90% AI fow now, I have not yet read very carefully what the AI did, but the tests pass and the performance is crazy good, so I think it's worth opening the PR to discuss if this kind of pattern has its place in scikit-learn.

AI usage disclosure

I used AI assistance for:

  • Code generation
  • Test generation

Benchmarks:

$ python benchmarks/bench_encoding.py -f string
onehot fit 210.6 ms
onehot transform 406.2 ms
onehot fit_transform 606.3 ms
ordinal fit 205.4 ms
ordinal transform 369.8 ms
ordinal fit_transform 575.0 ms
target fit 446.0 ms
target transform 367.0 ms
target fit_transform 584.1 ms

$ python benchmarks/bench_encoding.py -f categorical
onehot fit 28.3 ms
onehot transform 63.4 ms
onehot fit_transform 85.6 ms
ordinal fit 23.4 ms
ordinal transform 33.1 ms
ordinal fit_transform 56.0 ms
target fit 46.2 ms
target transform 30.2 ms
target fit_transform 187.5 ms

We see a 3x to 10x speed-up!

And compared to main, it's 5-80x speed-up 🤯

onehot fit 1826.2 ms
onehot transform 494.6 ms
onehot fit_transform 2322.2 ms
ordinal fit 1822.6 ms
ordinal transform 478.0 ms
ordinal fit_transform 2315.5 ms
target fit 603.1 ms
target transform 550.6 ms
target fit_transform 1057.8 ms

Comment thread sklearn/utils/_encode.py Outdated
"""Return categorical categories, integer codes, and the missing value mask."""
if hasattr(values, "cat") and hasattr(values.cat, "categories"):
categories = values.cat.categories.to_numpy()
codes = values.cat.codes.to_numpy()

@thomasjpfan thomasjpfan Jul 3, 2026 •

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 recall trying to do this ~4ish years ago. The "hard part" was to figure out the behavior during transform time. Let's say during fit time, the order was ["dog", "cat", "bear"] so the codes uses that ordering. At transform time:

  1. If the categorical dtype is the same ["dog", "cat", "bear"], the new codes are consistent with fit time, so we can use the codes directly.
  2. If the categorical dtype is out of order: ["cat", "bear", "dog"], this means we need to either reject this since the dtype is different or remap the codes.
  3. If the categorical dtype only contain a subset, ["cat", "dog"], which either remaps or errors.
  4. If the categorical dtype is a superset, ["cat", "dog", "bear", "bird"], then there we'll have to handle the unknown and remap the known categories to the ordering fit time ordering.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Oh thanks a lot for the detailed edge cases! Indeed, they don't look easy to deal with but I think it's manageable, at least I hope so 😅

Not that indexing/train_test_split preserve all the categories in the dtype, so case 1 should be the most common by far.

For other cases, maybe we can just route them through the normal object-string path... I'll see what's the easiest.

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.

Oh thanks a lot for the detailed edge cases!

We definitely need to start by writing failing tests cases for those and then think about how to deal with them.

Comment thread sklearn/utils/_encode.py Outdated
def _get_categorical_categories_and_codes(values):
"""Return categorical categories, integer codes, and the missing value mask."""
if hasattr(values, "cat") and hasattr(values.cat, "categories"):
categories = values.cat.categories.to_numpy()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What would happen if there are categories in the encoding which do not occur on the data passed to fit?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

For now, it's considered as a "seen category", which is a breaking change. I'm going to change that.

@cakedev0

cakedev0 commented Jul 9, 2026

Copy link
Copy Markdown
Member Author

I made a preliminary refactor to be merged first: #34452


I think I have a good coverage for all the edge cases, and that I found relatively elegant ways to solve them while preserving the speed-up.

I'm going to work on publishing some comprehensive benchmarks.


This is one main choice I made, which is a change of observable behavior:

I preserve the original order of the categorical dtype, while categories are currently always sorted (expect if you pass your owns, in which case for non-numeric, we accept unsorted categories). Note that the original order of the categorical dtype is the sorted order for numerical dtypes.

Why I did that:

  • Sorting would be a bit expensive, but maybe not that much and it can be safely skip in transform. I'll try to measure how expensive it is relative to the rest of the fit.
  • Sorting makes the code more complicated
  • The fact that arrays in categories_ are sorted is not documented
  • A pickle loaded from an older scikit-learn version would still work as expected

Why I'm not 100% sure: codes relying on this implicit contract will break or produce incorrect results.

I'll be happy to have opinions on this matter.

Comment on lines +1888 to +1889
dtype = pd.CategoricalDtype(["b", "a", "c"])
df = pd.DataFrame({"col1": pd.Series(["a", "b", "a"], dtype=dtype)})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Once the issue with unobserved categories is sorted out, could add a test where the unobserved category wouldn't be the last, verifying that there's no gaps in numeration of the output.

@cakedev0
cakedev0 force-pushed the expe/encode_using_pd_cat branch from ef3aafc to 4ba6c2e Compare July 14, 2026 09:02
@cakedev0

Copy link
Copy Markdown
Member Author

I'm closing this PR in favor of another way: using nw.Seriess uniques and replace_strict. I get almost the same speedup for pandas categorical, while also having an important speedup for the other cases (pandas string, polars) and a much much simpler code.

@cakedev0 cakedev0 closed this Jul 21, 2026
@lorentzenchr

Copy link
Copy Markdown
Member

@cakedev0 Can you ping me in the alternative PR with using narwhals?

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants