



from sklearn.metrics import recall_score

import datasets


a__			=		'''
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.
'''


a__			=		'''
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.])}
'''


a__			=		'''
@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 						snake_case  (		datasets.Metric     ):



   '''simple docstring'''






   def    UpperCamelCase_     (    self							:	Tuple) -> Union[str, 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    UpperCamelCase_     (    self							:	str ,						lowerCAmelCase							:	List[Any] ,						lowerCAmelCase							:	Optional[int] ,						lowerCAmelCase							:	Union[str, Any]=None ,						lowerCAmelCase							:	Dict=1 ,						lowerCAmelCase							:	Union[str, Any]="binary" ,						lowerCAmelCase							:	Dict=None ,						lowerCAmelCase							:	Tuple="warn" ,						) -> str:

    """simple docstring"""







    _snake_case			:     Tuple 		=    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}








# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


UpperCAmelCase_ :						Any      =      '''Create a default config file for Accelerate with only a few flags set.'''

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[int]="no"	,			__magic_name__					:  str = default_json_config_file	,			__magic_name__					:  bool = False					)		->			str:






	"""simple docstring"""



	UpperCamelCase     :Any          =	Path(__magic_name__					)
	path.parent.mkdir(parents=__magic_name__	,			exist_ok=__magic_name__					)
	if path.exists():
		print(
		    f"""Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`."""					)
		return False
	UpperCamelCase     :Dict          =	mixed_precision.lower()
	if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
		raise ValueError(
		    f"""`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}"""					)
	UpperCamelCase     :Optional[Any]          =	{
	    """compute_environment""": """LOCAL_MACHINE""",
	    """mixed_precision""": mixed_precision,
	}
	if torch.cuda.is_available():
		UpperCamelCase     :Union[str, Any]          =	torch.cuda.device_count()
		UpperCamelCase     :List[Any]          =	num_gpus
		UpperCamelCase     :Dict          =	False
		if num_gpus > 1:
			UpperCamelCase     :Any          =	"""MULTI_GPU"""
		else:
			UpperCamelCase     :Any          =	"""NO"""
	elif is_xpu_available() and use_xpu:
		UpperCamelCase     :Optional[Any]          =	torch.xpu.device_count()
		UpperCamelCase     :Optional[int]          =	num_xpus
		UpperCamelCase     :int          =	False
		if num_xpus > 1:
			UpperCamelCase     :Union[str, Any]          =	"""MULTI_XPU"""
		else:
			UpperCamelCase     :Union[str, Any]          =	"""NO"""
	elif is_npu_available():
		UpperCamelCase     :List[Any]          =	torch.npu.device_count()
		UpperCamelCase     :Optional[Any]          =	num_npus
		UpperCamelCase     :Tuple          =	False
		if num_npus > 1:
			UpperCamelCase     :Optional[Any]          =	"""MULTI_NPU"""
		else:
			UpperCamelCase     :List[Any]          =	"""NO"""
	else:
		UpperCamelCase     :Any          =	0
		UpperCamelCase     :Optional[Any]          =	True
		UpperCamelCase     :Optional[Any]          =	1
		UpperCamelCase     :List[str]          =	"""NO"""
	UpperCamelCase     :int          =	ClusterConfig(**__magic_name__					)
	config.to_json_file(__magic_name__					)
	return path

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict	,			__magic_name__					:  Tuple					)		->			List[str]:






	"""simple docstring"""



	UpperCamelCase     :Dict          =	parser.add_parser("""default"""	,			parents=__magic_name__	,			help=__magic_name__	,			formatter_class=__magic_name__					)
	parser.add_argument(
	    """--config_file"""	,			default=__magic_name__	,			help=(
	        """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """
	        """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """
	        """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """
	        """with 'huggingface'."""
	    )	,			dest="""save_location"""	,			)

	parser.add_argument(
	    """--mixed_precision"""	,			choices=["""no""", """fp16""", """bf16"""]	,			type=__magic_name__	,			help="""Whether or not to use mixed precision training. """
	    """Choose between FP16 and BF16 (bfloat16) training. """
	    """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later."""	,			default="""no"""	,			)
	parser.set_defaults(func=__magic_name__					)
	return parser

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[Any]					)		->			List[str]:






	"""simple docstring"""



	UpperCamelCase     :Optional[Any]          =	write_basic_config(args.mixed_precision	,			args.save_location					)
	if config_file:
		print(f"""accelerate configuration saved at {config_file}"""					)
