Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Address review: simplify guard and impute NaN encodings on export
- 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).
  • Loading branch information
CodeTrainerMan committed Oct 16, 2026
commit 9c8be6c6d7c6d367ff4733e7248c4f183f5d1b6a
41 changes: 32 additions & 9 deletions python/cuml/cuml/preprocessing/_target_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,12 +531,20 @@ def _compute_single_feature_encoding_median(self, train, col):
encode_all.columns = [col, "out"]
return encode_all

def _category_encodings(self, encode_all, col, categories):
def _category_encodings(
self, encode_all, col, categories, fill_value=None
):
"""Encodings of `categories` in order, falling back to the mean.

Uses a merge rather than comparing values so that a missing
category matches the missing key in `encode_all`.

`fill_value` overrides the fallback for categories without an
encoding; `as_sklearn()` passes `y_stat_val`, which is what cuML
itself falls back to.
"""
if fill_value is None:
fill_value = float(self.mean)
# A missing category has to be null to match the null key in
# `encode_all`. `_cats_to_series` hardcodes `nan_as_null=True`
# (cudf's default) so the behavior doesn't switch when cudf.pandas
Expand All @@ -548,7 +556,7 @@ def _category_encodings(self, encode_all, col, categories):
}
)
cats = cats.merge(encode_all[[col, "out"]], on=col, how="left")
out = cats.sort_values("pos")["out"].fillna(float(self.mean))
out = cats.sort_values("pos")["out"].fillna(fill_value)
return out.to_numpy()

def _make_fold_column(self, n_samples, fold_ids):
Expand Down Expand Up @@ -820,15 +828,30 @@ def _attrs_to_cpu(self, model):
# list, so the check has to test its value rather than its presence:
# otherwise the single-feature branch and the UnsupportedOnCPU branch
# below are both unreachable.
if getattr(self, "_encodings_per_feature", None):
encodings_list = []
for enc in self._encodings_per_feature:
encodings_list.append(cp.asnumpy(enc))
fallback = float(self.y_stat_val)

def _replace_nan(values):
# cuML imputes NaN encodings with y_stat_val before using them (see
# _impute_to_cupy; the variance of a singleton category is 0/0), so the
# exported model has to use the same value: otherwise its transform returns
# NaN where cuML returns the imputed statistic.
return np.where(np.isnan(values), fallback, values)

if self._encodings_per_feature:
encodings_list = [
_replace_nan(cp.asnumpy(enc))
for enc in self._encodings_per_feature
]
elif n_features == 1:
# Single feature: extract encodings directly (exact conversion)
encodings_list = [
self._category_encodings(
self.encode_all, "X_0", self.categories_[0]
_replace_nan(
self._category_encodings(
self.encode_all,
"X_0",
self.categories_[0],
fill_value=fallback,
)
)
]
else:
Expand Down Expand Up @@ -857,7 +880,7 @@ def _attrs_to_cpu(self, model):
# cuML falls back to `y_stat_val`, so export the statistic cuML
# actually uses. Otherwise a model fitted with `stat="median"` or
# `stat="var"` silently disagrees with cuML on unseen categories.
"target_mean_": float(self.y_stat_val),
"target_mean_": fallback,
# sklearn internal attributes needed for transform
"_infrequent_enabled": False,
"target_type_": self.target_type_,
Expand Down
42 changes: 37 additions & 5 deletions python/cuml/tests/test_target_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import pandas
import pytest

from cuml.internals.interop import UnsupportedOnCPU
from cuml.preprocessing._target_encoder import TargetEncoder
from cuml.testing.utils import array_equal

Expand Down Expand Up @@ -444,7 +445,9 @@ def test_as_sklearn_combination_mode_single_feature():

sklearn_model = encoder.as_sklearn()
assert len(sklearn_model.encodings_) == 1
np.testing.assert_allclose(sklearn_model.encodings_[0], [2.25, 3.0], rtol=1e-6)
np.testing.assert_allclose(
sklearn_model.encodings_[0], [2.25, 3.0], rtol=1e-6
)
assert array_equal(sklearn_model.transform(X_new), cuml_encoded)


Expand All @@ -459,15 +462,19 @@ def test_as_sklearn_median_stat_single_feature():

sklearn_model = encoder.as_sklearn()
assert len(sklearn_model.encodings_) == 1
np.testing.assert_allclose(sklearn_model.encodings_[0], [2.25, 3.0], rtol=1e-6)
np.testing.assert_allclose(
sklearn_model.encodings_[0], [2.25, 3.0], rtol=1e-6
)
assert array_equal(sklearn_model.transform(X_new), cuml_encoded)


def test_as_sklearn_combination_mode_multiple_features_raises():
# gh-8745: combination encoding of several features has no sklearn
# equivalent, so the conversion must refuse instead of exporting an
# empty model.
X = np.array([["a", "x"], ["b", "y"], ["a", "y"], ["b", "x"]], dtype=object)
X = np.array(
[["a", "x"], ["b", "y"], ["a", "y"], ["b", "x"]], dtype=object
)
y = np.array([1.5, 2.0, 3.0, 4.0])

encoder = TargetEncoder().fit(X, y)
Expand All @@ -477,11 +484,15 @@ def test_as_sklearn_combination_mode_multiple_features_raises():

def test_as_sklearn_independent_mode():
# independent mode already exported correctly and must keep working
X = np.array([["a", "x"], ["b", "y"], ["a", "y"], ["b", "x"]], dtype=object)
X = np.array(
[["a", "x"], ["b", "y"], ["a", "y"], ["b", "x"]], dtype=object
)
y = np.array([1.5, 2.0, 3.0, 4.0])
X_new = np.array([["a", "y"], ["b", "x"]], dtype=object)

encoder = TargetEncoder(multi_feature_mode="independent", output_type="numpy")
encoder = TargetEncoder(
multi_feature_mode="independent", output_type="numpy"
)
encoder.fit(X, y)
cuml_encoded = encoder.transform(X_new)

Expand Down Expand Up @@ -510,3 +521,24 @@ def test_as_sklearn_unseen_category_matches_cuml_fallback(stat):
np.testing.assert_allclose(
sklearn_model.transform(X_unseen), cuml_encoded, rtol=1e-5
)


def test_as_sklearn_singleton_category_no_nan_encodings():
# gh-8745 (review follow-up): with stat="var" and smooth=0 the variance of a
# singleton category is 0/0, i.e. NaN. cuML imputes that with y_stat_val before
# using it, so the export has to use the same value instead of copying the NaN:
# otherwise the exported model returns NaN where cuML returns the imputed statistic.
X = np.array([["a"], ["b"], ["b"]], dtype=object)
y = np.array([0.1, 1.2, 2.3])
X_new = np.array([["a"], ["unseen"]], dtype=object)

encoder = TargetEncoder(stat="var", smooth=0, output_type="numpy")
encoder.fit(X, y)
cuml_encoded = encoder.transform(X_new)

sklearn_model = encoder.as_sklearn()
exported = np.asarray(sklearn_model.encodings_[0], dtype=float)
assert not np.isnan(exported).any()
np.testing.assert_allclose(
sklearn_model.transform(X_new), cuml_encoded, rtol=1e-5
)
Loading