Skip to content

Fix TargetEncoder sklearn export and reject unsupported statistics - #8765

Merged
rapids-bot[bot] merged 4 commits into
NVIDIA:mainfrom
CodeTrainerMan:fix/target-encoder-as-sklearn-encodings
Oct 16, 2026
Merged

rapids-bot[bot] merged 4 commits into
NVIDIA:mainfrom
CodeTrainerMan:fix/target-encoder-as-sklearn-encodings

Conversation

@CodeTrainerMan

@CodeTrainerMan CodeTrainerMan commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes TargetEncoder.as_sklearn() to export populated encodings for single-feature combination mode and validates conversion eligibility for mean-based, per-feature encoding.

Raises UnsupportedOnCPU for median and variance statistics, preserving sklearn’s mean-based encoding contract.

Preserves the target mean and missing-category handling during export. Adds regression coverage for conversion eligibility, exported encodings, and unseen-category fallback.

Closes #8745

@CodeTrainerMan
CodeTrainerMan requested a review from a team as a code owner October 13, 2026 01:43
@copy-pr-bot

copy-pr-bot Bot commented Oct 13, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@github-actions github-actions Bot added the Cython / Python Cython or Python issue label Oct 13, 2026
@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: NVIDIA/cuml/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Enterprise
  • Run ID: a48870f2-1404-4c9f-8f87-d33d0ec8c11d
📥 Commits

Reviewing files that changed from the base of the PR and between 9c8be6c and b436855.

📒 Files selected for processing: 2
  • python/cuml/cuml/preprocessing/_target_encoder.py
  • python/cuml/tests/test_target_encoder.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

📝 Summary

Summary by CodeRabbit

  • Bug Fixes
    • Improved scikit-learn conversion for mean-mode target encoders, including matching behavior for unseen and missing categories.
    • Enabled conversion of single-feature combination-mode models and preserved support for independent-mode models.
    • Conversion remains unsupported for non-mean statistics and multi-feature combination models.

TargetEncoder.as_sklearn() now rejects non-mean statistics and handles empty per-feature encodings. Tests compare supported exports with cuML and check conversion errors and category behavior.

Changes: TargetEncoder sklearn export

Layer / File(s) Summary
Export encodings and validate conversion
python/cuml/cuml/preprocessing/_target_encoder.py, python/cuml/tests/test_target_encoder.py
The export path uses per-feature encodings when they are populated. Single-feature combination mode can use the existing fallback, while multi-feature combination mode raises UnsupportedOnCPU. Non-mean statistics also raise UnsupportedOnCPU. Tests compare supported exports with cuML and check missing and unseen categories.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: jcrist

Merge Risk: ⚪ Minimal · up to b4368

TargetEncoder.as_sklearn() now exports mean-mode encodings correctly and rejects unsupported statistics and multi-feature combination mode. No merge-blocking risk is identified. The full CI matrix was not run, which is normal pre-merge validation.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Linked Issues check Warning Issue #8745 requires sklearn export for one-feature combination mode and stat="median", with populated encodings and cuML-equivalent transform. The change fixes one-feature combination export and … Support stat="median" for the one-feature export path. Populate the sklearn encodings and verify that the exported model's transform matches cuML. Keep UnsupportedOnCPU for multi-feature combination mode.
Docstring Coverage Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 3 passed
Check name Status Explanation
Out of Scope Changes check Passed The production change and added tests stay in the TargetEncoder sklearn export path. The statistic checks, combination-mode checks, and fallback tests are directly related to issue #8745. No unrelated…
Description check Passed The description explains the problem, implementation scope, supported and unsupported export cases, regression coverage, and links issue #8745 with a closing keyword. It is sufficiently complete for t…
Title check Passed The title clearly describes the main changes: fixing TargetEncoder sklearn export and rejecting unsupported statistics.
Full details: Out of Scope Changes check

Explanation

The production change and added tests stay in the TargetEncoder sklearn export path. The statistic checks, combination-mode checks, and fallback tests are directly related to issue #8745. No unrelated change is demonstrated.

Full details: Description check

Explanation

The description explains the problem, implementation scope, supported and unsupported export cases, regression coverage, and links issue #8745 with a closing keyword. It is sufficiently complete for the provided template.

Full details: Linked Issues check

Explanation

Issue #8745 requires sklearn export for one-feature combination mode and stat="median", with populated encodings and cuML-equivalent transform. The change fixes one-feature combination export and rejects multi-feature combination export as required. However, _attrs_to_cpu raises UnsupportedOnCPU for every statistic other than "mean", and the added tests require rejection for "median". This does not meet the issue's median export requirement.

Resolution

Support stat="median" for the one-feature export path. Populate the sklearn encodings and verify that the exported model's transform matches cuML. Keep UnsupportedOnCPU for multi-feature combination mode.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@CodeTrainerMan

Copy link
Copy Markdown
Contributor Author

@csadorf this is the PR for #8745 whose scope you approved (combining the attrs_to_cpu branch-selection fix with exporting y_stat_val as arget_mean/unseen-category fallback, plus regression tests). It is rebased onto current main (9f5bc7b). Could you take a look when you have a chance? Thanks!

- Test the value of `_encodings_per_feature` rather than its presence.
  Combination and median fits set it to an empty list, which made the check
  always true after `fit`, leaving both the single-feature branch and the
  `UnsupportedOnCPU` branch unreachable: single-feature combination and
  `stat="median"` exported a model with `encodings_ = []`, and multi-feature
  combination exported an empty model instead of raising.

