Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 3 additions & 0 deletions docs/representations/categorical_encoding.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ t.transform(np.array([["unseen"]])).ravel()
```

Unseen categories at transform time map to a reserved slot (code `0`) rather than raising.
Codes follow the sorted order of the categories. A column that mixes types which cannot be
compared, such as integer codes and strings in one object column, is ordered by type name and
then naturally within each type.

```{note}
Integer encoding imposes an order on the codes. Feed it to models that treat the code as an
Expand Down
29 changes: 27 additions & 2 deletions pretab/encoding/categorical/ordinal.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,38 @@ def _is_missing_value(value) -> bool:
return bool(pd.isna(value))


def _sorted_categories(values: np.ndarray) -> list:
"""Return the distinct categories of ``values`` in sorted order.

Categories of one type keep their natural order (``np.unique``). A column that
mixes types that cannot be compared, such as ints and strings in an object
column, is ordered by type name first and naturally within each type, so the
numbering is still deterministic.
"""
try:
return list(np.unique(values))
except TypeError:
groups: dict[str, list] = {}
for value in dict.fromkeys(values):
groups.setdefault(type(value).__name__, []).append(value)
ordered = []
for name in sorted(groups):
try:
ordered.extend(sorted(groups[name]))
except TypeError:
ordered.extend(sorted(groups[name], key=repr))
return ordered


class ContinuousOrdinalTransformer(RepresentationSpecMixin, TransformerMixin, BaseEstimator):
"""Encode categorical features as continuous integer values.

Each unique category within a feature is assigned an integer based on its
sorted order. Unknown, missing (``None``, ``pd.NA`` or NaN), or unseen categories are
mapped to ``0``. This is useful for models that can only handle numerical
input.
input. A feature that mixes types which cannot be compared (e.g. ints and
strings in one object column) is ordered by type name, then naturally within
each type.

Attributes
----------
Expand Down Expand Up @@ -76,7 +101,7 @@ def fit(self, X, y=None):
# Missing values are excluded before sorting: np.unique
# cannot compare a NaN or None against a string category.
non_missing = np.array([v for v in column if not _is_missing_value(v)], dtype=object)
categories = np.unique(non_missing) if non_missing.size else np.array([], dtype=object)
categories = _sorted_categories(non_missing) if non_missing.size else []
mapping = {category: i + 1 for i, category in enumerate(categories)}
mapping[None] = 0 # Assign 0 to unknown/missing values
self.mapping_.append(mapping)
Expand Down
32 changes: 32 additions & 0 deletions tests/encoding/categorical/test_continuous_ordinal_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,35 @@ def test_continuous_ordinal_all_missing_and_transform_time_missing():
clean = ContinuousOrdinalTransformer().fit(pd.DataFrame({"c": ["a", "b"]}))
transformed = clean.transform(pd.DataFrame({"c": [pd.NA, "unseen", "a"]}))
assert transformed.ravel().tolist() == [0, 0, 1]


def test_continuous_ordinal_numbers_mixed_type_categories():
"""np.unique cannot sort ints next to strings, so fit raised TypeError."""
X = pd.DataFrame({"c": pd.Series([10, "b", 2, "a", np.nan, 2], dtype=object)})
transformer = ContinuousOrdinalTransformer().fit(X)

assert transformer.mapping_[0] == {2: 1, 10: 2, "a": 3, "b": 4, None: 0}
transformed = transformer.transform(pd.DataFrame({"c": pd.Series([2, "a", 10, "unseen", None], dtype=object)}))
assert transformed.ravel().tolist() == [1, 3, 2, 0, 0]


def test_continuous_ordinal_keeps_the_sorted_order_of_one_type():
X = pd.DataFrame({"c": [10, 2, 1, 2]})
assert ContinuousOrdinalTransformer().fit_transform(X).ravel().tolist() == [3, 2, 1, 2]


def test_preprocessor_encodes_a_mixed_type_categorical_column():
import json

from pretab import Preprocessor

rng = np.random.default_rng(0)
# One most frequent category: scikit-learn 1.6's SimpleImputer cannot break a
# most-frequent tie between an int and a str (later versions can).
X = pd.DataFrame({"code": pd.Series([1, "a", "a", 2, "b", 10] * 10, dtype=object), "x": rng.normal(size=60)})
pre = Preprocessor(numerical_method="minmax").fit(X, rng.normal(size=60))

assert pre.categorical_features_ == ["code"]
out = pre.transform(X, return_array=True)
restored = Preprocessor.from_spec(json.loads(json.dumps(pre.to_spec())))
np.testing.assert_array_equal(restored.transform(X, return_array=True), out)
Loading