





from sklearn.metrics import recall_score

import datasets


_lowerCamelCase			       =      '\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			       =      '\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			       =      '\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  ):




      """simple docstring"""







      def 				__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 				__snake_case			(		self      ,							a__      ,							a__      ,							a__=None      ,							a__=1      ,							a__="binary"      ,							a__=None      ,							a__="warn"      ,							):



             """simple docstring"""





             _lowerCamelCase							:     Optional[int]	=		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}








import time
from dataclasses import dataclass
from multiprocessing import Pool
from unittest import TestCase
from unittest.mock import patch

import multiprocess
import numpy as np
import pytest

from datasets.utils.py_utils import (
    NestedDataStructure,
    asdict,
    iflatmap_unordered,
    map_nested,
    temp_seed,
    temporary_assignment,
    zip_dict,
)

from .utils import require_tf, require_torch




def    __UpperCAmelCase(      lowercase_      ):  # picklable for multiprocessing
       return x.sum()




def    __UpperCAmelCase(      lowercase_      ):  # picklable for multiprocessing
       return i + 1







@dataclass
class 			__A       :




      """simple docstring"""







      UpperCAmelCase__						=      42
      UpperCAmelCase__						=      42







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Tuple	=		{}
             _lowerCamelCase							:     Dict	=		[]
             _lowerCamelCase							:     Optional[Any]	=		1
             _lowerCamelCase							:     Optional[int]	=		[1, 2]
             _lowerCamelCase							:     str	=		{'''a''': 1, '''b''': 2}
             _lowerCamelCase							:     Dict	=		{'''a''': [1, 2], '''b''': [3, 4]}
             _lowerCamelCase							:     Any	=		{'''a''': {'''1''': 1}, '''b''': 2}
             _lowerCamelCase							:     Optional[Any]	=		{'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4}
             _lowerCamelCase							:     str	=		{}
             _lowerCamelCase							:     int	=		[]
             _lowerCamelCase							:     str	=		2
             _lowerCamelCase							:     int	=		[2, 3]
             _lowerCamelCase							:     str	=		{'''a''': 2, '''b''': 3}
             _lowerCamelCase							:     Tuple	=		{'''a''': [2, 3], '''b''': [4, 5]}
             _lowerCamelCase							:     List[str]	=		{'''a''': {'''1''': 2}, '''b''': 3}
             _lowerCamelCase							:     str	=		{'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5}
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__)      ,							a__)

             _lowerCamelCase							:     Dict	=		2
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(map_nested(a__      ,							a__      ,							num_proc=a__)      ,							a__)

             _lowerCamelCase							:     Any	=		{'''a''': np.eye(2), '''b''': np.zeros(3), '''c''': np.ones(2)}
             _lowerCamelCase							:     Optional[int]	=		{'''a''': 2, '''b''': 0, '''c''': 2}
             _lowerCamelCase							:     Optional[int]	=		{
                 '''a''': np.eye(2).astype(a__),
                 '''b''': np.zeros(3).astype(a__),
                 '''c''': np.ones(2).astype(a__),
             }
             self.assertEqual(map_nested(a__      ,							a__      ,							map_numpy=a__)      ,							a__)
             self.assertEqual(
                 {k: v.tolist() for k, v in map_nested(a__      ,							a__      ,							map_numpy=a__).items()}      ,							{k: v.tolist() for k, v in expected_map_nested_sna_int.items()}      ,							)
             self.assertEqual(map_nested(a__      ,							a__      ,							map_numpy=a__      ,							num_proc=a__)      ,							a__)
             self.assertEqual(
                 {k: v.tolist() for k, v in map_nested(a__      ,							a__      ,							map_numpy=a__      ,							num_proc=a__).items()}      ,							{k: v.tolist() for k, v in expected_map_nested_sna_int.items()}      ,							)
             with self.assertRaises(a__):  # can't pickle a local lambda
                    map_nested(lambda a__: x + 1      ,							a__      ,							num_proc=a__)


      def 				__snake_case			(		self):



             """simple docstring"""





             _lowerCamelCase							:     Dict	=		{'''a''': 1, '''b''': 2}
             _lowerCamelCase							:     Optional[int]	=		{'''a''': 3, '''b''': 4}
             _lowerCamelCase							:     int	=		{'''a''': 5, '''b''': 6}
             _lowerCamelCase							:     Optional[int]	=		sorted([('''a''', (1, 3, 5)), ('''b''', (2, 4, 6))])
             self.assertEqual(sorted(zip_dict(a__      ,							a__      ,							a__))      ,							a__)



      def 				__snake_case			(		self):



             """simple docstring"""





             class 			__A       :




                   """simple docstring"""







                   UpperCAmelCase__						=      """bar"""
             _lowerCamelCase							:     Any	=		Foo()
             self.assertEqual(foo.my_attr      ,							'''bar''')
             with temporary_assignment(a__      ,							'''my_attr'''      ,							'''BAR'''):
                    self.assertEqual(foo.my_attr      ,							'''BAR''')
             self.assertEqual(foo.my_attr      ,							'''bar''')




