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
Restrict TargetEncoder sklearn export to mean statistics
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.
  • Loading branch information
csadorf committed Oct 16, 2026
commit b43685555c0cd3fca7749cbe85664d594c7e769c
58 changes: 17 additions & 41 deletions python/cuml/cuml/preprocessing/_target_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,20 +531,12 @@ 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, fill_value=None
):
def _category_encodings(self, encode_all, col, categories):
"""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 @@ -556,7 +548,7 @@ def _category_encodings(
}
)
cats = cats.merge(encode_all[[col, "out"]], on=col, how="left")
out = cats.sort_values("pos")["out"].fillna(fill_value)
out = cats.sort_values("pos")["out"].fillna(float(self.mean))
return out.to_numpy()

def _make_fold_column(self, n_samples, fold_ids):
Expand Down Expand Up @@ -813,45 +805,33 @@ def _attrs_from_cpu(self, model):
def _attrs_to_cpu(self, model):
"""Convert cuML TargetEncoder attributes to sklearn format.

sklearn expects independent per-feature encodings. If cuML was fitted
in independent mode, we have exact encodings. Multi-feature combination
mode cannot be converted to sklearn.
sklearn only supports mean-based, independent per-feature encodings.
Median/variance statistics and multi-feature combination mode cannot
be converted to sklearn.
"""
if self.stat != "mean":
raise UnsupportedOnCPU(
f"`stat={self.stat!r}` is not supported by sklearn TargetEncoder; "
"only `stat='mean'` can be converted"
)

# Handle categories that may be numpy arrays or cupy arrays
categories_cpu = []
for cat in self.categories_:
categories_cpu.append(cp.asnumpy(cat))
n_features = len(self.categories_)

# Use per-feature encodings if available (from independent mode or
# sklearn). Combination and median fits set the attribute to an empty
# 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.
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)

# Combination fits initialize an empty list; only independent fits
# and sklearn imports populate per-feature encodings.
if self._encodings_per_feature:
encodings_list = [
_replace_nan(cp.asnumpy(enc))
for enc in self._encodings_per_feature
cp.asnumpy(enc) for enc in self._encodings_per_feature
]
elif n_features == 1:
# Single feature: extract encodings directly (exact conversion)
encodings_list = [
_replace_nan(
self._category_encodings(
self.encode_all,
"X_0",
self.categories_[0],
fill_value=fallback,
)
self._category_encodings(
self.encode_all, "X_0", self.categories_[0]
)
]
else:
Expand All @@ -876,11 +856,7 @@ def _replace_nan(values):
"encodings_": encodings_list,
"categories_": categories_cpu,
"classes_": self.classes_,
# sklearn falls back to `target_mean_` for unseen categories while
# 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_": fallback,
"target_mean_": float(self.mean),
# sklearn internal attributes needed for transform
"_infrequent_enabled": False,
"target_type_": self.target_type_,
Expand Down
222 changes: 118 additions & 104 deletions python/cuml/tests/test_target_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,111 @@ def test_get_feature_names_out():
np.testing.assert_array_equal(res, sol)


def test_as_sklearn_combination_mode_single_feature():
# gh-8745: with a single feature, combination encoding matches sklearn's
# per-feature encoding, so the exported model must carry the encodings.
X = np.array([["a"], ["b"], ["a"], ["b"]], dtype=object)
y = np.array([1.5, 2.0, 3.0, 4.0])
X_new = np.array([["a"], ["b"]], dtype=object)

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

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
)
assert array_equal(sklearn_model.transform(X_new), cuml_encoded)


@pytest.mark.parametrize("stat", ["median", "var"])
@pytest.mark.parametrize("multi_feature_mode", ["combination", "independent"])
@pytest.mark.parametrize("n_features", [1, 2])
def test_as_sklearn_non_mean_stat_raises(stat, multi_feature_mode, n_features):
X = np.array([["a", "x"], ["b", "y"], ["b", "x"]], dtype=object)[
:, :n_features
]
y = np.array([0.1, 1.2, 2.3])
encoder = TargetEncoder(
stat=stat, multi_feature_mode=multi_feature_mode, smooth=0
).fit(X, y)

with pytest.raises(UnsupportedOnCPU, match="only `stat='mean'`"):
encoder.as_sklearn()


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
)
y = np.array([1.5, 2.0, 3.0, 4.0])

encoder = TargetEncoder().fit(X, y)
with pytest.raises(UnsupportedOnCPU):
encoder.as_sklearn()


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
)
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.fit(X, y)
cuml_encoded = encoder.transform(X_new)

sklearn_model = encoder.as_sklearn()
assert len(sklearn_model.encodings_) == 2
np.testing.assert_allclose(
sklearn_model.transform(X_new), cuml_encoded, rtol=1e-5
)


@pytest.mark.parametrize("multi_feature_mode", ["combination", "independent"])
def test_as_sklearn_unseen_category_matches_cuml_fallback(multi_feature_mode):
# Mean-mode export preserves both the target mean and unseen fallback.
X = np.array([["a"], ["b"], ["a"], ["b"]], dtype=object)
y = np.array([0.0, 0.1, 0.2, 10.0])
X_unseen = np.array([["unseen"]], dtype=object)

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

sklearn_model = encoder.as_sklearn()
assert sklearn_model.target_mean_ == pytest.approx(y.mean())
np.testing.assert_allclose(
sklearn_model.transform(X_unseen), cuml_encoded, rtol=1e-5
)


def test_as_sklearn_singleton_variance_raises():
# Reject the singleton-variance reproducer rather than export a variance
# fallback under sklearn's target_mean_ attribute.
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)
np.testing.assert_allclose(encoder.transform(X_new), [[1.21], [1.21]])

with pytest.raises(UnsupportedOnCPU, match="only `stat='mean'`"):
encoder.as_sklearn()


def _make_missing_X(values, kind):
"""Build a single-column input with missing values (``None``) in the
representation given by ``kind``."""
Expand Down Expand Up @@ -432,113 +537,22 @@ def test_targetencoder_missing_string_category_is_nan(kind):
assert isinstance(categories[-1], float) and np.isnan(categories[-1])


def test_as_sklearn_combination_mode_single_feature():
# gh-8745: with a single feature, combination encoding matches sklearn's
# per-feature encoding, so the exported model must carry the encodings.
X = np.array([["a"], ["b"], ["a"], ["b"]], dtype=object)
y = np.array([1.5, 2.0, 3.0, 4.0])
X_new = np.array([["a"], ["b"]], dtype=object)

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

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
)
assert array_equal(sklearn_model.transform(X_new), cuml_encoded)


def test_as_sklearn_median_stat_single_feature():
X = np.array([["a"], ["b"], ["a"], ["b"]], dtype=object)
y = np.array([1.5, 2.0, 3.0, 4.0])
X_new = np.array([["a"], ["b"]], dtype=object)

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

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
)
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
)
y = np.array([1.5, 2.0, 3.0, 4.0])

encoder = TargetEncoder().fit(X, y)
with pytest.raises(UnsupportedOnCPU):
encoder.as_sklearn()


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
@pytest.mark.parametrize("multi_feature_mode", ["combination", "independent"])
def test_as_sklearn_missing_category_matches_cuml(multi_feature_mode):
# Preserve missing-category matching from gh-8698 in supported mean mode.
X = np.array([["a"], ["b"], [None], [None]], dtype=object)
y = np.array([0.1, 1.2, 2.3, 10.0])
X_new = np.array(
[["a"], ["b"], [None], [np.nan], ["unseen"]], 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.fit(X, y)
cuml_encoded = encoder.transform(X_new)

sklearn_model = encoder.as_sklearn()
assert len(sklearn_model.encodings_) == 2
np.testing.assert_allclose(
sklearn_model.transform(X_new), cuml_encoded, rtol=1e-5
)


@pytest.mark.parametrize("stat", ["mean", "median", "var"])
def test_as_sklearn_unseen_category_matches_cuml_fallback(stat):
# gh-8745: cuML falls back to `y_stat_val` for an unseen category, while
# sklearn's TargetEncoder falls back to `target_mean_`. The export has to
# use the same statistic cuML uses, otherwise a median or variance model
# silently disagrees with cuML on unseen categories.
X = np.array([["a"], ["b"], ["a"], ["b"]], dtype=object)
y = np.array([0.0, 0.1, 0.2, 10.0])
X_unseen = np.array([["unseen"]], dtype=object)

encoder = TargetEncoder(stat=stat, output_type="numpy")
encoder.fit(X, y)
cuml_encoded = encoder.transform(X_unseen)

sklearn_model = encoder.as_sklearn()
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)
multi_feature_mode=multi_feature_mode,
smooth=0,
output_type="numpy",
).fit(X, y)

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