



'''simple docstring'''




import itertools
import random
import unittest

import numpy as np

from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor
from transformers.testing_utils import require_torch, slow

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


a     :    str      						=					random.Random()



def    __lowerCamelCase						(      _lowercase			,       _lowercase=1.0			,       _lowercase=None			,       _lowercase=None	)   ->    Optional[Any]:
							if rng is None:
														UpperCAmelCase  :	List[str]							  =	global_rng

							UpperCAmelCase  :	Union[str, Any]							  =	[]
							for batch_idx in range(shape[0]	):
														values.append([]	)
														for _ in range(shape[1]	):
																					values[-1].append(rng.random() * scale	)

							return values

class     UpperCamelCase_				(							unittest.TestCase    ):





	def __init__(						self	,	A	,	A=7	,	A=400	,	A=2000	,	A=1	,	A=0.0	,	A=16000	,	A=True	,	A=True	,	)    ->    Optional[int]:
								UpperCAmelCase  :	Dict							  =	parent
								UpperCAmelCase  :	Dict							  =	batch_size
								UpperCAmelCase  :	str							  =	min_seq_length
								UpperCAmelCase  :	Optional[int]							  =	max_seq_length
								UpperCAmelCase  :	List[str]							  =	(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
								UpperCAmelCase  :	List[Any]							  =	feature_size
								UpperCAmelCase  :	List[str]							  =	padding_value
								UpperCAmelCase  :	Any							  =	sampling_rate
								UpperCAmelCase  :	List[Any]							  =	return_attention_mask
								UpperCAmelCase  :	Union[str, Any]							  =	do_normalize





	def 				_lowercase(						self					)    ->    Union[str, Any]:
								return {
								    "feature_size": self.feature_size,
								    "padding_value": self.padding_value,
								    "sampling_rate": self.sampling_rate,
								    "return_attention_mask": self.return_attention_mask,
								    "do_normalize": self.do_normalize,
								}






	def 				_lowercase(						self	,	A=False	,	A=False					)    ->    Optional[Any]:
								def _flatten(A					):
															return list(itertools.chain(*A					)					)

								if equal_length:
															UpperCAmelCase  :	List[Any]							  =	floats_list((self.batch_size, self.max_seq_length)					)
								else:
															# make sure that inputs increase in size
															UpperCAmelCase  :	Union[str, Any]							  =	[
															    _flatten(floats_list((x, self.feature_size)					)					)
															    for x in range(self.min_seq_length	,	self.max_seq_length	,	self.seq_length_diff					)
															]

								if numpify:
															UpperCAmelCase  :	Optional[int]							  =	[np.asarray(A					) for x in speech_inputs]

								return speech_inputs




class     UpperCamelCase_				(							__magic_name__   ,  unittest.TestCase    ):
	lowercase    =				WavaVecaFeatureExtractor





	def 				_lowercase(						self					)    ->    List[str]:
								UpperCAmelCase  :	str							  =	WavaVecaFeatureExtractionTester(self					)





	def 				_lowercase(						self	,	A					)    ->    int:
								self.assertTrue(np.all(np.mean(A	,	axis=0					) < 1e-3					)					)
								self.assertTrue(np.all(np.abs(np.var(A	,	axis=0					) - 1					) < 1e-3					)					)





	def 				_lowercase(						self					)    ->    Optional[Any]:
								# Tests that all call wrap to encode_plus and batch_encode_plus
								UpperCAmelCase  :	List[str]							  =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
								# create three inputs of length 800, 1000, and 1200
								UpperCAmelCase  :	Any							  =	[floats_list((1, x)					)[0] for x in range(800	,	1400	,	200					)]
								UpperCAmelCase  :	Any							  =	[np.asarray(A					) for speech_input in speech_inputs]

								# Test not batched input
								UpperCAmelCase  :	Tuple							  =	feat_extract(speech_inputs[0]	,	return_tensors="""np"""					).input_values
								UpperCAmelCase  :	str							  =	feat_extract(np_speech_inputs[0]	,	return_tensors="""np"""					).input_values
								self.assertTrue(np.allclose(A	,	A	,	atol=1e-3					)					)

								# Test batched
								UpperCAmelCase  :	Optional[int]							  =	feat_extract(A	,	return_tensors="""np"""					).input_values
								UpperCAmelCase  :	List[Any]							  =	feat_extract(A	,	return_tensors="""np"""					).input_values
								for enc_seq_a, enc_seq_a in zip(A	,	A					):
															self.assertTrue(np.allclose(A	,	A	,	atol=1e-3					)					)

								# Test 2-D numpy arrays are batched.
								UpperCAmelCase  :	Tuple							  =	[floats_list((1, x)					)[0] for x in (800, 800, 800)]
								UpperCAmelCase  :	Optional[int]							  =	np.asarray(A					)
								UpperCAmelCase  :	int							  =	feat_extract(A	,	return_tensors="""np"""					).input_values
								UpperCAmelCase  :	List[str]							  =	feat_extract(A	,	return_tensors="""np"""					).input_values
								for enc_seq_a, enc_seq_a in zip(A	,	A					):
															self.assertTrue(np.allclose(A	,	A	,	atol=1e-3					)					)





	def 				_lowercase(						self					)    ->    Union[str, Any]:
								UpperCAmelCase  :	Any							  =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
								UpperCAmelCase  :	Union[str, Any]							  =	[floats_list((1, x)					)[0] for x in range(800	,	1400	,	200					)]

								UpperCAmelCase  :	Any							  =	["""longest""", """max_length""", """do_not_pad"""]
								UpperCAmelCase  :	List[Any]							  =	[None, 1600, None]
								for max_length, padding in zip(A	,	A					):
															UpperCAmelCase  :	Dict							  =	feat_extract(A	,	padding=A	,	max_length=A	,	return_tensors="""np"""					)
															UpperCAmelCase  :	List[Any]							  =	processed.input_values

															self._check_zero_mean_unit_variance(input_values[0][:800]					)
															self.assertTrue(input_values[0][800:].sum() < 1e-6					)
															self._check_zero_mean_unit_variance(input_values[1][:1000]					)
															self.assertTrue(input_values[0][1000:].sum() < 1e-6					)
															self._check_zero_mean_unit_variance(input_values[2][:1200]					)





	def 				_lowercase(						self					)    ->    str:
								UpperCAmelCase  :	Tuple							  =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
								UpperCAmelCase  :	str							  =	range(800	,	1400	,	200					)
								UpperCAmelCase  :	Optional[int]							  =	[floats_list((1, x)					)[0] for x in lengths]

								UpperCAmelCase  :	Optional[int]							  =	["""longest""", """max_length""", """do_not_pad"""]
								UpperCAmelCase  :	Dict							  =	[None, 1600, None]

								for max_length, padding in zip(A	,	A					):
															UpperCAmelCase  :	List[Any]							  =	feat_extract(A	,	max_length=A	,	padding=A					)
															UpperCAmelCase  :	Optional[Any]							  =	processed.input_values

															self._check_zero_mean_unit_variance(input_values[0][:800]					)
															self._check_zero_mean_unit_variance(input_values[1][:1000]					)
															self._check_zero_mean_unit_variance(input_values[2][:1200]					)





	def 				_lowercase(						self					)    ->    List[Any]:
								UpperCAmelCase  :	List[Any]							  =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
								UpperCAmelCase  :	Union[str, Any]							  =	[floats_list((1, x)					)[0] for x in range(800	,	1400	,	200					)]
								UpperCAmelCase  :	Dict							  =	feat_extract(
								    A	,	truncation=A	,	max_length=1000	,	padding="""max_length"""	,	return_tensors="""np"""					)
								UpperCAmelCase  :	int							  =	processed.input_values

								self._check_zero_mean_unit_variance(input_values[0, :800]					)
								self._check_zero_mean_unit_variance(input_values[1]					)
								self._check_zero_mean_unit_variance(input_values[2]					)





	def 				_lowercase(						self					)    ->    Optional[Any]:
								UpperCAmelCase  :	Optional[int]							  =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
								UpperCAmelCase  :	List[str]							  =	[floats_list((1, x)					)[0] for x in range(800	,	1400	,	200					)]
								UpperCAmelCase  :	Union[str, Any]							  =	feat_extract(
								    A	,	truncation=A	,	max_length=1000	,	padding="""longest"""	,	return_tensors="""np"""					)
								UpperCAmelCase  :	Union[str, Any]							  =	processed.input_values

								self._check_zero_mean_unit_variance(input_values[0, :800]					)
								self._check_zero_mean_unit_variance(input_values[1, :1000]					)
								self._check_zero_mean_unit_variance(input_values[2]					)

								# make sure that if max_length < longest -> then pad to max_length
								self.assertTrue(input_values.shape == (3, 1000)					)

								UpperCAmelCase  :	List[Any]							  =	[floats_list((1, x)					)[0] for x in range(800	,	1400	,	200					)]
								UpperCAmelCase  :	List[str]							  =	feat_extract(
								    A	,	truncation=A	,	max_length=2000	,	padding="""longest"""	,	return_tensors="""np"""					)
								UpperCAmelCase  :	Optional[int]							  =	processed.input_values

								self._check_zero_mean_unit_variance(input_values[0, :800]					)
								self._check_zero_mean_unit_variance(input_values[1, :1000]					)
								self._check_zero_mean_unit_variance(input_values[2]					)

								# make sure that if max_length > longest -> then pad to longest
								self.assertTrue(input_values.shape == (3, 1200)					)





	@require_torch
	def 				_lowercase(						self					)    ->    Tuple:
								import torch

								UpperCAmelCase  :	str							  =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()					)
								UpperCAmelCase  :	Tuple							  =	np.random.rand(100					).astype(np.floataa					)
								UpperCAmelCase  :	str							  =	np_speech_inputs.tolist()

								for inputs in [py_speech_inputs, np_speech_inputs]:
															UpperCAmelCase  :	Union[str, Any]							  =	feature_extractor.pad([{"""input_values""": inputs}]	,	return_tensors="""np"""					)
															self.assertTrue(np_processed.input_values.dtype == np.floataa					)
															UpperCAmelCase  :	Tuple							  =	feature_extractor.pad([{"""input_values""": inputs}]	,	return_tensors="""pt"""					)
															self.assertTrue(pt_processed.input_values.dtype == torch.floataa					)






	@slow
	@require_torch
	def 				_lowercase(						self					)    ->    Dict:
								# this test makes sure that models that are using
								# group norm don't have their feature extractor return the
								# attention_mask
								for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST:
															UpperCAmelCase  :	Optional[Any]							  =	WavaVecaConfig.from_pretrained(A					)
															UpperCAmelCase  :	Optional[Any]							  =	WavaVecaFeatureExtractor.from_pretrained(A					)

															# only "layer" feature extraction norm should make use of
															# attention_mask
															self.assertEqual(feat_extract.return_attention_mask	,	config.feat_extract_norm == """layer"""					)