@pytest.mark.parametrize(
    '''iterable_length, num_proc, expected_num_proc''' ,    [
        (1, None, 1),
        (1, 1, 1),
        (2, None, 1),
        (2, 1, 1),
        (2, 2, 1),
        (2, 3, 1),
        (3, 2, 1),
        (16, 16, 16),
        (16, 17, 16),
        (17, 16, 16),
    ] ,    )
def    __UpperCAmelCase(      lowercase_ ,    lowercase_ ,    lowercase_      ):
       with patch('''datasets.utils.py_utils._single_map_nested'''      ) as mock_single_map_nested, patch(
           '''datasets.parallel.parallel.Pool'''      ) as mock_multiprocessing_pool:
              _lowerCamelCase							:     Union[str, Any]	=		{F"""{i}""": i for i in range(lowercase_      )}
              _lowerCamelCase							:     List[str]	=		map_nested(lambda lowercase_      : x + 10 ,    lowercase_ ,    num_proc=lowercase_ ,    parallel_min_length=16      )
              if expected_num_proc == 1:
                     assert mock_single_map_nested.called
                     assert not mock_multiprocessing_pool.called
              else:
                     assert not mock_single_map_nested.called
                     assert mock_multiprocessing_pool.called
                     assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc







class 			__A       (      lowerCamelCase__  ):




      """simple docstring"""







      @require_tf
      def 				__snake_case			(		self):



             """simple docstring"""





             import tensorflow as tf
             from tensorflow.keras import layers

             _lowerCamelCase							:     int	=		layers.Dense(2)

             def gen_random_output():
                    _lowerCamelCase							:     Union[str, Any]	=		tf.random.uniform((1, 3))
                    return model(a__).numpy()

             with temp_seed(42      ,							set_tensorflow=a__):
                    _lowerCamelCase							:     List[str]	=		gen_random_output()
             with temp_seed(42      ,							set_tensorflow=a__):
                    _lowerCamelCase							:     Any	=		gen_random_output()
             _lowerCamelCase							:     str	=		gen_random_output()

             np.testing.assert_equal(a__      ,							a__)
             self.assertGreater(np.abs(outa - outa).sum()      ,							0)


      @require_torch
      def 				__snake_case			(		self):



             """simple docstring"""





             import torch

             def gen_random_output():
                    _lowerCamelCase							:     Union[str, Any]	=		torch.nn.Linear(3      ,							2)
                    _lowerCamelCase							:     Dict	=		torch.rand(1      ,							3)
                    return model(a__).detach().numpy()

             with temp_seed(42      ,							set_pytorch=a__):
                    _lowerCamelCase							:     Any	=		gen_random_output()
             with temp_seed(42      ,							set_pytorch=a__):
                    _lowerCamelCase							:     Optional[int]	=		gen_random_output()
             _lowerCamelCase							:     Union[str, Any]	=		gen_random_output()

             np.testing.assert_equal(a__      ,							a__)
             self.assertGreater(np.abs(outa - outa).sum()      ,							0)



      def 				__snake_case			(		self):



             """simple docstring"""





             def gen_random_output():
                    return np.random.rand(1      ,							3)

             with temp_seed(42):
                    _lowerCamelCase							:     Union[str, Any]	=		gen_random_output()
             with temp_seed(42):
                    _lowerCamelCase							:     List[str]	=		gen_random_output()
             _lowerCamelCase							:     str	=		gen_random_output()

             np.testing.assert_equal(a__      ,							a__)
             self.assertGreater(np.abs(outa - outa).sum()      ,							0)




