Repository navigation
Conversation
| """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() |
There was a problem hiding this comment.
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:
- If the categorical dtype is the same
["dog", "cat", "bear"], the new codes are consistent withfittime, so we can use the codes directly. - 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. - If the categorical dtype only contain a subset,
["cat", "dog"], which either remaps or errors. - 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 orderingfittime ordering.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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() |
There was a problem hiding this comment.
What would happen if there are categories in the encoding which do not occur on the data passed to fit?
There was a problem hiding this comment.
For now, it's considered as a "seen category", which is a breaking change. I'm going to change that.
…-learn into expe/encode_using_pd_cat
# Conflicts: # sklearn/preprocessing/_encoders.py # sklearn/utils/_encode.py # sklearn/utils/tests/test_encode.py
|
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:
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. |
| dtype = pd.CategoricalDtype(["b", "a", "c"]) | ||
| df = pd.DataFrame({"col1": pd.Series(["a", "b", "a"], dtype=dtype)}) |
There was a problem hiding this comment.
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.
ef3aafc to
4ba6c2e
Compare
|
I'm closing this PR in favor of another way: using |
|
@cakedev0 Can you ping me in the alternative PR with using narwhals? |
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:
Benchmarks:
-f string=> goes through the normal/old python path, still benefits from speed-up of ENH PERF Speed up unique counts for strings, thereby speeding up encoding #34386 and PRF: Faster encoders thanks to F-order layout #34392.-f categorical=> uses pandas categorical => uses the fast pathWe see a 3x to 10x speed-up!
And compared to main, it's 5-80x speed-up 🤯