






"""simple docstring"""





import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import MobileNetVaForImageClassification, MobileNetVaModel
  from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import MobileNetVaImageProcessor






class 	a		(   __snake_case						):






    def   UpperCamelCase			(			self	:				Dict   )	->						Optional[Any]:
      lowerCamelCase_       	=		self.config_class(**self.inputs_dict   )
      self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE			,		'tf_padding'   )   )
      self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE			,		'depth_multiplier'   )   )






class 	a		:






    def __init__(			self	:				Dict			,		__SCREAMING_SNAKE_CASE	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				Dict=13			,		__SCREAMING_SNAKE_CASE	:				Any=3			,		__SCREAMING_SNAKE_CASE	:				List[str]=32			,		__SCREAMING_SNAKE_CASE	:				Any=0.25			,		__SCREAMING_SNAKE_CASE	:				List[str]=8			,		__SCREAMING_SNAKE_CASE	:				Tuple=True			,		__SCREAMING_SNAKE_CASE	:				Tuple=1024			,		__SCREAMING_SNAKE_CASE	:				List[str]=32			,		__SCREAMING_SNAKE_CASE	:				List[str]="relu6"			,		__SCREAMING_SNAKE_CASE	:				Dict=0.1			,		__SCREAMING_SNAKE_CASE	:				List[str]=0.02			,		__SCREAMING_SNAKE_CASE	:				str=True			,		__SCREAMING_SNAKE_CASE	:				int=True			,		__SCREAMING_SNAKE_CASE	:				str=10			,		__SCREAMING_SNAKE_CASE	:				List[str]=None			,		)	->						Any:
      lowerCamelCase_       	=		parent
      lowerCamelCase_       	=		batch_size
      lowerCamelCase_       	=		num_channels
      lowerCamelCase_       	=		image_size
      lowerCamelCase_       	=		depth_multiplier
      lowerCamelCase_       	=		min_depth
      lowerCamelCase_       	=		tf_padding
      lowerCamelCase_       	=		int(last_hidden_size * depth_multiplier   )
      lowerCamelCase_       	=		output_stride
      lowerCamelCase_       	=		hidden_act
      lowerCamelCase_       	=		classifier_dropout_prob
      lowerCamelCase_       	=		use_labels
      lowerCamelCase_       	=		is_training
      lowerCamelCase_       	=		num_labels
      lowerCamelCase_       	=		initializer_range
      lowerCamelCase_       	=		scope






    def   UpperCamelCase			(			self	:				Tuple   )	->						Tuple:
      lowerCamelCase_       	=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

      lowerCamelCase_       	=		None
      lowerCamelCase_       	=		None
      if self.use_labels:
        lowerCamelCase_       	=		ids_tensor([self.batch_size]			,		self.num_labels   )
        lowerCamelCase_       	=		ids_tensor([self.batch_size, self.image_size, self.image_size]			,		self.num_labels   )

      lowerCamelCase_       	=		self.get_config()

      return config, pixel_values, labels, pixel_labels






    def   UpperCamelCase			(			self	:				List[Any]   )	->						Any:
      return MobileNetVaConfig(
          num_channels=self.num_channels			,		image_size=self.image_size			,		depth_multiplier=self.depth_multiplier			,		min_depth=self.min_depth			,		tf_padding=self.tf_padding			,		hidden_act=self.hidden_act			,		classifier_dropout_prob=self.classifier_dropout_prob			,		initializer_range=self.initializer_range			,		)






    def   UpperCamelCase			(			self	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				Any			,		__SCREAMING_SNAKE_CASE	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				List[Any]   )	->						Optional[Any]:
      lowerCamelCase_       	=		MobileNetVaModel(config=__SCREAMING_SNAKE_CASE   )
      model.to(__SCREAMING_SNAKE_CASE   )
      model.eval()
      lowerCamelCase_       	=		model(__SCREAMING_SNAKE_CASE   )
      self.parent.assertEqual(
          result.last_hidden_state.shape			,		(
              self.batch_size,
              self.last_hidden_size,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )			,		)






    def   UpperCamelCase			(			self	:				Optional[Any]			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				Optional[Any]			,		__SCREAMING_SNAKE_CASE	:				Optional[int]			,		__SCREAMING_SNAKE_CASE	:				Optional[Any]   )	->						Optional[Any]:
      lowerCamelCase_       	=		self.num_labels
      lowerCamelCase_       	=		MobileNetVaForImageClassification(__SCREAMING_SNAKE_CASE   )
      model.to(__SCREAMING_SNAKE_CASE   )
      model.eval()
      lowerCamelCase_       	=		model(__SCREAMING_SNAKE_CASE			,		labels=__SCREAMING_SNAKE_CASE   )
      self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.num_labels)   )






    def   UpperCamelCase			(			self	:				Union[str, Any]   )	->						Optional[Any]:
      lowerCamelCase_       	=		self.prepare_config_and_inputs()
      lowerCamelCase_	,      lowerCamelCase_	,      lowerCamelCase_	,      lowerCamelCase_       	=		config_and_inputs
      lowerCamelCase_       	=		{'pixel_values': pixel_values}
      return config, inputs_dict






