





from sklearn.metrics import recall_score

import datasets


__lowerCAmelCase :int     =    '\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n'


__lowerCAmelCase :Union[str, Any]     =    '\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the \'positive class\' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n    - `\'binary\'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n    - `\'micro\'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n    - `\'macro\'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n    - `\'weighted\'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.\n    - `\'samples\'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n    - `\'warn\'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n    - `0`: If there is a zero division, the return value is `0`.\n    - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n    Example 1-A simple example with some errors\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n        >>> print(results)\n        {\'recall\': 0.6666666666666666}\n\n    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n        >>> print(results)\n        {\'recall\': 0.5}\n\n    Example 3-The same example as Example 1, but with `sample_weight` included.\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n        >>> print(results)\n        {\'recall\': 0.55}\n\n    Example 4-A multiclass example, using different averages.\n        >>> recall_metric = datasets.load_metric(\'recall\')\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'macro\')\n        >>> print(results)\n        {\'recall\': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'micro\')\n        >>> print(results)\n        {\'recall\': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'weighted\')\n        >>> print(results)\n        {\'recall\': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {\'recall\': array([1., 0., 0.])}\n'


__lowerCAmelCase :List[Any]     =    '\n@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}\n'






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,   _KWARGS_DESCRIPTION    )
class        _a(    datasets.Metric    ):







		def        lowercase       (    self				)      ->      List[Any]:


							'''simple docstring'''

							return datasets.MetricInfo(
							    description=_DESCRIPTION ,						citation=_CITATION ,						inputs_description=_KWARGS_DESCRIPTION ,						features=datasets.Features(
							        {
							            "predictions": datasets.Sequence(datasets.Value("int32"				)				),
							            "references": datasets.Sequence(datasets.Value("int32"				)				),
							        }
							        if self.config_name == "multilabel"
							        else {
							            "predictions": datasets.Value("int32"				),
							            "references": datasets.Value("int32"				),
							        }				) ,						reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"] ,						)







		def        lowercase       (    self ,						__snake_case ,						__snake_case ,						__snake_case=None ,						__snake_case=1 ,						__snake_case="binary" ,						__snake_case=None ,						__snake_case="warn" ,						)      ->      str:


							'''simple docstring'''

							_snake_case       :					Optional[int]				       =   recall_score(
							    __snake_case ,						__snake_case ,						labels=__snake_case ,						pos_label=__snake_case ,						average=__snake_case ,						sample_weight=__snake_case ,						zero_division=__snake_case ,						)
							return {"recall": float(__snake_case				) if score.size == 1 else score}






import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


__lowerCAmelCase :Tuple     =    logging.get_logger(__name__)






@dataclass
class        _a:
		lowerCamelCase__     :str   				=		field(metadata={'help': 'The name of the task to train on: ' + ', '.join(glue_processors.keys()    )}    )
		lowerCamelCase__     :str   				=		field(
		    metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'}    )
		lowerCamelCase__     :int   				=		field(
		    default=128	,   metadata={
		        'help': (
		            'The maximum total input sequence length after tokenization. Sequences longer '
		            'than this will be truncated, sequences shorter will be padded.'
		        )
		    }	,   )
		lowerCamelCase__     :bool   				=		field(
		    default=__A	,   metadata={'help': 'Overwrite the cached training and evaluation sets'}    )







		def        lowercase       (    self				)      ->      Optional[Any]:


							'''simple docstring'''

							_snake_case       :					Dict				       =   self.task_name.lower()






class        _a(    __A    ):
		lowerCamelCase__     :Optional[Any]   				=		'train'
		lowerCamelCase__     :List[str]   				=		'dev'
		lowerCamelCase__     :Any   				=		'test'






class        _a(    __A    ):
		lowerCamelCase__     :GlueDataTrainingArguments
		lowerCamelCase__     :str
		lowerCamelCase__     :List[InputFeatures]







		def __init__(    self ,						__snake_case ,						__snake_case ,						__snake_case = None ,						__snake_case = Split.train ,						__snake_case = None ,						)      ->      Any:


							'''simple docstring'''

							warnings.warn(
							    "This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets "
							    "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" ,						__snake_case ,						)
							_snake_case       :					Optional[Any]				       =   args
							_snake_case       :					Optional[int]				       =   glue_processors[args.task_name]()
							_snake_case       :					int				       =   glue_output_modes[args.task_name]
							if isinstance(__snake_case ,						__snake_case				):
												try:
																	_snake_case       :					Tuple				       =   Split[mode]
												except KeyError:
																	raise KeyError("mode is not a valid split name"				)
        # Load data features from cache or dataset file
							_snake_case       :					List[str]				       =   os.path.join(
							    cache_dir if cache_dir is not None else args.data_dir ,						f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}""" ,						)
							_snake_case       :					List[Any]				       =   self.processor.get_labels()
							if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
							    "RobertaTokenizer",
							    "RobertaTokenizerFast",
							    "XLMRobertaTokenizer",
							    "BartTokenizer",
							    "BartTokenizerFast",
							):
												# HACK(label indices are swapped in RoBERTa pretrained model)
												_snake_case       , _snake_case       :					int				       =   label_list[2], label_list[1]
							_snake_case       :					str				       =   label_list

							# Make sure only the first process in distributed training processes the dataset,
							# and the others will use the cache.
							_snake_case       :					Optional[Any]				       =   cached_features_file + ".lock"
							with FileLock(__snake_case				):
												if os.path.exists(__snake_case				) and not args.overwrite_cache:
																	_snake_case       :					List[str]				       =   time.time()
																	_snake_case       :					str				       =   torch.load(__snake_case				)
																	logger.info(
																	    f"""Loading features from cached file {cached_features_file} [took %.3f s]""" ,						time.time() - start				)
												else:
																	logger.info(f"""Creating features from dataset file at {args.data_dir}"""				)

																	if mode == Split.dev:
																						_snake_case       :					List[Any]				       =   self.processor.get_dev_examples(args.data_dir				)
																	elif mode == Split.test:
																						_snake_case       :					List[Any]				       =   self.processor.get_test_examples(args.data_dir				)
																	else:
																						_snake_case       :					str				       =   self.processor.get_train_examples(args.data_dir				)
																	if limit_length is not None:
																						_snake_case       :					Tuple				       =   examples[:limit_length]
																	_snake_case       :					List[str]				       =   glue_convert_examples_to_features(
																	    __snake_case ,						__snake_case ,						max_length=args.max_seq_length ,						label_list=__snake_case ,						output_mode=self.output_mode ,						)
																	_snake_case       :					Optional[Any]				       =   time.time()
																	torch.save(self.features ,						__snake_case				)
																	# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
																	logger.info(
																	    f"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"""				)







		def __len__(    self				)      ->      List[str]:


							'''simple docstring'''

							return len(self.features				)







		def __getitem__(    self ,						__snake_case				)      ->      InputFeatures:


							'''simple docstring'''

							return self.features[i]







		def        lowercase       (    self				)      ->      Optional[Any]:


							'''simple docstring'''

							return self.label_list