'''simple docstring'''




from sklearn.metrics import mean_squared_error

import datasets


a     :    Union[str, Any]      						=					"""\
@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}
}
"""

a     :    int      						=					"""\
Mean Squared Error(MSE) is the average of the square of difference between the predicted
and actual values.
"""


a     :    int      						=					"""
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

        \"raw_values\" : Returns a full set of errors in case of multioutput input.

        \"uniform_average\" : Errors of all outputs are averaged with uniform weight.

    squared : bool, default=True
        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.

Returns:
    mse : mean squared error.
Examples:

    >>> mse_metric = datasets.load_metric(\"mse\")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mse': 0.375}
    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)
    >>> print(rmse_result)
    {'mse': 0.6123724356957945}

    If you're using multi-dimensional lists, then set the config as follows :

    >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mse': 0.7083333333333334}
    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')
    >>> print(results) # doctest: +NORMALIZE_WHITESPACE
    {'mse': array([0.41666667, 1. ])}
"""

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





	def 				_lowercase(						self					)    ->    List[str]:
								return datasets.MetricInfo(
								    description=_DESCRIPTION	,	citation=_CITATION	,	inputs_description=_KWARGS_DESCRIPTION	,	features=datasets.Features(self._get_feature_types()					)	,	reference_urls=[
								        """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html"""
								    ]	,	)





	def 				_lowercase(						self					)    ->    List[Any]:
								if self.config_name == "multilist":
															return {
															    "predictions": datasets.Sequence(datasets.Value("""float"""					)					),
															    "references": datasets.Sequence(datasets.Value("""float"""					)					),
															}
								else:
															return {
															    "predictions": datasets.Value("""float"""					),
															    "references": datasets.Value("""float"""					),
															}






	def 				_lowercase(						self	,	A	,	A	,	A=None	,	A="uniform_average"	,	A=True					)    ->    List[Any]:
								UpperCAmelCase  :	List[Any]							  =	mean_squared_error(
								    A	,	A	,	sample_weight=A	,	multioutput=A	,	squared=A					)

								return {"mse": mse}

