


'''simple docstring'''

import warnings

from ...utils import is_sklearn_available, requires_backends


if is_sklearn_available():
 from scipy.stats import pearsonr, spearmanr
 from sklearn.metrics import fa_score, matthews_corrcoef


lowerCamelCase				:  Tuple    		=      (
    'This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate '
    'library. You can have a look at this example script for pointers: '
    'https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py'
)

def _SCREAMING_SNAKE_CASE (A    ,					A			)			->			Optional[Any]:






       """simple docstring"""







       warnings.warn(A    ,					A			)
       requires_backends(A    ,					'''sklearn'''			)
       return (preds == labels).mean()

def _SCREAMING_SNAKE_CASE (A    ,					A			)			->			Tuple:






       """simple docstring"""







       warnings.warn(A    ,					A			)
       requires_backends(A    ,					'''sklearn'''			)
       lowercase__      =					simple_accuracy(A    ,					A			)
       lowercase__      =					fa_score(y_true=A    ,					y_pred=A			)
       return {
           "acc": acc,
           "f1": fa,
           "acc_and_f1": (acc + fa) / 2,
       }

def _SCREAMING_SNAKE_CASE (A    ,					A			)			->			List[str]:






       """simple docstring"""







       warnings.warn(A    ,					A			)
       requires_backends(A    ,					'''sklearn'''			)
       lowercase__      =					pearsonr(A    ,					A			)[0]
       lowercase__      =					spearmanr(A    ,					A			)[0]
       return {
           "pearson": pearson_corr,
           "spearmanr": spearman_corr,
           "corr": (pearson_corr + spearman_corr) / 2,
       }

def _SCREAMING_SNAKE_CASE (A    ,					A    ,					A			)			->			Dict:






       """simple docstring"""







       warnings.warn(A    ,					A			)
       requires_backends(A    ,					'''sklearn'''			)
       assert len(A			) == len(A			), f"Predictions and labels have mismatched lengths {len(A			)} and {len(A			)}"
       if task_name == "cola":
              return {"mcc": matthews_corrcoef(A    ,					A			)}
       elif task_name == "sst-2":
              return {"acc": simple_accuracy(A    ,					A			)}
       elif task_name == "mrpc":
              return acc_and_fa(A    ,					A			)
       elif task_name == "sts-b":
              return pearson_and_spearman(A    ,					A			)
       elif task_name == "qqp":
              return acc_and_fa(A    ,					A			)
       elif task_name == "mnli":
              return {"mnli/acc": simple_accuracy(A    ,					A			)}
       elif task_name == "mnli-mm":
              return {"mnli-mm/acc": simple_accuracy(A    ,					A			)}
       elif task_name == "qnli":
              return {"acc": simple_accuracy(A    ,					A			)}
       elif task_name == "rte":
              return {"acc": simple_accuracy(A    ,					A			)}
       elif task_name == "wnli":
              return {"acc": simple_accuracy(A    ,					A			)}
       elif task_name == "hans":
              return {"acc": simple_accuracy(A    ,					A			)}
       else:
              raise KeyError(A			)

def _SCREAMING_SNAKE_CASE (A    ,					A    ,					A			)			->			Optional[int]:






       """simple docstring"""







       warnings.warn(A    ,					A			)
       requires_backends(A    ,					'''sklearn'''			)
       if len(A			) != len(A			):
              raise ValueError(f"Predictions and labels have mismatched lengths {len(A			)} and {len(A			)}"			)
       if task_name == "xnli":
              return {"acc": simple_accuracy(A    ,					A			)}
       else:
              raise KeyError(A			)








'''simple docstring'''

# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
 import torch
