From d90172b312d5a28a320f6fccfdcb850f7c693864 Mon Sep 17 00:00:00 2001 From: "claude[bot]" <41898282+claude[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:36:58 +0000 Subject: [PATCH 1/3] Support OrdinalEncoder and unknown categorical values in ValueEncoder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cédric Couralet <243027+micedre@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- tests/test_value_encoder_unknown.py | 26 +++++++ .../value_encoder/value_encoder.py | 71 +++++++++++++++---- 2 files changed, 85 insertions(+), 12 deletions(-) create mode 100644 tests/test_value_encoder_unknown.py diff --git a/tests/test_value_encoder_unknown.py b/tests/test_value_encoder_unknown.py new file mode 100644 index 0000000..cccc028 --- /dev/null +++ b/tests/test_value_encoder_unknown.py @@ -0,0 +1,26 @@ +import numpy as np +import pytest +from sklearn.preprocessing import LabelEncoder, OrdinalEncoder + +from torchTextClassifiers.value_encoder.value_encoder import ValueEncoder + +X = np.array([["a", "x"], ["b", "y"], ["a", "y"]]) + + +def _make(handle_unknown): + cats = {"c1": OrdinalEncoder().fit(X[:, [0]]), "c2": LabelEncoder().fit(X[:, 1])} + return ValueEncoder(LabelEncoder().fit(["p", "q"]), cats, handle_unknown=handle_unknown) + + +def test_handle_unknown_maps_to_extra_index(): + enc = _make(True) + assert enc.vocabulary_sizes == [3, 3] + out = enc.transform(np.array([["a", "z"], ["new", "y"], [np.nan, "x"]], dtype=object)) + assert out.tolist() == [[0, 2], [2, 1], [2, 0]] + + +def test_unknown_raises_by_default(): + enc = _make(False) + assert enc.vocabulary_sizes == [2, 2] + with pytest.raises(ValueError): + enc.transform(np.array([["new", "x"]], dtype=object)) diff --git a/torchTextClassifiers/value_encoder/value_encoder.py b/torchTextClassifiers/value_encoder/value_encoder.py index 7ca946b..27cd903 100644 --- a/torchTextClassifiers/value_encoder/value_encoder.py +++ b/torchTextClassifiers/value_encoder/value_encoder.py @@ -1,7 +1,7 @@ from typing import Optional import numpy as np -from sklearn.preprocessing import LabelEncoder +from sklearn.preprocessing import LabelEncoder, OrdinalEncoder class DictEncoder: @@ -39,11 +39,17 @@ class ValueEncoder: Build encoders externally before passing them in: - DictEncoder: provide a ``{value: index}`` mapping directly. - sklearn LabelEncoder: call ``LabelEncoder().fit(column)`` per feature. + - sklearn OrdinalEncoder: call ``OrdinalEncoder().fit(column.reshape(-1, 1))`` per feature. + (Only for categorical features, not labels.) Initialization: - label_encoder: A DictEncoder or LabelEncoder instance for encoding labels. - - encoders (optional): A dictionary mapping feature names to DictEncoder or - LabelEncoder instances. + - categorical_encoders (optional): A dictionary mapping feature names to DictEncoder, + LabelEncoder or OrdinalEncoder instances. + - handle_unknown (default False): If True, categorical values not seen during fitting + (or missing values) are mapped to an extra "unknown" index, equal to the number of known + categories of the feature, instead of raising a ValueError. ``vocabulary_sizes`` then + includes this extra slot so the embedding layer has a row for it. Properties: - vocabulary_sizes: List of vocabulary sizes (number of unique values) for each feature. @@ -57,9 +63,20 @@ class ValueEncoder: def __init__( self, label_encoder: DictEncoder | LabelEncoder | list[DictEncoder | LabelEncoder], - categorical_encoders: Optional[dict[str, DictEncoder | LabelEncoder]] = None, + categorical_encoders: Optional[ + dict[str, DictEncoder | LabelEncoder | OrdinalEncoder] + ] = None, + handle_unknown: bool = False, ): self.categorical_encoders = categorical_encoders + self.handle_unknown = handle_unknown + if categorical_encoders is not None: + for name, enc in categorical_encoders.items(): + if not isinstance(enc, (DictEncoder, LabelEncoder, OrdinalEncoder)): + raise TypeError( + f"Encoder for '{name}' must be a DictEncoder, LabelEncoder or " + f"OrdinalEncoder, got {type(enc)}" + ) if isinstance(label_encoder, list): for enc in label_encoder: @@ -84,14 +101,26 @@ def vocabulary_sizes(self) -> list[int]: else: sizes = [] for enc in self.categorical_encoders.values(): - if isinstance(enc, DictEncoder): - sizes.append(len(enc.mapping)) - elif hasattr(enc, "classes_"): - sizes.append(len(enc.classes_)) - else: - raise TypeError(f"Unsupported encoder type: {type(enc)}") + sizes.append(len(self._known_categories(enc)) + int(self.handle_unknown)) return sizes + @staticmethod + def _known_categories(enc) -> np.ndarray: + if isinstance(enc, DictEncoder): + return np.array(list(enc.mapping.keys())) + elif isinstance(enc, OrdinalEncoder): + return np.asarray(enc.categories_[0]) + elif hasattr(enc, "classes_"): + return np.asarray(enc.classes_) + raise TypeError(f"Unsupported encoder type: {type(enc)}") + + @staticmethod + def _encode_known(enc, col: np.ndarray) -> np.ndarray: + """Encode a column that only contains known values.""" + if isinstance(enc, OrdinalEncoder): + return enc.transform(col.reshape(-1, 1))[:, 0] + return np.asarray(enc.transform(col)) + @property def num_classes(self) -> int: """Number of unique classes in the label encoder, if provided.""" @@ -116,7 +145,8 @@ def _get_num_classes(enc): def transform(self, X_categorical: np.ndarray) -> np.ndarray: """Encode all categorical columns to integer indices. - Values are converted to strings before lookup. Unknown values raise a ValueError. + Values are converted to strings before lookup. Unknown values raise a ValueError, + unless ``handle_unknown=True``, in which case they map to index ``vocabulary_size``. Args: X_categorical: Array of shape (N, n_features) with categorical values. @@ -137,7 +167,24 @@ def transform(self, X_categorical: np.ndarray) -> np.ndarray: result = np.empty(X_categorical.shape, dtype=np.int64) for idx, (name, encoder) in enumerate(self.categorical_encoders.items()): col = X_categorical[:, idx].astype(str) - encoded = encoder.transform(col) + if self.handle_unknown: + known = self._known_categories(encoder) + is_known = np.isin(col, known.astype(str)) + unknown_index = len(known) + column = np.full(col.shape, unknown_index, dtype=np.int64) + if is_known.any(): + column[is_known] = self._encode_known(encoder, col[is_known]).astype(np.int64) + result[:, idx] = column + continue + if isinstance(encoder, OrdinalEncoder): + known = self._known_categories(encoder).astype(str) + unknown = sorted(set(col[~np.isin(col, known)].tolist())) + if unknown: + raise ValueError( + f"Unknown values in categorical feature '{name}': {unknown}. " + "These values were not seen during fitting." + ) + encoded = self._encode_known(encoder, col) try: result[:, idx] = encoded.astype(np.int64) except (TypeError, ValueError): From 08a09f68817638784a85365aa1af0fecb1c74923 Mon Sep 17 00:00:00 2001 From: "claude[bot]" <41898282+claude[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:21:11 +0000 Subject: [PATCH 2/3] Document OrdinalEncoder support and handle_unknown in ValueEncoder Co-authored-by: Meilame Tayebjee <114609737+meilame-tayebjee@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- docs/source/architecture/overview.md | 24 ++++++++++++++++++++++++ docs/source/tutorials/mixed_features.md | 23 +++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/docs/source/architecture/overview.md b/docs/source/architecture/overview.md index fe0467b..b9c8512 100644 --- a/docs/source/architecture/overview.md +++ b/docs/source/architecture/overview.md @@ -44,6 +44,11 @@ cat_encoder = LabelEncoder().fit(X_train_categories) # Option B: explicit dict mapping cat_encoder = DictEncoder({"Electronics": 0, "Audio": 1, "Books": 2}) +# Option C: sklearn OrdinalEncoder (categorical features only, not labels; +# expects a 2D input, hence the reshape) +from sklearn.preprocessing import OrdinalEncoder +cat_encoder = OrdinalEncoder().fit(X_train_categories.reshape(-1, 1)) + value_encoder = ValueEncoder( label_encoder=LabelEncoder().fit(y_train), # encodes/decodes labels categorical_encoders={ @@ -53,6 +58,25 @@ value_encoder = ValueEncoder( ) ``` +### Handling Unknown Categorical Values + +By default, a categorical value not seen when the encoder was fitted raises a +`ValueError`. Pass `handle_unknown=True` to map unknown (or missing) values to an extra +"unknown" index instead, equal to the number of known categories of that feature: + +```python +value_encoder = ValueEncoder( + label_encoder=LabelEncoder().fit(y_train), + categorical_encoders={"category": cat_encoder}, + handle_unknown=True, +) + +value_encoder.vocabulary_sizes # [4] – 3 known categories + 1 unknown slot +``` + +`vocabulary_sizes` includes the extra slot, so the embedding layer automatically gets a +row for it. This option applies to categorical features only; labels are unaffected. + ### What It Provides ```python diff --git a/docs/source/tutorials/mixed_features.md b/docs/source/tutorials/mixed_features.md index 6da09a1..20317cb 100644 --- a/docs/source/tutorials/mixed_features.md +++ b/docs/source/tutorials/mixed_features.md @@ -217,6 +217,29 @@ X_train = np.column_stack([texts_train, categories_train]) # dtype=object is fi The `ValueEncoder` also exposes `.vocabulary_sizes` and `.num_classes` so you don't have to compute them manually for `ModelConfig`. +sklearn's `OrdinalEncoder` is also supported for categorical features (not labels). +It expects 2D input, so fit it on a reshaped column: + +```python +from sklearn.preprocessing import OrdinalEncoder + +cat_encoder = OrdinalEncoder().fit(X_train_categories.reshape(-1, 1)) +``` + +**Unknown categories at inference time.** By default, a category not seen during fitting +raises a `ValueError`. Set `handle_unknown=True` to map unseen or missing values to an +extra "unknown" embedding index instead: + +```python +value_encoder = ValueEncoder( + label_encoder=LabelEncoder().fit(y_train), + categorical_encoders={"category": cat_encoder}, + handle_unknown=True, +) +``` + +`.vocabulary_sizes` then includes the extra slot (number of known categories + 1). + #### Without ValueEncoder (manual encoding) If you prefer to manage encoding yourself, categorical features must be From 3ffddbaf51ae8121ad1ff84be1d66b1e3190e58e Mon Sep 17 00:00:00 2001 From: meilame-tayebjee <114609737+meilame-tayebjee@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:27:40 +0000 Subject: [PATCH 3/3] Allow Claude bot in code review workflow Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .github/workflows/claude-code-review.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml index 37e66f3..c61bdcc 100644 --- a/.github/workflows/claude-code-review.yml +++ b/.github/workflows/claude-code-review.yml @@ -36,6 +36,7 @@ jobs: uses: anthropics/claude-code-action@v1 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} + allowed_bots: 'claude' plugin_marketplaces: 'https://github.com/anthropics/claude-code.git' plugins: 'code-review@claude-code-plugins' prompt: '/code-review:code-review --comment ${{ github.repository }}/pull/${{ github.event.pull_request.number }}'