Repository navigation
Conversation
Add a pandas-specific fast path in `_BaseEncoder._check_X`/`_unique`/`_encode` that avoids materializing Categorical/Arrow-backed pandas columns into a full per-row numpy object array before uniquing/encoding. Non-numeric pandas columns are kept as native Series through `_check_X`, and `_unique`/`_encode` dispatch to `pandas.factorize`/`Series.unique`/`Index.get_indexer` for non-object dtypes, falling back to the existing set()/dict-based path for plain object dtype where pandas' own call overhead isn't worth paying.
This reverts commit da33e44.
|
Maybe @MarcoGorelli has an opinion? |
| """ | ||
| import pandas as pd | ||
|
|
||
| codes, index = pd.factorize(values, sort=True, use_na_sentinel=False) |
There was a problem hiding this comment.
Wouldn't this change the order of the categories compared to 'unique()'?
There was a problem hiding this comment.
The sort=True should avoid that.
thanks for the ping! In general we try to keep overhead minimal (even negative sometimes, compared with how most people write pandas https://narwhals-dev.github.io/narwhals/overhead/) @cakedev0 may I ask which operations incurred overhead? I'm aware of the |
|
It was a while ago already 😅 but IIRC it was not really that narwhals adds overhead in itself, it's either one of those:
I asked a LLM to try to implement narwhals equivalent of the [LLM speaking:] Result: a genuine narwhals implementation cannot beat the current pandas fast path — it's consistently 2–11x slower. Root cause, not just overhead:
The only variant that matched pandas performance was the "hybrid" one — which special-cases [me again:] The last paragraph is probably what I'll do in the next PR: replace the pandas path by a narwhals path with inside it a fast path for pandas. I could have started by the narwhals path and then specialize it for pandas, but personally I would not approve a perf PR with an unclear speed trade-off. |
|
Hey @cakedev0 I noticed there's no test covering OrdinalEncoder(categories="auto") against a pd.Categorical with a deliberately non-alphabetical order (checked the diff and the rest of the test file, nothing exercises that case). Since pd.factorize(sort=True) follows the dtype's own category order rather than sorting alphabetically, adding that test would lock in behavior that effectively closes #14953. Mind if I put together that test and open it as a follow-up? |
|
Hi @lcrmorin
Thank you, this is a good catch and this is a problem, currently with this PR:
For now, I will maintain alphabetical order for the pandas path too. |
This is my third attempt at this 😅 but I'm really convinced this is the good one.
Reference Issues/PRs
Towards #14953 (or even closes it?)
Previous attempts for reference:
DataFrame.sort()fails on dictionary-encoded pyarrow columns narwhals-dev/narwhals#3841 (when it is, I might reopen the PR, as a polars/pyarrow fast path through narwhals).This PR is an in-between: it's only for pandas (so no narwhals overhead), but has the same nice implementation pattern than the narwhals one (specialized paths in
sklearn/utils/_encode.py).What does this implement/fix? Explain your changes.
It changes
_BaseEncoder._check_Xto keep string or categorical dataframe columns as Series instead of forcing everything throughcheck_arrayinto numpy object arrays. It also simplifies it overall, which leads to a slight speed-up for the object path (which still goes through numpy conversion, etc. see comments in the code about why this choice).Then in
_unique/_encode, those Series are routed through special paths (_unique_pandas/_encode_pandas) that are particularly efficient for categorical dtype:_unique_pandasleverages pd.factorize_encode_pandasleveragespd.Index(uniques).get_indexer(values)It also adds/fixes the support for recent pandas pyarrow-backed string Series (added non regression test parametrized over
string[python]/string[pyarrow]).Also, fixing code coverage led me to port the same optimization in
LabelEncoder(to naturally use thereturn_inversebranch of_unique_pandas). I checked performance impact quickly, it's a clear win, similar to what happens with encoders.AI usage disclosure
I used AI assistance for:
Any other comments?
An other nice thing with this PR: it compounds well with the "transform cache" idea I started exploring here cakedev0#13
Benchmarks
I ran
python benchmarks/bench_encoders.py -l pandas -e ordinal,ordinal-max10 -o main.csv(pandas only,OrdinalEncoder(without and with counts computing), 5 OpenML datasets), onmainand this branch and compared results.No regressions anywhere in this matrix and some very big speed-ups for the categorical case (and could be even much more with a larger number of rows).
Object path is sometimes faster thanks to simplifications in
_check_Xonly (no other optimizations for this path).Numbers below are
main_ms → this_branch_ms (speedup).ordinal
ordinal-max10
Very similar speed-ups
Details