- Export `y_stat_val` as the sklearn model's `target_mean_`, and use it as
  the fallback for categories missing from `encode_all`. cuML falls back to
  `y_stat_val` for unseen categories while sklearn falls back to
  `target_mean_`, so exporting `self.mean` made the converted model disagree
  with cuML for `stat="median"` and `stat="var"` (and for `stat="mean"`
  whenever `y_stat_val` differs from `self.mean`).

Tests cover the single-feature combination and median exports, the
`UnsupportedOnCPU` path, independent mode, and unseen-category agreement
between cuML and the exported model for mean, median and var.
- Use the direct truthiness check on _encodings_per_feature instead of getattr():
  all fitted paths initialize the attribute, so the direct check is enough.
- Impute NaN/undefined encodings with y_stat_val on export. With stat="var" and
  smooth=0 the variance of a singleton category is 0/0 (NaN); cuML imputes that with
  y_stat_val before use, so the exported model must use the same value. The
  single-feature path now passes y_stat_val as _category_encodings' fill_value,
  because the helper otherwise falls back to self.mean, which disagrees with cuML
  for stat="median"/"var"; _replace_nan() covers the remaining export path.
- Add a regression test for the singleton-category case (stat="var", smooth=0).
- Apply ruff-format to the files touched by this PR (79-column style).
@CodeTrainerMan
CodeTrainerMan force-pushed the fix/target-encoder-as-sklearn-encodings branch from 86798ee to 9c8be6c Compare October 16, 2026 14:17
@CodeTrainerMan

CodeTrainerMan commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor Author

@csadorf thanks for the review. I've rebased onto current main and both points are addressed in 9c8be6c.

On the conflict: it came from #8698 ("Treat missing string value seen during fit as its own category"), which refactored the single-feature encoding extraction in _attrs_to_cpu into the new _category_encodings() helper and appended new tests to test_target_encoder.py. For the record, gh-8745 itself is still unfixed on main (_attrs_to_cpu still selects its branch with hasattr(self, "_encodings_per_feature") and still exports target_mean_ as self.mean), so this PR is still needed and does not duplicate anything.

I resolved it by adopting upstream's _category_encodings() - its merge-based lookup is required for missing categories - while keeping our guard and the y_stat_val export.

One thing worth flagging: _category_encodings() falls back to float(self.mean) for categories without an encoding, but cuML's own transform path falls back to y_stat_val (_impute_to_cupy). Those differ whenever stat is median or var, so the exported model disagreed with cuML: for y = [0, 0.1, 0.2, 10] the fallback should be the median 0.15, not the mean 2.575. That also masked the NaN fix you asked for - with stat="var" and smooth=0 a singleton category produces 0/0, and the helper filled it with the mean before any NaN handling could run, so the export returned 1.2 where cuML returns 1.21.

To fix it I added an optional fill_value argument to _category_encodings() (the default is unchanged, so the _fit call site is unaffected) and as_sklearn() passes y_stat_val. It may be worth checking whether the _fit_transform_independent call site should use y_stat_val as well, since it raises the same mean-vs-statistic question.

Validation (RTX 4070 Ti, from-source cuML 26.12.00a117):

  • single-feature combination: cuML and the exported model both give [2.25 3. ], encodings_ is [array([2.25, 3. ])]
  • multi-feature combination: raises UnsupportedOnCPU
  • stat="median": matches cuML
  • unseen-category fallback: matches cuML for mean, median and var
  • singleton category (stat="var", smooth=0): encodings_ contains no NaN and the model transforms [["a"], ["unseen"]] to [1.21 1.21], matching cuML
  • python/cuml/tests/test_target_encoder.py: 87 passed

I also updated the PR description with a validation section. One note so it doesn't look like a regression: three pandas-string cases fail locally if only _target_encoder.py is refreshed inside an older build; with the full source tree (including encoders.py) all 87 pass, so those were an artifact of my local setup rather than this change.

Housekeeping: I don't have permission to apply RAPIDS labels here - could you please add non-breaking and bug? The Label Checker is currently the only failing status on this PR.

Reject median and variance export instead of storing a non-mean fallback in target_mean_. Remove export-only fallback translation, preserve native cuML behavior, and cover supported mean-mode exports and unsupported statistics.
@csadorf

csadorf commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

I’ve restricted as_sklearn() to mean-based encoding; stat="median" and "var" now raise UnsupportedOnCPU.

Exporting y_stat_val as target_mean_ preserves unseen-category predictions, but violates sklearn’s definition of that attribute as the overall target mean. Keeping the actual mean would instead change predictions for those modes. Rejecting the conversion avoids both problems without changing native cuML behavior. This supersedes my earlier request to impute singleton-variance encodings during export.

I’ve pushed two commits: one merges main; the other applies this restriction and updates the tests. Mean-mode export remains supported for independent encoding and single-feature combination encoding. Multi-feature combination export continues to raise UnsupportedOnCPU.

@csadorf csadorf added bug Something isn't working non-breaking Non-breaking change labels Oct 16, 2026
@csadorf

csadorf commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

/ok to test b436855

@csadorf csadorf changed the title Fix TargetEncoder.as_sklearn exporting empty encodings Fix TargetEncoder sklearn export and reject unsupported statistics Oct 16, 2026
@csadorf

csadorf commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Updated the PR title and description to reflect the revised scope and implementation.

@csadorf

csadorf commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

/merge

@rapids-bot
rapids-bot Bot merged commit ab7e1f5 into NVIDIA:main Oct 16, 2026
149 of 151 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working Cython / Python Cython or Python issue non-breaking Non-breaking change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] TargetEncoder.as_sklearn() exports empty encodings_ for the default multi_feature_mode="combination"

2 participants