



'''simple docstring'''




from typing import Tuple, Union

from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig


if is_timm_available():
						import timm


if is_torch_available():
						from torch import Tensor

class     UpperCamelCase_				(							__snake_case   ,  __snake_case    ):
	lowercase    =				'pixel_values'
	lowercase    =				False
	lowercase    =				TimmBackboneConfig





	def __init__(						self	,	A	,	**A					)    ->    Tuple:
								requires_backends(self	,	"""timm"""					)
								super().__init__(__UpperCamelCase					)
								UpperCAmelCase  :	Optional[Any]							  =	config

								if config.backbone is None:
															raise ValueError("""backbone is not set in the config. Please set it to a timm model name."""					)

								if config.backbone not in timm.list_models():
															raise ValueError(f'''backbone {config.backbone} is not supported by timm.'''					)

								if hasattr(__UpperCamelCase	,	"""out_features"""					) and config.out_features is not None:
															raise ValueError("""out_features is not supported by TimmBackbone. Please use out_indices instead."""					)

								UpperCAmelCase  :	Optional[Any]							  =	getattr(__UpperCamelCase	,	"""use_pretrained_backbone"""	,	__UpperCamelCase					)
								if pretrained is None:
															raise ValueError("""use_pretrained_backbone is not set in the config. Please set it to True or False."""					)

								# We just take the final layer by default. This matches the default for the transformers models.
								UpperCAmelCase  :	Dict							  =	config.out_indices if getattr(__UpperCamelCase	,	"""out_indices"""	,	__UpperCamelCase					) is not None else (-1,)

								UpperCAmelCase  :	Any							  =	timm.create_model(
								    config.backbone	,	pretrained=__UpperCamelCase	,	features_only=config.features_only	,	in_chans=config.num_channels	,	out_indices=__UpperCamelCase	,	**__UpperCamelCase	,	)
								# These are used to control the output of the model when called. If output_hidden_states is True, then
								# return_layers is modified to include all layers.
								UpperCAmelCase  :	int							  =	self._backbone.return_layers
								UpperCAmelCase  :	Dict							  =	{layer["""module"""]: str(__UpperCamelCase					) for i, layer in enumerate(self._backbone.feature_info.info					)}
								super()._init_backbone(__UpperCamelCase					)





	@classmethod
	def 				_lowercase(						cls	,	A	,	*A	,	**A					)    ->    List[str]:
								requires_backends(cls	,	["""vision""", """timm"""]					)
								from ...models.timm_backbone import TimmBackboneConfig

								UpperCAmelCase  :	int							  =	kwargs.pop("""config"""	,	TimmBackboneConfig()					)

								UpperCAmelCase  :	str							  =	kwargs.pop("""use_timm_backbone"""	,	__UpperCamelCase					)
								if not use_timm:
															raise ValueError("""use_timm_backbone must be True for timm backbones"""					)

								UpperCAmelCase  :	Dict							  =	kwargs.pop("""num_channels"""	,	config.num_channels					)
								UpperCAmelCase  :	Optional[Any]							  =	kwargs.pop("""features_only"""	,	config.features_only					)
								UpperCAmelCase  :	Tuple							  =	kwargs.pop("""use_pretrained_backbone"""	,	config.use_pretrained_backbone					)
								UpperCAmelCase  :	Any							  =	kwargs.pop("""out_indices"""	,	config.out_indices					)
								UpperCAmelCase  :	Union[str, Any]							  =	TimmBackboneConfig(
								    backbone=__UpperCamelCase	,	num_channels=__UpperCamelCase	,	features_only=__UpperCamelCase	,	use_pretrained_backbone=__UpperCamelCase	,	out_indices=__UpperCamelCase	,	)
								return super()._from_config(__UpperCamelCase	,	**__UpperCamelCase					)





	def 				_lowercase(						self	,	A					)    ->    int:
								pass






	def 				_lowercase(						self	,	A	,	A=None	,	A=None	,	A=None	,	**A					)    ->    Optional[Any]:
								UpperCAmelCase  :	Optional[Any]							  =	return_dict if return_dict is not None else self.config.use_return_dict
								UpperCAmelCase  :	Optional[int]							  =	(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								UpperCAmelCase  :	Any							  =	output_attentions if output_attentions is not None else self.config.output_attentions

								if output_attentions:
															raise ValueError("""Cannot output attentions for timm backbones at the moment"""					)

								if output_hidden_states:
															# We modify the return layers to include all the stages of the backbone
															UpperCAmelCase  :	int							  =	self._all_layers
															UpperCAmelCase  :	List[str]							  =	self._backbone(__UpperCamelCase	,	**__UpperCamelCase					)
															UpperCAmelCase  :	Tuple							  =	self._return_layers
															UpperCAmelCase  :	Any							  =	tuple(hidden_states[i] for i in self.out_indices					)
								else:
															UpperCAmelCase  :	List[Any]							  =	self._backbone(__UpperCamelCase	,	**__UpperCamelCase					)
															UpperCAmelCase  :	Any							  =	None

								UpperCAmelCase  :	Optional[int]							  =	tuple(__UpperCamelCase					)
								UpperCAmelCase  :	List[Any]							  =	tuple(__UpperCamelCase					) if hidden_states is not None else None

								if not return_dict:
															UpperCAmelCase  :	int							  =	(feature_maps,)
															if output_hidden_states:
																						UpperCAmelCase  :	Union[str, Any]							  =	output + (hidden_states,)
															return output

								return BackboneOutput(feature_maps=__UpperCamelCase	,	hidden_states=__UpperCamelCase	,	attentions=__UpperCamelCase					)






'''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}

