


"""simple docstring"""
import unittest

import numpy as np

from transformers import AlbertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
			import jax.numpy as jnp

			from transformers.models.albert.modeling_flax_albert import (
			    FlaxAlbertForMaskedLM,
			    FlaxAlbertForMultipleChoice,
			    FlaxAlbertForPreTraining,
			    FlaxAlbertForQuestionAnswering,
			    FlaxAlbertForSequenceClassification,
			    FlaxAlbertForTokenClassification,
			    FlaxAlbertModel,
			)



class 			_UpperCAmelCase (							unittest.TestCase				):






		'''simple docstring'''

		def __init__(self				,       a_				,       a_=13				,       a_=7				,       a_=True				,       a_=True				,       a_=True				,       a_=True				,       a_=99				,       a_=32				,       a_=5				,       a_=4				,       a_=37				,       a_="gelu"				,       a_=0.1				,       a_=0.1				,       a_=5_12				,       a_=16				,       a_=2				,       a_=0.02				,       a_=4				,       ):





			'''simple docstring'''

			__snake_case	:						Union[str, Any]						=				parent
			__snake_case	:						Dict						=				batch_size
			__snake_case	:						Optional[int]						=				seq_length
			__snake_case	:						Tuple						=				is_training
			__snake_case	:						Optional[int]						=				use_attention_mask
			__snake_case	:						Dict						=				use_token_type_ids
			__snake_case	:						Dict						=				use_labels
			__snake_case	:						Tuple						=				vocab_size
			__snake_case	:						Tuple						=				hidden_size
			__snake_case	:						List[str]						=				num_hidden_layers
			__snake_case	:						Dict						=				num_attention_heads
			__snake_case	:						Optional[int]						=				intermediate_size
			__snake_case	:						Any						=				hidden_act
			__snake_case	:						Union[str, Any]						=				hidden_dropout_prob
			__snake_case	:						Union[str, Any]						=				attention_probs_dropout_prob
			__snake_case	:						Dict						=				max_position_embeddings
			__snake_case	:						str						=				type_vocab_size
			__snake_case	:						List[Any]						=				type_sequence_label_size
			__snake_case	:						Optional[int]						=				initializer_range
			__snake_case	:						Any						=				num_choices



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Union[str, Any]						=				ids_tensor([self.batch_size, self.seq_length]				,       self.vocab_size					)

			__snake_case	:						Union[str, Any]						=				None
			if self.use_attention_mask:
				__snake_case	:						Tuple						=				random_attention_mask([self.batch_size, self.seq_length]					)

			__snake_case	:						Optional[Any]						=				None
			if self.use_token_type_ids:
				__snake_case	:						List[Any]						=				ids_tensor([self.batch_size, self.seq_length]				,       self.type_vocab_size					)

			__snake_case	:						Tuple						=				AlbertConfig(
			    vocab_size=self.vocab_size				,       hidden_size=self.hidden_size				,       num_hidden_layers=self.num_hidden_layers				,       num_attention_heads=self.num_attention_heads				,       intermediate_size=self.intermediate_size				,       hidden_act=self.hidden_act				,       hidden_dropout_prob=self.hidden_dropout_prob				,       attention_probs_dropout_prob=self.attention_probs_dropout_prob				,       max_position_embeddings=self.max_position_embeddings				,       type_vocab_size=self.type_vocab_size				,       is_decoder=a_				,       initializer_range=self.initializer_range				,       )

			return config, input_ids, token_type_ids, attention_mask



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Dict						=				self.prepare_config_and_inputs()
			__snake_case	,							__snake_case	,							__snake_case	,							__snake_case	:						Optional[Any]						=				config_and_inputs
			__snake_case	:						Any						=				{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
			return config, inputs_dict



@require_flax
class 			_UpperCAmelCase (							__snake_case,				unittest.TestCase				):






		'''simple docstring'''

		lowerCamelCase__				=(
		    (
		        FlaxAlbertModel,
		        FlaxAlbertForPreTraining,
		        FlaxAlbertForMaskedLM,
		        FlaxAlbertForMultipleChoice,
		        FlaxAlbertForQuestionAnswering,
		        FlaxAlbertForSequenceClassification,
		        FlaxAlbertForTokenClassification,
		        FlaxAlbertForQuestionAnswering,
		    )
		    if is_flax_available()
		    else ()
		)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Dict						=				FlaxAlbertModelTester(self					)



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			for model_class_name in self.all_model_classes:
				__snake_case	:						Union[str, Any]						=				model_class_name.from_pretrained('''albert-base-v2'''					)
				__snake_case	:						Tuple						=				model(np.ones((1, 1)					)					)
				self.assertIsNotNone(a_					)



@require_flax
class 			_UpperCAmelCase (							unittest.TestCase				):






		'''simple docstring'''

		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Tuple						=				FlaxAlbertModel.from_pretrained('''albert-base-v2'''					)
			__snake_case	:						List[str]						=				np.array([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]]					)
			__snake_case	:						Tuple						=				np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]					)
			__snake_case	:						Dict						=				model(a_				,       attention_mask=a_					)[0]
			__snake_case	:						Dict						=				(1, 11, 7_68)
			self.assertEqual(output.shape				,       a_					)
			__snake_case	:						int						=				np.array(
			    [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]]					)

			self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]				,       a_				,       atol=1E-4					)					)









"""simple docstring"""
from sklearn.metrics import recall_score

import datasets


SCREAMING_SNAKE_CASE :    Dict									=				"""
Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:
Recall = TP / (TP + FN)
Where TP is the true positives and FN is the false negatives.
"""


SCREAMING_SNAKE_CASE :    Any									=				"""
Args:
- **predictions** (`list` of `int`): The predicted labels.
- **references** (`list` of `int`): The ground truth labels.
- **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.
- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.
- **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'`.
    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.
    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.
    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
    - `'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.
    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.
- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .
    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.
    - `0`: If there is a zero division, the return value is `0`.
    - `1`: If there is a zero division, the return value is `1`.

Returns:
- **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.

Examples:

    Example 1-A simple example with some errors
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])
        >>> print(results)
        {'recall': 0.6666666666666666}

    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)
        >>> print(results)
        {'recall': 0.5}

    Example 3-The same example as Example 1, but with `sample_weight` included.
        >>> recall_metric = datasets.load_metric('recall')
        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)
        >>> print(results)
        {'recall': 0.55}

    Example 4-A multiclass example, using different averages.
        >>> recall_metric = datasets.load_metric('recall')
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'recall': array([1., 0., 0.])}
"""


SCREAMING_SNAKE_CASE :    Tuple									=				"""
@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}
"""



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






		'''simple docstring'''

		def 				SCREAMING_SNAKE_CASE  (self					):





			'''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 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_				,       a_=None				,       a_=1				,       a_="binary"				,       a_=None				,       a_="warn"				,       ):





			'''simple docstring'''

			__snake_case	:						Any						=				recall_score(
			    a_				,       a_				,       labels=a_				,       pos_label=a_				,       average=a_				,       sample_weight=a_				,       zero_division=a_				,       )
			return {"recall": float(a_					) if score.size == 1 else score}





