text_classification.py 11 KB

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