text_classification.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. import inspect
  2. from typing import Any
  3. import numpy as np
  4. from ..utils import ExplicitEnum, add_end_docstrings, is_torch_available
  5. from .base import GenericTensor, Pipeline, build_pipeline_init_args
  6. if is_torch_available():
  7. from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
  8. def sigmoid(_outputs):
  9. return 1.0 / (1.0 + np.exp(-_outputs))
  10. def softmax(_outputs):
  11. maxes = np.max(_outputs, axis=-1, keepdims=True)
  12. shifted_exp = np.exp(_outputs - maxes)
  13. return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
  14. class ClassificationFunction(ExplicitEnum):
  15. SIGMOID = "sigmoid"
  16. SOFTMAX = "softmax"
  17. NONE = "none"
  18. @add_end_docstrings(
  19. build_pipeline_init_args(has_tokenizer=True),
  20. r"""
  21. function_to_apply (`str`, *optional*, defaults to `"default"`):
  22. The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:
  23. - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
  24. has several labels, will apply the softmax function on the output. In case of regression tasks, will not
  25. apply any function on the output.
  26. - `"sigmoid"`: Applies the sigmoid function on the output.
  27. - `"softmax"`: Applies the softmax function on the output.
  28. - `"none"`: Does not apply any function on the output.""",
  29. )
  30. class TextClassificationPipeline(Pipeline):
  31. """
  32. Text classification pipeline using any `ModelForSequenceClassification`. See the [sequence classification
  33. examples](../task_summary#sequence-classification) for more information.
  34. Example:
  35. ```python
  36. >>> from transformers import pipeline
  37. >>> classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
  38. >>> classifier("This movie is disgustingly good !")
  39. [{'label': 'POSITIVE', 'score': 1.0}]
  40. >>> classifier("Director tried too much.")
  41. [{'label': 'NEGATIVE', 'score': 0.996}]
  42. ```
  43. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
  44. This text classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
  45. `"sentiment-analysis"` (for classifying sequences according to positive or negative sentiments).
  46. If multiple classification labels are available (`model.config.num_labels >= 2`), the pipeline will run a softmax
  47. over the results. If there is a single label, the pipeline will run a sigmoid over the result. In case of regression
  48. tasks (`model.config.problem_type == "regression"`), will not apply any function on the output.
  49. The models that this pipeline can use are models that have been fine-tuned on a sequence classification task. See
  50. the up-to-date list of available models on
  51. [huggingface.co/models](https://huggingface.co/models?filter=text-classification).
  52. """
  53. _load_processor = False
  54. _load_image_processor = False
  55. _load_feature_extractor = False
  56. _load_tokenizer = True
  57. function_to_apply = ClassificationFunction.NONE
  58. def __init__(self, **kwargs):
  59. super().__init__(**kwargs)
  60. self.check_model_type(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES)
  61. def _sanitize_parameters(self, function_to_apply=None, top_k="", **tokenizer_kwargs):
  62. # Using "" as default argument because we're going to use `top_k=None` in user code to declare
  63. # "No top_k"
  64. preprocess_params = tokenizer_kwargs
  65. postprocess_params = {}
  66. if isinstance(top_k, int) or top_k is None:
  67. postprocess_params["top_k"] = top_k
  68. postprocess_params["_legacy"] = False
  69. if isinstance(function_to_apply, str):
  70. function_to_apply = ClassificationFunction[function_to_apply.upper()]
  71. if function_to_apply is not None:
  72. postprocess_params["function_to_apply"] = function_to_apply
  73. return preprocess_params, {}, postprocess_params
  74. def __call__(
  75. self,
  76. inputs: str | list[str] | dict[str, str] | list[dict[str, str]],
  77. **kwargs: Any,
  78. ) -> list[dict[str, Any]]:
  79. """
  80. Classify the text(s) given as inputs.
  81. Args:
  82. inputs (`str` or `list[str]` or `dict[str]`, or `list[dict[str]]`):
  83. One or several texts to classify. In order to use text pairs for your classification, you can send a
  84. dictionary containing `{"text", "text_pair"}` keys, or a list of those.
  85. top_k (`int`, *optional*, defaults to `1`):
  86. How many results to return.
  87. function_to_apply (`str`, *optional*, defaults to `"default"`):
  88. The function to apply to the model outputs in order to retrieve the scores. Accepts four different
  89. values:
  90. If this argument is not specified, then it will apply the following functions according to the number
  91. of labels:
  92. - If problem type is regression, will not apply any function on the output.
  93. - If the model has a single label, will apply the sigmoid function on the output.
  94. - If the model has several labels, will apply the softmax function on the output.
  95. Possible values are:
  96. - `"sigmoid"`: Applies the sigmoid function on the output.
  97. - `"softmax"`: Applies the softmax function on the output.
  98. - `"none"`: Does not apply any function on the output.
  99. Return:
  100. A list of `dict`: Each result comes as list of dictionaries with the following keys:
  101. - **label** (`str`) -- The label predicted.
  102. - **score** (`float`) -- The corresponding probability.
  103. If `top_k` is used, one such dictionary is returned per label.
  104. """
  105. inputs = (inputs,)
  106. result = super().__call__(*inputs, **kwargs)
  107. # TODO try and retrieve it in a nicer way from _sanitize_parameters.
  108. _legacy = "top_k" not in kwargs
  109. if isinstance(inputs[0], str) and _legacy:
  110. # This pipeline is odd, and return a list when single item is run
  111. return [result]
  112. else:
  113. return result
  114. def preprocess(self, inputs, **tokenizer_kwargs) -> dict[str, GenericTensor]:
  115. return_tensors = "pt"
  116. if isinstance(inputs, dict):
  117. return self.tokenizer(**inputs, return_tensors=return_tensors, **tokenizer_kwargs)
  118. elif isinstance(inputs, list) and len(inputs) == 1 and isinstance(inputs[0], list) and len(inputs[0]) == 2:
  119. # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
  120. return self.tokenizer(
  121. text=inputs[0][0], text_pair=inputs[0][1], return_tensors=return_tensors, **tokenizer_kwargs
  122. )
  123. elif isinstance(inputs, list):
  124. # This is likely an invalid usage of the pipeline attempting to pass text pairs.
  125. raise ValueError(
  126. "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a"
  127. ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'
  128. )
  129. return self.tokenizer(inputs, return_tensors=return_tensors, **tokenizer_kwargs)
  130. def _forward(self, model_inputs):
  131. # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported
  132. model_forward = self.model.forward
  133. if "use_cache" in inspect.signature(model_forward).parameters:
  134. model_inputs["use_cache"] = False
  135. return self.model(**model_inputs)
  136. def postprocess(self, model_outputs, function_to_apply=None, top_k=1, _legacy=True):
  137. # `_legacy` is used to determine if we're running the naked pipeline and in backward
  138. # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
  139. # the more natural result containing the list.
  140. # Default value before `set_parameters`
  141. if function_to_apply is None:
  142. if self.model.config.problem_type == "regression":
  143. function_to_apply = ClassificationFunction.NONE
  144. elif self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
  145. function_to_apply = ClassificationFunction.SIGMOID
  146. elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
  147. function_to_apply = ClassificationFunction.SOFTMAX
  148. elif hasattr(self.model.config, "function_to_apply") and function_to_apply is None:
  149. function_to_apply = self.model.config.function_to_apply
  150. else:
  151. function_to_apply = ClassificationFunction.NONE
  152. outputs = model_outputs["logits"][0]
  153. # To enable using fp16 and bf16
  154. outputs = outputs.float().numpy()
  155. if function_to_apply == ClassificationFunction.SIGMOID:
  156. scores = sigmoid(outputs)
  157. elif function_to_apply == ClassificationFunction.SOFTMAX:
  158. scores = softmax(outputs)
  159. elif function_to_apply == ClassificationFunction.NONE:
  160. scores = outputs
  161. else:
  162. raise ValueError(f"Unrecognized `function_to_apply` argument: {function_to_apply}")
  163. if top_k == 1 and _legacy:
  164. return {"label": self.model.config.id2label[scores.argmax().item()], "score": scores.max().item()}
  165. dict_scores = [
  166. {"label": self.model.config.id2label[i], "score": score.item()} for i, score in enumerate(scores)
  167. ]
  168. if not _legacy:
  169. dict_scores.sort(key=lambda x: x["score"], reverse=True)
  170. if top_k is not None:
  171. dict_scores = dict_scores[:top_k]
  172. return dict_scores