|
| 1 | +import logging |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +import numpy.typing as npt |
| 6 | +from sklearn.linear_model import LogisticRegression |
| 7 | +from sklearn.multioutput import MultiOutputClassifier |
| 8 | +from sklearn.utils import all_estimators |
| 9 | +from typing_extensions import Self |
| 10 | + |
| 11 | +from autointent import Context, Embedder |
| 12 | +from autointent.custom_types import LabelType |
| 13 | +from autointent.modules.abc import ScoringModule |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | +AVAILABLE_CLASSIFIERS = { |
| 17 | + name: class_ |
| 18 | + for name, class_ in all_estimators( |
| 19 | + type_filter=[ |
| 20 | + # remove transformer (e.g. TfidfTransformer) from the list of available classifiers |
| 21 | + "classifier", |
| 22 | + "regressor", |
| 23 | + "cluster", |
| 24 | + ] |
| 25 | + ) |
| 26 | + if hasattr(class_, "predict_proba") |
| 27 | +} |
| 28 | + |
| 29 | + |
| 30 | +class SklearnScorer(ScoringModule): |
| 31 | + """ |
| 32 | + Scoring module for classification using sklearn classifiers with implemented predict_proba() method. |
| 33 | +
|
| 34 | + This module uses embeddings generated from a transformer model to train |
| 35 | + chosen sklearn classifier for intent classification. |
| 36 | +
|
| 37 | + :ivar name: Name of the scorer, defaults to "linear". |
| 38 | + """ |
| 39 | + |
| 40 | + name = "sklearn" |
| 41 | + |
| 42 | + def __init__( |
| 43 | + self, |
| 44 | + embedder_name: str, |
| 45 | + clf_name: str, |
| 46 | + embedder_batch_size: int = 32, |
| 47 | + embedder_max_length: int | None = None, |
| 48 | + embedder_device: str = "cpu", |
| 49 | + embedder_use_cache: bool = True, |
| 50 | + clf_args: dict[str, Any] | None = None, |
| 51 | + ) -> None: |
| 52 | + """ |
| 53 | + Initialize the SklearnScorer. |
| 54 | +
|
| 55 | + :param embedder_name: Name of the embedder model. |
| 56 | + :param clf_name: Name of the sklearn classifier to use. |
| 57 | + :param clf_args: dictionary with the chosen sklearn classifier arguments, defaults to {}. |
| 58 | + :param embedder_batch_size: Batch size for embedding generation, defaults to 32. |
| 59 | + :param embedder_max_length: Maximum sequence length for embedding, or None for default. |
| 60 | + :param embedder_device: Device to run operations on, e.g., "cpu" or "cuda". |
| 61 | + :param embedder_use_cache: Flag indicating whether to cache intermediate embeddings. |
| 62 | + """ |
| 63 | + self.embedder_name = embedder_name |
| 64 | + self.clf_name = clf_name |
| 65 | + self.clf_args = clf_args or {} |
| 66 | + self.embedder_batch_size = embedder_batch_size |
| 67 | + self.embedder_max_length = embedder_max_length |
| 68 | + self.embedder_device = embedder_device |
| 69 | + self.embedder_use_cache = embedder_use_cache |
| 70 | + |
| 71 | + @classmethod |
| 72 | + def from_context( |
| 73 | + cls, |
| 74 | + context: Context, |
| 75 | + clf_name: str = LogisticRegression.__name__, |
| 76 | + clf_args: dict[str, Any] | None = None, |
| 77 | + embedder_name: str | None = None, |
| 78 | + ) -> Self: |
| 79 | + """ |
| 80 | + Create a SklearnScorer instance using a Context object. |
| 81 | +
|
| 82 | + :param context: Context containing configurations and utilities. |
| 83 | + :param clf_name: Name of the sklearn classifier to use. |
| 84 | + :param clf_args: dictionary with the chosen sklearn classifier arguments, defaults to {}. |
| 85 | + :param embedder_name: Name of the embedder, or None to use the best embedder. |
| 86 | + :return: Initialized SklearnScorer instance. |
| 87 | + """ |
| 88 | + if embedder_name is None: |
| 89 | + embedder_name = context.optimization_info.get_best_embedder() |
| 90 | + |
| 91 | + return cls( |
| 92 | + embedder_name=embedder_name, |
| 93 | + embedder_device=context.get_device(), |
| 94 | + embedder_batch_size=context.get_batch_size(), |
| 95 | + embedder_max_length=context.get_max_length(), |
| 96 | + embedder_use_cache=context.get_use_cache(), |
| 97 | + clf_name=clf_name, |
| 98 | + clf_args=clf_args, |
| 99 | + ) |
| 100 | + |
| 101 | + def fit( |
| 102 | + self, |
| 103 | + utterances: list[str], |
| 104 | + labels: list[LabelType], |
| 105 | + ) -> None: |
| 106 | + """ |
| 107 | + Train the chosen sklearn classifier. |
| 108 | +
|
| 109 | + :param utterances: List of training utterances. |
| 110 | + :param labels: List of labels corresponding to the utterances. |
| 111 | + :raises ValueError: If the vector index mismatches the provided utterances. |
| 112 | + """ |
| 113 | + self._multilabel = isinstance(labels[0], list) |
| 114 | + |
| 115 | + embedder = Embedder( |
| 116 | + device=self.embedder_device, |
| 117 | + model_name_or_path=self.embedder_name, |
| 118 | + batch_size=self.embedder_batch_size, |
| 119 | + max_length=self.embedder_max_length, |
| 120 | + use_cache=self.embedder_use_cache, |
| 121 | + ) |
| 122 | + features = embedder.embed(utterances) |
| 123 | + if AVAILABLE_CLASSIFIERS.get(self.clf_name): |
| 124 | + base_clf = AVAILABLE_CLASSIFIERS[self.clf_name](**self.clf_args) |
| 125 | + else: |
| 126 | + msg = f"Class {self.clf_name} does not exist in sklearn or does not have predict_proba method" |
| 127 | + logger.error(msg) |
| 128 | + raise ValueError(msg) |
| 129 | + |
| 130 | + clf = MultiOutputClassifier(base_clf) if self._multilabel else base_clf |
| 131 | + |
| 132 | + clf.fit(features, labels) |
| 133 | + |
| 134 | + self._clf = clf |
| 135 | + self._embedder = embedder |
| 136 | + |
| 137 | + def predict(self, utterances: list[str]) -> npt.NDArray[Any]: |
| 138 | + """ |
| 139 | + Predict probabilities for the given utterances. |
| 140 | +
|
| 141 | + :param utterances: List of query utterances. |
| 142 | + :return: Array of predicted probabilities for each class. |
| 143 | + """ |
| 144 | + features = self._embedder.embed(utterances) |
| 145 | + probas = self._clf.predict_proba(features) |
| 146 | + if self._multilabel: |
| 147 | + probas = np.stack(probas, axis=1)[..., 1] |
| 148 | + return probas # type: ignore[no-any-return] |
| 149 | + |
| 150 | + def clear_cache(self) -> None: |
| 151 | + """Clear cached data in memory used by the embedder.""" |
| 152 | + self._embedder.delete() |
0 commit comments