class     __lowerCAmelCase		(TensorFormatter[Mapping, """torch.Tensor""", Mapping]	):





      '''simple docstring'''






      def __init__(self       :       Optional[Any]  ,		UpperCamelCase       :       Tuple=None  ,		**UpperCamelCase       :       List[str]					):

             '''simple docstring'''







             super().__init__(features=UpperCamelCase					)
             lowercase__      =					torch_tensor_kwargs
             import torch  # noqa import torch at initialization



      def  UpperCamelCase__						(self       :       List[str]  ,		UpperCamelCase       :       Union[str, Any]					):

             '''simple docstring'''







             import torch

             if isinstance(UpperCamelCase  ,		UpperCamelCase					) and column:
                    if all(
                        isinstance(UpperCamelCase  ,		torch.Tensor					) and x.shape == column[0].shape and x.dtype == column[0].dtype
                        for x in column					):
                           return torch.stack(UpperCamelCase					)
             return column



      def  UpperCamelCase__						(self       :       List[Any]  ,		UpperCamelCase       :       Optional[Any]					):

             '''simple docstring'''







             import torch

             if isinstance(UpperCamelCase  ,		(str, bytes, type(UpperCamelCase					))					):
                    return value
             elif isinstance(UpperCamelCase  ,		(np.character, np.ndarray)					) and np.issubdtype(value.dtype  ,		np.character					):
                    return value.tolist()

             lowercase__      =					{}

             if isinstance(UpperCamelCase  ,		(np.number, np.ndarray)					) and np.issubdtype(value.dtype  ,		np.integer					):
                    lowercase__      =					{'''dtype''': torch.intaa}
             elif isinstance(UpperCamelCase  ,		(np.number, np.ndarray)					) and np.issubdtype(value.dtype  ,		np.floating					):
                    lowercase__      =					{'''dtype''': torch.floataa}
             elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                    import PIL.Image

                    if isinstance(UpperCamelCase  ,		PIL.Image.Image					):
                           lowercase__      =					np.asarray(UpperCamelCase					)
             return torch.tensor(UpperCamelCase  ,		**{**default_dtype, **self.torch_tensor_kwargs}					)



      def  UpperCamelCase__						(self       :       Optional[int]  ,		UpperCamelCase       :       Dict					):

             '''simple docstring'''







             import torch

             # support for torch, tf, jax etc.
             if hasattr(UpperCamelCase  ,		'''__array__'''					) and not isinstance(UpperCamelCase  ,		torch.Tensor					):
                    lowercase__      =					data_struct.__array__()
             # support for nested types like struct of list of struct
             if isinstance(UpperCamelCase  ,		np.ndarray					):
                    if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
                           return self._consolidate([self.recursive_tensorize(UpperCamelCase					) for substruct in data_struct]					)
             elif isinstance(UpperCamelCase  ,		(list, tuple)					):
                    return self._consolidate([self.recursive_tensorize(UpperCamelCase					) for substruct in data_struct]					)
             return self._tensorize(UpperCamelCase					)



      def  UpperCamelCase__						(self       :       List[str]  ,		UpperCamelCase       :       dict					):

             '''simple docstring'''







             return map_nested(self._recursive_tensorize  ,		UpperCamelCase  ,		map_list=UpperCamelCase					)



      def  UpperCamelCase__						(self       :       Dict  ,		UpperCamelCase       :       pa.Table					):

             '''simple docstring'''







             lowercase__      =					self.numpy_arrow_extractor().extract_row(UpperCamelCase					)
             lowercase__      =					self.python_features_decoder.decode_row(UpperCamelCase					)
             return self.recursive_tensorize(UpperCamelCase					)



      def  UpperCamelCase__						(self       :       List[Any]  ,		UpperCamelCase       :       pa.Table					):

             '''simple docstring'''







             lowercase__      =					self.numpy_arrow_extractor().extract_column(UpperCamelCase					)
             lowercase__      =					self.python_features_decoder.decode_column(UpperCamelCase  ,		pa_table.column_names[0]					)
             lowercase__      =					self.recursive_tensorize(UpperCamelCase					)
             lowercase__      =					self._consolidate(UpperCamelCase					)
             return column






      def  UpperCamelCase__						(self       :       Tuple  ,		UpperCamelCase       :       pa.Table					):

             '''simple docstring'''







             lowercase__      =					self.numpy_arrow_extractor().extract_batch(UpperCamelCase					)
             lowercase__      =					self.python_features_decoder.decode_batch(UpperCamelCase					)
             lowercase__      =					self.recursive_tensorize(UpperCamelCase					)
             for column_name in batch:
                    lowercase__      =					self._consolidate(batch[column_name]					)
             return batch