@require_torch
class 	a		(   __snake_case    , __snake_case    , unittest.TestCase						):
    SCREAMING_SNAKE_CASE		:	List[str]		=					(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
    SCREAMING_SNAKE_CASE		:	List[str]		=					(
        {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
        if is_torch_available()
        else {}
    )

    SCREAMING_SNAKE_CASE		:	str		=					False
    SCREAMING_SNAKE_CASE		:	List[Any]		=					False
    SCREAMING_SNAKE_CASE		:	Any		=					False
    SCREAMING_SNAKE_CASE		:	int		=					False






    def   UpperCamelCase			(			self	:				Tuple   )	->						str:
      lowerCamelCase_       	=		MobileNetVaModelTester(self   )
      lowerCamelCase_       	=		MobileNetVaConfigTester(self			,		config_class=__SCREAMING_SNAKE_CASE			,		has_text_modality=__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				Union[str, Any]   )	->						str:
      self.config_tester.run_common_tests()






    @unittest.skip(reason='MobileNetV1 does not use inputs_embeds'   )
    def   UpperCamelCase			(			self	:				Optional[int]   )	->						Optional[Any]:
      pass






    @unittest.skip(reason='MobileNetV1 does not support input and output embeddings'   )
    def   UpperCamelCase			(			self	:				List[str]   )	->						Tuple:
      pass






    @unittest.skip(reason='MobileNetV1 does not output attentions'   )
    def   UpperCamelCase			(			self	:				List[Any]   )	->						Tuple:
      pass






    def   UpperCamelCase			(			self	:				Any   )	->						List[str]:
      lowerCamelCase_	,      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        lowerCamelCase_       	=		model_class(__SCREAMING_SNAKE_CASE   )
        lowerCamelCase_       	=		inspect.signature(model.forward   )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        lowerCamelCase_       	=		[*signature.parameters.keys()]

        lowerCamelCase_       	=		['pixel_values']
        self.assertListEqual(arg_names[:1]			,		__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				Dict   )	->						List[str]:
      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				Optional[Any]   )	->						str:
      def check_hidden_states_output(__SCREAMING_SNAKE_CASE	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				Optional[int]			,		__SCREAMING_SNAKE_CASE	:				Dict   ):
        lowerCamelCase_       	=		model_class(__SCREAMING_SNAKE_CASE   )
        model.to(__SCREAMING_SNAKE_CASE   )
        model.eval()

        with torch.no_grad():
          lowerCamelCase_       	=		model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )   )

        lowerCamelCase_       	=		outputs.hidden_states

        lowerCamelCase_       	=		26
        self.assertEqual(len(__SCREAMING_SNAKE_CASE   )			,		__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_	,      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        lowerCamelCase_       	=		True
        check_hidden_states_output(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        lowerCamelCase_       	=		True

        check_hidden_states_output(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				Any   )	->						Dict:
      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE   )






    @slow
    def   UpperCamelCase			(			self	:				Any   )	->						str:
      for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCamelCase_       	=		MobileNetVaModel.from_pretrained(__SCREAMING_SNAKE_CASE   )
        self.assertIsNotNone(__SCREAMING_SNAKE_CASE   )







def 	lowerCamelCase__			(				) ->							Optional[Any]:
  lowerCamelCase_       	=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
  return image






@require_torch
@require_vision
class 	a		(   unittest.TestCase						):






    @cached_property
    def   UpperCamelCase			(			self	:				Any   )	->						Dict:
      return (
          MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224'   ) if is_vision_available() else None
      )






    @slow
    def   UpperCamelCase			(			self	:				List[Any]   )	->						str:
      lowerCamelCase_       	=		MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224'   ).to(__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		self.default_image_processor
      lowerCamelCase_       	=		prepare_img()
      lowerCamelCase_       	=		image_processor(images=__SCREAMING_SNAKE_CASE			,		return_tensors='pt'   ).to(__SCREAMING_SNAKE_CASE   )

      # forward pass
      with torch.no_grad():
        lowerCamelCase_       	=		model(**__SCREAMING_SNAKE_CASE   )

      # verify the logits
      lowerCamelCase_       	=		torch.Size((1, 1001)   )
      self.assertEqual(outputs.logits.shape			,		__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		torch.tensor([-4.1_739, -1.1_233, 3.1_205]   ).to(__SCREAMING_SNAKE_CASE   )

      self.assertTrue(torch.allclose(outputs.logits[0, :3]			,		__SCREAMING_SNAKE_CASE			,		atol=1e-4   )   )












"""simple docstring"""





from scipy.stats import pearsonr

import datasets


_SCREAMING_SNAKE_CASE   :							List[str]          =		'''
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
'''


_SCREAMING_SNAKE_CASE   :							int          =		'''
Args:
    predictions (`list` of `int`): Predicted class labels, as returned by a model.
    references (`list` of `int`): Ground truth labels.
    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.

Returns:
    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.

Examples:

    Example 1-A simple example using only predictions and references.
        >>> pearsonr_metric = datasets.load_metric("pearsonr")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
        >>> print(round(results[\'pearsonr\'], 2))
        -0.74

    Example 2-The same as Example 1, but that also returns the `p-value`.
        >>> pearsonr_metric = datasets.load_metric("pearsonr")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
        >>> print(sorted(list(results.keys())))
        [\'p-value\', \'pearsonr\']
        >>> print(round(results[\'pearsonr\'], 2))
        -0.74
        >>> print(round(results[\'p-value\'], 2))
        0.15
'''


_SCREAMING_SNAKE_CASE   :							Dict          =		'''
@article{2020SciPy-NMeth,
author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
      Haberland, Matt and Reddy, Tyler and Cournapeau, David and
      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
      Kern, Robert and Larson, Eric and Carey, C J and
      Polat, Ilhan and Feng, Yu and Moore, Eric W. and
      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
      Harris, Charles R. and Archibald, Anne M. and
      Ribeiro, Antonio H. and Pedregosa, Fabian and
      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
      Computing in Python}},
journal = {Nature Methods},
year    = {2020},
volume  = {17},
pages   = {261--272},
adsurl  = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
'''






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






    def   UpperCamelCase			(			self	:				Dict   )	->						Any:
      return datasets.MetricInfo(
          description=_DESCRIPTION			,		citation=_CITATION			,		inputs_description=_KWARGS_DESCRIPTION			,		features=datasets.Features(
              {
                  'predictions': datasets.Value('float'   ),
                  'references': datasets.Value('float'   ),
              }   )			,		reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html']			,		)






    def   UpperCamelCase			(			self	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				Tuple			,		__SCREAMING_SNAKE_CASE	:				Tuple=False   )	->						Tuple:
      if return_pvalue:
        lowerCamelCase_       	=		pearsonr(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )
        return {"pearsonr": results[0], "p-value": results[1]}
      else:
        return {"pearsonr": float(pearsonr(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )[0]   )}




