


'''simple docstring'''






import re

import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey

from ..utils import logging


__A					:  int											=      logging.get_logger(__name__)







def 				UpperCamelCase_			(    A__					:   Dict					):
  '''simple docstring'''





  lowerCAmelCase_			:      Optional[int]			=   R"""\w+[.]\d+"""
  lowerCAmelCase_			:      Tuple			=   re.findall(A__							,    A__					)
  for pat in pats:
    lowerCAmelCase_			:      Union[str, Any]			=   key.replace(A__							,    """_""".join(pat.split("""."""					)					)					)
  return key







def 				UpperCamelCase_			(    A__					:   Dict							,    A__					:   Any							,    A__					:   Any					):
  '''simple docstring'''





  lowerCAmelCase_			:      List[Any]			=   pt_tuple_key[:-1] + ("""scale""",)
  if (
      any("""norm""" in str_ for str_ in pt_tuple_key					)
      and (pt_tuple_key[-1] == "bias")
      and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
      and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
  ):
    lowerCAmelCase_			:      Optional[Any]			=   pt_tuple_key[:-1] + ("""scale""",)
    return renamed_pt_tuple_key, pt_tensor
  elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
    lowerCAmelCase_			:      Optional[Any]			=   pt_tuple_key[:-1] + ("""scale""",)
    return renamed_pt_tuple_key, pt_tensor

  # embedding
  if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
    lowerCAmelCase_			:      str			=   pt_tuple_key[:-1] + ("""embedding""",)
    return renamed_pt_tuple_key, pt_tensor

  # conv layer
  lowerCAmelCase_			:      List[str]			=   pt_tuple_key[:-1] + ("""kernel""",)
  if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
    lowerCAmelCase_			:      List[str]			=   pt_tensor.transpose(2							,    3							,    1							,    0					)
    return renamed_pt_tuple_key, pt_tensor

  # linear layer
  lowerCAmelCase_			:      Optional[int]			=   pt_tuple_key[:-1] + ("""kernel""",)
  if pt_tuple_key[-1] == "weight":
    lowerCAmelCase_			:      int			=   pt_tensor.T
    return renamed_pt_tuple_key, pt_tensor

  # old PyTorch layer norm weight
  lowerCAmelCase_			:      Any			=   pt_tuple_key[:-1] + ("""weight""",)
  if pt_tuple_key[-1] == "gamma":
    return renamed_pt_tuple_key, pt_tensor

  # old PyTorch layer norm bias
  lowerCAmelCase_			:      Optional[Any]			=   pt_tuple_key[:-1] + ("""bias""",)
  if pt_tuple_key[-1] == "beta":
    return renamed_pt_tuple_key, pt_tensor

  return pt_tuple_key, pt_tensor







def 				UpperCamelCase_			(    A__					:   str							,    A__					:   Tuple							,    A__					:   str=42					):
  '''simple docstring'''





  lowerCAmelCase_			:      List[str]			=   {k: v.numpy() for k, v in pt_state_dict.items()}

  # Step 2: Since the model is stateless, get random Flax params
  lowerCAmelCase_			:      int			=   flax_model.init_weights(PRNGKey(A__					)					)

  lowerCAmelCase_			:      Any			=   flatten_dict(A__					)
  lowerCAmelCase_			:      Any			=   {}

  # Need to change some parameters name to match Flax names
  for pt_key, pt_tensor in pt_state_dict.items():
    lowerCAmelCase_			:      str			=   rename_key(A__					)
    lowerCAmelCase_			:      int			=   tuple(renamed_pt_key.split("""."""					)					)

    # Correctly rename weight parameters
    lowerCAmelCase_,							lowerCAmelCase_			:      Optional[Any]			=   rename_key_and_reshape_tensor(A__							,    A__							,    A__					)

    if flax_key in random_flax_state_dict:
      if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
        raise ValueError(
            f'PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape '
            f'{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.'					)

        # also add unexpected weight so that warning is thrown
    lowerCAmelCase_			:      List[Any]			=   jnp.asarray(A__					)

  return unflatten_dict(A__					)







'''simple docstring'''






from sklearn.metrics import recall_score

import datasets


__A					:  Dict											=      "\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"


__A					:  List[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"


__A					:  str											=      "\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    __snake_case       (   datasets.Metric):







    """simple docstring"""



    def __lowercase   (   self    :  str		)   ->  Dict:
      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    :  Tuple    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Optional[Any]=None    ,						lowerCamelCase    :  Optional[int]=1    ,						lowerCamelCase    :  Union[str, Any]="binary"    ,						lowerCamelCase    :  Any=None    ,						lowerCamelCase    :  str="warn"    ,						)   ->  List[Any]:
      lowerCAmelCase_			:      Optional[int]			=   recall_score(
          lowerCamelCase    ,						lowerCamelCase    ,						labels=lowerCamelCase    ,						pos_label=lowerCamelCase    ,						average=lowerCamelCase    ,						sample_weight=lowerCamelCase    ,						zero_division=lowerCamelCase    ,						)
      return {"recall": float(lowerCamelCase		) if score.size == 1 else score}



