|
| 1 | +"""CatBoostScorer class for CatBoost-based classification with switchable encoding.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from enum import Enum |
| 5 | +from typing import Any, cast |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +import numpy.typing as npt |
| 9 | +import pandas as pd |
| 10 | +from catboost import CatBoostClassifier |
| 11 | + |
| 12 | +from autointent import Context, Embedder |
| 13 | +from autointent.configs import EmbedderConfig, TaskTypeEnum |
| 14 | +from autointent.custom_types import FloatFromZeroToOne, ListOfLabels |
| 15 | +from autointent.modules.base import BaseScorer |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +class FeaturesType(str, Enum): |
| 21 | + """Type of features used in CatBoostScorer.""" |
| 22 | + |
| 23 | + TEXT = "text" |
| 24 | + EMBEDDING = "embedding" |
| 25 | + BOTH = "both" |
| 26 | + |
| 27 | + |
| 28 | +class CatBoostScorer(BaseScorer): |
| 29 | + """CatBoost scorer using either external embeddings or CatBoost's own BoW encoding. |
| 30 | +
|
| 31 | + Args: |
| 32 | + embedder_config: Config of the base transformer model (HFModelConfig, str, or dict) |
| 33 | + If None (default) the scorer relies on CatBoost's own Bag-of-Words encoding, |
| 34 | + otherwise the provided embedder is used. |
| 35 | +
|
| 36 | + features_type: Type of features used in CatBoost. Can be one of: |
| 37 | + - "text": Use only text features (CatBoost's BoW encoding). |
| 38 | + - "embedding": Use only embedding features. |
| 39 | + - "both": Use both text and embedding features. |
| 40 | +
|
| 41 | + use_embedding_features: If True, the model uses CatBoost `embedding_features` otherwise |
| 42 | + each number will be in separate column. |
| 43 | +
|
| 44 | + loss_function: CatBoost loss function. If None, an appropriate loss is |
| 45 | + chosen automatically from the task type. |
| 46 | +
|
| 47 | + verbose: If True, CatBoost prints training progress. |
| 48 | +
|
| 49 | + val_fraction: fraction of training data used for early stopping. Set to None to disaple early stopping. |
| 50 | + Note: early stopping is not supported with multilabel classification. |
| 51 | +
|
| 52 | + early_stopping_rounds: number of iterations without metric increasing waiting for early stopping. |
| 53 | + Ignored when ``val_fraction`` is ``None``. |
| 54 | +
|
| 55 | + **catboost_kwargs: Any additional keyword arguments forwarded to |
| 56 | + :class:`catboost.CatBoostClassifier`. Please refer to |
| 57 | + `catboost's documentation <https://catboost.ai/docs/en/concepts/python-reference_catboostclassifier>`_ |
| 58 | +
|
| 59 | + Example: |
| 60 | + ------- |
| 61 | +
|
| 62 | + .. testcode:: |
| 63 | +
|
| 64 | + from autointent.modules import CatBoostScorer |
| 65 | +
|
| 66 | + scorer = CatBoostScorer( |
| 67 | + iterations=50, |
| 68 | + learning_rate=0.05, |
| 69 | + depth=6, |
| 70 | + l2_leaf_reg=3, |
| 71 | + eval_metric="Accuracy", |
| 72 | + random_seed=42, |
| 73 | + verbose=False, |
| 74 | + features_type="embedding", # or "text" or "both" |
| 75 | + ) |
| 76 | + utterances = ["hello", "goodbye", "allo", "sayonara"] |
| 77 | + labels = [0, 1, 0, 1] |
| 78 | + scorer.fit(utterances, labels) |
| 79 | + test_utterances = ["hi", "bye"] |
| 80 | + probabilities = scorer.predict(test_utterances) |
| 81 | + print(probabilities) |
| 82 | +
|
| 83 | + .. testoutput:: |
| 84 | +
|
| 85 | + [[0.41493207 0.58506793] |
| 86 | + [0.55036046 0.44963954]] |
| 87 | +
|
| 88 | + """ |
| 89 | + |
| 90 | + name = "catboost" |
| 91 | + supports_multiclass = True |
| 92 | + supports_multilabel = True |
| 93 | + |
| 94 | + _model: CatBoostClassifier |
| 95 | + |
| 96 | + encoder_features_types = (FeaturesType.EMBEDDING, FeaturesType.BOTH) |
| 97 | + |
| 98 | + def __init__( |
| 99 | + self, |
| 100 | + embedder_config: EmbedderConfig | str | dict[str, Any] | None = None, |
| 101 | + features_type: FeaturesType = FeaturesType.BOTH, |
| 102 | + use_embedding_features: bool = True, |
| 103 | + loss_function: str | None = None, |
| 104 | + verbose: bool = False, |
| 105 | + val_fraction: float | None = 0.2, |
| 106 | + early_stopping_rounds: int = 100, |
| 107 | + **catboost_kwargs: dict[str, Any], |
| 108 | + ) -> None: |
| 109 | + self.val_fraction = val_fraction |
| 110 | + self.early_stopping_rounds = early_stopping_rounds |
| 111 | + self.features_type = features_type |
| 112 | + self.use_embedding_features = use_embedding_features |
| 113 | + if features_type == FeaturesType.TEXT and use_embedding_features: |
| 114 | + msg = "Only catbooost text features will be used, `use_embedding_features` is ignored." |
| 115 | + logger.warning(msg) |
| 116 | + |
| 117 | + self.embedder_config = EmbedderConfig.from_search_config(embedder_config) |
| 118 | + self.loss_function = loss_function |
| 119 | + self.verbose = verbose |
| 120 | + self.catboost_kwargs = catboost_kwargs or {} |
| 121 | + |
| 122 | + @classmethod |
| 123 | + def from_context( |
| 124 | + cls, |
| 125 | + context: Context, |
| 126 | + embedder_config: EmbedderConfig | str | dict[str, Any] | None = None, |
| 127 | + features_type: FeaturesType = FeaturesType.BOTH, |
| 128 | + use_embedding_features: bool = True, |
| 129 | + loss_function: str | None = None, |
| 130 | + verbose: bool = False, |
| 131 | + val_fraction: FloatFromZeroToOne | None = 0.2, |
| 132 | + early_stopping_rounds: int = 100, |
| 133 | + **catboost_kwargs: dict[str, Any], |
| 134 | + ) -> "CatBoostScorer": |
| 135 | + if embedder_config is None: |
| 136 | + embedder_config = context.resolve_embedder() |
| 137 | + return cls( |
| 138 | + embedder_config=embedder_config, |
| 139 | + loss_function=loss_function, |
| 140 | + verbose=verbose, |
| 141 | + features_type=features_type, |
| 142 | + use_embedding_features=use_embedding_features, |
| 143 | + val_fraction=val_fraction, |
| 144 | + early_stopping_rounds=early_stopping_rounds, |
| 145 | + **catboost_kwargs, |
| 146 | + ) |
| 147 | + |
| 148 | + def get_implicit_initialization_params(self) -> dict[str, Any]: |
| 149 | + return { |
| 150 | + "embedder_config": self.embedder_config.model_dump() |
| 151 | + if self.features_type in self.encoder_features_types |
| 152 | + else None, |
| 153 | + } |
| 154 | + |
| 155 | + def _prepare_data_for_fit( |
| 156 | + self, |
| 157 | + utterances: list[str], |
| 158 | + ) -> pd.DataFrame: |
| 159 | + if self.features_type in self.encoder_features_types: |
| 160 | + encoded_utterances = self._embedder.embed(utterances, TaskTypeEnum.classification).tolist() |
| 161 | + if self.use_embedding_features: |
| 162 | + data = pd.DataFrame({"embedding": encoded_utterances}) |
| 163 | + else: |
| 164 | + data = pd.DataFrame(np.array(encoded_utterances)) |
| 165 | + if self.features_type == FeaturesType.BOTH: |
| 166 | + data["text"] = utterances |
| 167 | + else: |
| 168 | + data = pd.DataFrame({"text": utterances}) |
| 169 | + |
| 170 | + return data |
| 171 | + |
| 172 | + def get_extra_params(self) -> dict[str, Any]: |
| 173 | + extra_params = {} |
| 174 | + if self.features_type == FeaturesType.EMBEDDING: |
| 175 | + if self.use_embedding_features: # to not raise error if embedding without embedding_features |
| 176 | + extra_params["embedding_features"] = ["embedding"] |
| 177 | + elif self.features_type in {FeaturesType.TEXT, FeaturesType.BOTH}: |
| 178 | + extra_params["text_features"] = ["text"] |
| 179 | + if self.features_type == FeaturesType.BOTH and self.use_embedding_features: |
| 180 | + extra_params["embedding_features"] = ["embedding"] |
| 181 | + else: |
| 182 | + msg = f"Unsupported features type: {self.features_type}" |
| 183 | + raise ValueError(msg) |
| 184 | + return extra_params |
| 185 | + |
| 186 | + def fit( |
| 187 | + self, |
| 188 | + utterances: list[str], |
| 189 | + labels: ListOfLabels, |
| 190 | + ) -> None: |
| 191 | + self._validate_task(labels) |
| 192 | + |
| 193 | + if self.features_type in self.encoder_features_types: |
| 194 | + self._embedder = Embedder(self.embedder_config) |
| 195 | + |
| 196 | + dataset = self._prepare_data_for_fit(utterances) |
| 197 | + |
| 198 | + default_loss = ( |
| 199 | + "MultiLogloss" if self._multilabel else ("MultiClass" if self._n_classes > 2 else "Logloss") # noqa: PLR2004 |
| 200 | + ) |
| 201 | + |
| 202 | + if self._multilabel: |
| 203 | + self.val_fraction = None |
| 204 | + msg = "Disabling early stopping in CatBoostClassifier as it is not supported with multi-label task." |
| 205 | + logger.warning(msg) |
| 206 | + |
| 207 | + self._model = CatBoostClassifier( |
| 208 | + loss_function=self.loss_function or default_loss, |
| 209 | + verbose=self.verbose, |
| 210 | + allow_writing_files=False, |
| 211 | + eval_fraction=self.val_fraction, |
| 212 | + **self.catboost_kwargs, |
| 213 | + **self.get_extra_params(), |
| 214 | + ) |
| 215 | + self._model.fit( |
| 216 | + dataset, labels, early_stopping_rounds=self.early_stopping_rounds if self.val_fraction is not None else None |
| 217 | + ) |
| 218 | + |
| 219 | + def predict(self, utterances: list[str]) -> npt.NDArray[np.float64]: |
| 220 | + if getattr(self, "_model", None) is None: |
| 221 | + msg = "Model is not trained. Call fit() first." |
| 222 | + raise RuntimeError(msg) |
| 223 | + data = self._prepare_data_for_fit(utterances) |
| 224 | + return cast("npt.NDArray[np.float64]", self._model.predict_proba(data)) |
| 225 | + |
| 226 | + def clear_cache(self) -> None: |
| 227 | + if hasattr(self, "_model"): |
| 228 | + del self._model |
| 229 | + if hasattr(self, "_embedder"): |
| 230 | + del self._embedder |
0 commit comments