@pytest.mark.parametrize('''input_data''' ,    [{}]      )
def    __UpperCAmelCase(      lowercase_      ):
       _lowerCamelCase							:     List[Any]	=		NestedDataStructure(lowercase_      ).data
       assert output_data == input_data




@pytest.mark.parametrize(
    '''data, expected_output''' ,    [
        ({}, []),
        ([], []),
        ('''foo''', ['''foo''']),
        (['''foo''', '''bar'''], ['''foo''', '''bar''']),
        ([['''foo''', '''bar''']], ['''foo''', '''bar''']),
        ([[['''foo'''], ['''bar''']]], ['''foo''', '''bar''']),
        ([[['''foo'''], '''bar''']], ['''foo''', '''bar''']),
        ({'''a''': 1, '''b''': 2}, [1, 2]),
        ({'''a''': [1, 2], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[1, 2]], '''b''': [[3, 4]]}, [1, 2, 3, 4]),
        ({'''a''': [[1, 2]], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [[[3], [4]]]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [[3, 4]]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [3, 4]}, [1, 2, 3, 4]),
        ({'''a''': [[[1], [2]]], '''b''': [3, [4]]}, [1, 2, 3, 4]),
        ({'''a''': {'''1''': 1}, '''b''': 2}, [1, 2]),
        ({'''a''': {'''1''': [1]}, '''b''': 2}, [1, 2]),
        ({'''a''': {'''1''': [1]}, '''b''': [2]}, [1, 2]),
    ] ,    )
def    __UpperCAmelCase(      lowercase_ ,    lowercase_      ):
       _lowerCamelCase							:     int	=		NestedDataStructure(lowercase_      ).flatten()
       assert output == expected_output




def    __UpperCAmelCase(      ):
       _lowerCamelCase							:     Any	=		A(x=1 ,    y='''foobar'''      )
       _lowerCamelCase							:     Union[str, Any]	=		{'''x''': 1, '''y''': '''foobar'''}
       assert asdict(lowercase_      ) == expected_output

       _lowerCamelCase							:     Optional[int]	=		{'''a''': {'''b''': A(x=10 ,    y='''foo'''      )}, '''c''': [A(x=20 ,    y='''bar'''      )]}
       _lowerCamelCase							:     Union[str, Any]	=		{'''a''': {'''b''': {'''x''': 10, '''y''': '''foo'''}}, '''c''': [{'''x''': 20, '''y''': '''bar'''}]}
       assert asdict(lowercase_      ) == expected_output

       with pytest.raises(lowercase_      ):
              asdict([1, A(x=10 ,    y='''foo'''      )]      )




def    __UpperCAmelCase(      lowercase_      ):
       return text.split()




def    __UpperCAmelCase(      lowercase_      ):
       yield (time.time(), content)
       time.sleep(2      )
       yield (time.time(), content)




def    __UpperCAmelCase(      ):
       with Pool(2      ) as pool:
              _lowerCamelCase							:     Tuple	=		list(iflatmap_unordered(lowercase_ ,    _split_text ,    kwargs_iterable=[{'''text''': '''hello there'''}] * 10      )      )
              assert out.count('''hello'''      ) == 10
              assert out.count('''there'''      ) == 10
              assert len(lowercase_      ) == 20

       # check multiprocess from pathos (uses dill for pickling)
       with multiprocess.Pool(2      ) as pool:
              _lowerCamelCase							:     Dict	=		list(iflatmap_unordered(lowercase_ ,    _split_text ,    kwargs_iterable=[{'''text''': '''hello there'''}] * 10      )      )
              assert out.count('''hello'''      ) == 10
              assert out.count('''there'''      ) == 10
              assert len(lowercase_      ) == 20

       # check that we get items as fast as possible
       with Pool(2      ) as pool:
              _lowerCamelCase							:     str	=		[]
              for yield_time, content in iflatmap_unordered(
                  lowercase_ ,    _aseconds_generator_of_aitems_with_timing ,    kwargs_iterable=[{'''content''': '''a'''}, {'''content''': '''b'''}]      ):
                     assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded"
                     out.append(lowercase_      )
              assert out.count('''a'''      ) == 2
              assert out.count('''b'''      ) == 2
              assert len(lowercase_      ) == 4

