
    h$,fm                        d Z ddlZddlZddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ dd	lmZ dd
lmZmZmZmZ ddlmZ ddlmZmZmZmZmZmZmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZC d ZD G d d      ZE G d de      ZF G d deF      ZG edeHeIdgid      d        ZJ G d d      ZKd ZLd ZM eeIgdeNeO eh d       gd!gd! e ed"h            gd! e ed"h            gd#d      ddd"d"d$d%       ZP ePe&      ZQ ePe4      ZR ePe+d&'      ZS ePe0d&'      ZT ePe1d&'      ZU ePe,d&'      ZV ePe-d&'      ZW ePe2d&'      ZX ePe7d&'      ZY ePe8d&'      ZZ ePe/d&'      Z[ ePe.d&'      Z\ ePe!      Z] ePe#      Z^ ePe*      Z_d( Z`d) Za ePe`      Zb ePead&'      Zc ePe9dd*+      Zd ePe6dd*+      Ze ePe"d*,      Zf ePe6d-d./      Zg ePe6d-d.d01      Zh ePe6d-d2/      Zi ePe6d-d2d01      Zj ePe)d&d-+      Zk ePe$d&d-+      Zl ePe$d&d-+      Zm ePe<      Zn ePeB      Zo ePe?      Zp ePe=      Zq ePeC      Zr ePe@      Zs ePe;      Zt ePeA      Zu ePe>      Zv ewddi d3eQd4eRd5eSd6e_d7eXd8eVd9eWd:eTd;eUd<eYd=eZd>e[d?e\d@e]dAeddBeedCeidDegdEejdFehdGe^dHefdIekdJeldKebdLecdMendNeodOepdPeqdQerdResdSetdTeudUevZxdV ZydWe3fdXe5fdYe'fdZe(ffD ]9  \  ZzZ{ ePe{d[\      exez<   d]D ]"  Z|d^j                  eze|      Z~ ePe{de|_      exe~<   $ ;  e ed`      g e e ey                   eIdgd!gdad      ded&dbdc       Zy)faH  
The :mod:`sklearn.metrics.scorer` submodule implements a flexible
interface for model selection and evaluation using
arbitrary score functions.

A scorer object is a callable that can be passed to
:class:`~sklearn.model_selection.GridSearchCV` or
:func:`sklearn.model_selection.cross_val_score` as the ``scoring``
parameter, to specify how a model should be evaluated.

The signature of the call is ``(estimator, X, y)`` where ``estimator``
is the model to be evaluated, ``X`` is the test data and ``y`` is the
ground truth labeling (or ``None`` in the case of unsupervised models).
    N)Counter)partial)	signature)
format_exc   )is_regressor)Bunch)
HasMethodsHidden
StrOptionsvalidate_params_get_response_values)MetadataRequestMetadataRouter_MetadataRequester_raise_for_params_routing_enabledget_routing_for_objectprocess_routing)_check_response_method   )accuracy_scoreaverage_precision_scorebalanced_accuracy_scorebrier_score_lossclass_likelihood_ratiosexplained_variance_scoref1_scorejaccard_scorelog_lossmatthews_corrcoef	max_errormean_absolute_errormean_absolute_percentage_errormean_gamma_deviancemean_poisson_deviancemean_squared_errormean_squared_log_errormedian_absolute_errorprecision_scorer2_scorerecall_scoreroc_auc_scoreroot_mean_squared_errorroot_mean_squared_log_errortop_k_accuracy_score)	adjusted_mutual_info_scoreadjusted_rand_scorecompleteness_scorefowlkes_mallows_scorehomogeneity_scoremutual_info_scorenormalized_mutual_info_score
rand_scorev_measure_scorec                 R    | 	|| v r| |   S t        |g|d|i|\  }}| || |<   |S )z/Call estimator with method and args and kwargs.response_methodr   )cache	estimatorr<   argskwargsresult_s          7lib/python3.12/site-packages/sklearn/metrics/_scorer.py_cached_callrD   R   sZ    _5_%%$*9=CIFA !'oM    c                   .    e Zd ZdZdddZd Zd Zd Zy)	_MultimetricScorera  Callable for multimetric scoring used to avoid repeated calls
    to `predict_proba`, `predict`, and `decision_function`.

    `_MultimetricScorer` will return a dictionary of scores corresponding to
    the scorers in the dictionary. Note that `_MultimetricScorer` can be
    created with a dictionary with one key  (i.e. only one actual scorer).

    Parameters
    ----------
    scorers : dict
        Dictionary mapping names to callable scorers.

    raise_exc : bool, default=True
        Whether to raise the exception in `__call__` or not. If set to `False`
        a formatted string of the exception details is passed as result of
        the failing scorer.
    T)	raise_excc                     || _         || _        y N)_scorers
_raise_exc)selfscorersrH   s      rC   __init__z_MultimetricScorer.__init__t   s    #rE   c                 h   i }| j                  |      ri nd}t        t        |      }t               rt	        | dfi |}n.t        di | j                  D ci c]  }|t        |       c}}| j                  j                         D ]q  \  }}		 t        |	t              r1 |	j                  ||g|i |j                  |      j                  }
n% |	|g|i |j                  |      j                  }
|
||<   s |S c c}w # t        $ r%}| j                  r|t               ||<   Y d}~d}~ww xY w)z!Evaluate predicted target values.NscorerQ    )
_use_cacher   rD   r   r   r	   rK   items
isinstance_BaseScorer_scoregetrQ   	ExceptionrL   r   )rM   r>   r?   r@   scoresr=   cached_callrouted_paramsnamescorerrQ   es               rC   __call__z_MultimetricScorer.__call__x   s6   ooi0dlE2+D'DVDM " 9=G4V,,GM !MM//1 	0LD&0fk2)FMM#Y159F9J9J49P9V9VE #9UtU}7H7H7N7T7TUE$t	0 # H  0??G#-<F4L	0s   C>A+D	D1D,,D1c           	      @   t        | j                        dk(  ryt        | j                  j                         D cg c]2  }t	        |t
              r t        ||j                        j                  4 c}      }t        d |j                         D              ryyc c}w )zuReturn True if using a cache is beneficial, thus when a response method will
        be called several time.
        r   Fc              3   &   K   | ]	  }|d kD    yw)r   NrS   ).0vals     rC   	<genexpr>z0_MultimetricScorer._use_cache.<locals>.<genexpr>   s     33sQw3s   T)
lenrK   r   valuesrV   rW   r   _response_method__name__any)rM   r>   r_   counters       rC   rT   z_MultimetricScorer._use_cache   s     t}}" #mm224fk2 'y&2I2IJSS
 3'.."233 s   7Bc                 ~     t        | j                  j                        j                  di | j                  ddiS )ab  Get metadata routing of this object.

        Please check :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        .. versionadded:: 1.3

        Returns
        -------
        routing : MetadataRouter
            A :class:`~utils.metadata_routing.MetadataRouter` encapsulating
            routing information.
        ownermethod_mappingrQ   rS   )r   	__class__rj   addrK   rM   s    rC   get_metadata_routingz'_MultimetricScorer.get_metadata_routing   s=     A~DNN$;$;<@@ 
mm
,3
 	
rE   N)rj   
__module____qualname____doc__rO   ra   rT   rt   rS   rE   rC   rG   rG   a   s     $ .2 $<*
rE   rG   c                   4    e Zd ZddZd Zd Zd	dZd Zd Zy)
rW   c                 <    || _         || _        || _        || _        y rJ   )_score_func_sign_kwargsri   )rM   
score_funcsignr@   r<   s        rC   rO   z_BaseScorer.__init__   s     %
 /rE   c                     d| j                   v r| j                   d   S t        | j                        j                  }d|v r|d   j                  S y )N	pos_label)r|   r   rz   
parametersdefault)rM   score_func_paramss     rC   _get_pos_labelz_BaseScorer._get_pos_label   sQ    $,,&<<,,%d&6&67BB++$[1999rE   c           
         | j                   dkD  rdnd}d| j                  }dj                  | j                  j	                         D cg c]  \  }}d| d|  c}}      }d| j
                  j                   | | | dS c c}}w )	Nr    z, greater_is_better=Falsez, response_method=z, =zmake_scorer())r{   ri   joinr|   rU   rz   rj   )rM   sign_stringresponse_method_stringkvkwargs_strings         rC   __repr__z_BaseScorer.__repr__   s     JJNb0K#5d6K6K5N!O$,,:L:L:N O$!Q2aS! OP 4++445k]%&}oQ8	
 !Ps   B
Nc                     t        || d       t        j                  |      }|||d<    | j                  t	        t
        d      |||fi |S )a  Evaluate predicted target values for X relative to y_true.

        Parameters
        ----------
        estimator : object
            Trained estimator to use for scoring. Must have a predict_proba
            method; the output of that is used to compute the score.

        X : {array-like, sparse matrix}
            Test data that will be fed to estimator.predict.

        y_true : array-like
            Gold standard target values for X.

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights.

        **kwargs : dict
            Other parameters passed to the scorer. Refer to
            :func:`set_score_request` for more details.

            Only available if `enable_metadata_routing=True`. See the
            :ref:`User Guide <metadata_routing>`.

            .. versionadded:: 1.3

        Returns
        -------
        score : float
            Score function applied to prediction of estimator on X.
        Nsample_weight)r   copydeepcopyrX   r   rD   )rM   r>   Xy_truer   r@   r|   s          rC   ra   z_BaseScorer.__call__   sS    @ 	&$---'$'4GO$t{{7<6	1fXPWXXrE   c                     | j                   
t               n"t        | j                   j                               }|j                  |j                               }|r t	        j
                  | d| t               yy)zWarn if there is any overlap between ``self._kwargs`` and ``kwargs``.

        This method is intended to be used to check for overlap between
        ``self._kwargs`` and ``kwargs`` passed as metadata.
        Nz Overlapping parameters are: )r|   setkeysintersectionwarningswarnUserWarning)rM   messager@   r|   overlaps        rC   _warn_overlapz_BaseScorer._warn_overlap   sc      <</#%S9J9J9L5M&&v{{}5MM)8	BK rE   c                    t               st        d      | j                  d|       t        | j                  j
                        | _        |j                         D ],  \  }}| j                  j                  j                  ||       . | S )aw  Set requested parameters by the scorer.

        Please see :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        .. versionadded:: 1.3

        Parameters
        ----------
        kwargs : dict
            Arguments should be of the form ``param_name=alias``, and `alias`
            can be one of ``{True, False, None, str}``.
        zThis method is only available when metadata routing is enabled. You can enable it using sklearn.set_config(enable_metadata_routing=True).zYou are setting metadata request for parameters which are already set as kwargs for this metric. These set values will be overridden by passed metadata if provided. Please pass them either as metadata or kwargs to `make_scorer`.r   r@   rn   )paramalias)
r   RuntimeErrorr   r   rq   rj   _metadata_requestrU   rQ   add_request)rM   r@   r   r   s       rC   set_score_requestz_BaseScorer.set_score_request  s      !E  	:
  	 	
 "1t~~7N7N!O"LLN 	OLE5""((4454N	OrE   )predictrJ   )	rj   ru   rv   rO   r   r   ra   r   r   rS   rE   rC   rW   rW      s"    0
&YP!rE   rW   c                       e Zd Zd Zy)_Scorerc                    | j                  d|       t        |      rdn| j                         }t        || j                        } |||j
                  ||      }i | j                  |}	| j                   | j                  ||fi |	z  S )a  Evaluate the response method of `estimator` on `X` and `y_true`.

        Parameters
        ----------
        method_caller : callable
            Returns predictions given an estimator, method name, and other
            arguments, potentially caching results.

        estimator : object
            Trained estimator to use for scoring.

        X : {array-like, sparse matrix}
            Test data that will be fed to clf.decision_function or
            clf.predict_proba.

        y_true : array-like
            Gold standard target values for X. These must be class labels,
            not decision function values.

        **kwargs : dict
            Other parameters passed to the scorer. Refer to
            :func:`set_score_request` for more details.

        Returns
        -------
        score : float
            Score function applied to prediction of estimator on X.
        zThere is an overlap between set kwargs of this scorer instance and passed metadata. Please pass them either as kwargs to `make_scorer` or metadata, but not both.r   N)r   )	r   r   r   r   ri   rj   r|   r{   rz   )
rM   method_callerr>   r   r   r@   r   r<   y_predscoring_kwargss
             rC   rX   z_Scorer._score1  s    : 	.  	 	
 )3D9L9L9N	0D<Q<QR//i
 4DLL3F3zz,D,,VVN~NNNrE   N)rj   ru   rv   rX   rS   rE   rC   r   r   0  s    -OrE   r   scoringT)prefer_skip_nested_validationc                     t        | t              r	 t        j                  t        |          }|S | }|S # t
        $ r t        d| z        w xY w)a  Get a scorer from string.

    Read more in the :ref:`User Guide <scoring_parameter>`.
    :func:`~sklearn.metrics.get_scorer_names` can be used to retrieve the names
    of all available scorers.

    Parameters
    ----------
    scoring : str, callable or None
        Scoring method as string. If callable it is returned as is.
        If None, returns None.

    Returns
    -------
    scorer : callable
        The scorer.

    Notes
    -----
    When passed a string, this function always returns a copy of the scorer
    object. Calling `get_scorer` twice for the same scorer results in two
    separate scorer objects.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.dummy import DummyClassifier
    >>> from sklearn.metrics import get_scorer
    >>> X = np.reshape([0, 1, -1, -0.5, 2], (-1, 1))
    >>> y = np.array([0, 1, 1, 0, 1])
    >>> classifier = DummyClassifier(strategy="constant", constant=0).fit(X, y)
    >>> accuracy = get_scorer("accuracy")
    >>> accuracy(classifier, X, y)
    0.4
    z]%r is not a valid scoring value. Use sklearn.metrics.get_scorer_names() to get valid options.)rV   strr   r   _SCORERSKeyError
ValueError)r   r_   s     rC   
get_scorerr   a  se    T '3	]]8G#45F M M  	(*12 	s	   4 Ac                       e Zd Zd Zd Zd Zy)_PassthroughScorerc                     || _         y rJ   )
_estimator)rM   r>   s     rC   rO   z_PassthroughScorer.__init__  s	    #rE   c                 &     |j                   |i |S )z!Method that wraps estimator.scorerR   )rM   r>   r?   r@   s       rC   ra   z_PassthroughScorer.__call__  s    y///rE   c                 ,    t        | j                        S )a\  Get requested data properties.

        Please check :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        .. versionadded:: 1.3

        Returns
        -------
        routing : MetadataRouter
            A :class:`~utils.metadata_routing.MetadataRouter` encapsulating
            routing information.
        )r   r   rs   s    rC   rt   z'_PassthroughScorer.get_metadata_routing  s    ( &doo66rE   N)rj   ru   rv   rO   ra   rt   rS   rE   rC   r   r     s    $07rE   r   c           	          d|d}t        |t        t        t        f      rd}	 t        |      }t        |      t        |      k7  rt        | d|      t        |      dkD  rat        d |D              s2t        d |D              rt        | d	|      t        | d
|      |D ci c]  }|t        | |       }}|S t        | d|      t        |t              rwt        |      }t        d |D              st        d|      t        |      dk(  rt        d|      |j                         D ci c]  \  }}|t        | |       }}}|S t        |      # t        $ r}t        |      |d}~ww xY wc c}w c c}}w )a!  Check the scoring parameter in cases when multiple metrics are allowed.

    In addition, multimetric scoring leverages a caching mechanism to not call the same
    estimator response method multiple times. Hence, the scorer is modified to only use
    a single response method given a list of response methods and the estimator.

    Parameters
    ----------
    estimator : sklearn estimator instance
        The estimator for which the scoring will be applied.

    scoring : list, tuple or dict
        Strategy to evaluate the performance of the cross-validated model on
        the test set.

        The possibilities are:

        - a list or tuple of unique strings;
        - a callable returning a dictionary where they keys are the metric
          names and the values are the metric scores;
        - a dictionary with metric names as keys and callables a values.

        See :ref:`multimetric_grid_search` for an example.

    Returns
    -------
    scorers_dict : dict
        A dict mapping each scorer name to its validated scorer.
    zscoring is invalid (got zh). Refer to the scoring glossary for details: https://scikit-learn.org/stable/glossary.html#term-scoringzFThe list/tuple elements must be unique strings of predefined scorers. Nz2 Duplicate elements were found in the given list. r   c              3   <   K   | ]  }t        |t                y wrJ   rV   r   rd   r   s     rC   rf   z-_check_multimetric_scoring.<locals>.<genexpr>  s     8az!S)8   c              3   2   K   | ]  }t        |        y wrJ   )callabler   s     rC   rf   z-_check_multimetric_scoring.<locals>.<genexpr>  s     1qx{1s   zi One or more of the elements were callables. Use a dict of score name mapped to the scorer callable. Got z4 Non-string types were found in the given list. Got )r   z Empty list was given. c              3   <   K   | ]  }t        |t                y wrJ   r   r   s     rC   rf   z-_check_multimetric_scoring.<locals>.<genexpr>   s     4!:a%4r   zCNon-string types were found in the keys of the given dict. scoring=zAn empty dict was passed. )rV   listtupler   	TypeErrorr   rg   allrk   check_scoringdictrU   )	r>   r   err_msg_genericerr_msgr   r`   r_   rN   keys	            rC   _check_multimetric_scoringr     s    > #7+ .E 	E  'D%-.T 		-w<D t9G$) $$+;0  Y]84881D11$") $  'k+  %") $229> 
 PWEKi@@G , N% y(?{KLL	GT	"7|4t44++2+7  t9>9'EFF  '}}
V y&99
 
 N ))U  	-W%1,	-,
s#   E( -F F
(	F1E==Fc                     |dk7  }|dk7  }| du}|dk(  rdn|}|dk(  rdn|}|r|s|rt        d      |s|rt        j                  dt               |r| S |du r|du rt        d      |du rd} | S |du rd	} | S d
} | S )zmHandles deprecation of `needs_threshold` and `needs_proba` parameters in
    favor of `response_method`.
    
deprecatedNFzYou cannot set both `response_method` and `needs_proba` or `needs_threshold` at the same time. Only use `response_method` since the other two are deprecated in version 1.4 and will be removed in 1.6.zThe `needs_threshold` and `needs_proba` parameter are deprecated in version 1.4 and will be removed in 1.6. You can either let `response_method` be `None` or set it to `predict` to preserve the same behaviour.TzYou cannot set both `needs_proba` and `needs_threshold` at the same time. Use `response_method` instead since the other two are deprecated in version 1.4 and will be removed in 1.6.predict_probadecision_functionr   r   )r   r   r   FutureWarning)r<   needs_thresholdneeds_probaneeds_threshold_providedneeds_proba_providedresponse_method_provideds         rC   _get_response_methodr     s      /,>&,6.d:.,>eOO&,6%KK%9=UV
 	
 7"
 	
  d$69
 	
 d)  
D	 @  $rE   >   r   r   r   booleanr   )r}   r<   greater_is_betterr   r   )r<   r   r   r   c                D    t        |||      }|rdnd}t        | |||      S )a  Make a scorer from a performance metric or loss function.

    A scorer is a wrapper around an arbitrary metric or loss function that is called
    with the signature `scorer(estimator, X, y_true, **kwargs)`.

    It is accepted in all scikit-learn estimators or functions allowing a `scoring`
    parameter.

    The parameter `response_method` allows to specify which method of the estimator
    should be used to feed the scoring/loss function.

    Read more in the :ref:`User Guide <scoring>`.

    Parameters
    ----------
    score_func : callable
        Score function (or loss function) with signature
        ``score_func(y, y_pred, **kwargs)``.

    response_method : {"predict_proba", "decision_function", "predict"} or             list/tuple of such str, default=None

        Specifies the response method to use get prediction from an estimator
        (i.e. :term:`predict_proba`, :term:`decision_function` or
        :term:`predict`). Possible choices are:

        - if `str`, it corresponds to the name to the method to return;
        - if a list or tuple of `str`, it provides the method names in order of
          preference. The method returned corresponds to the first method in
          the list and which is implemented by `estimator`.
        - if `None`, it is equivalent to `"predict"`.

        .. versionadded:: 1.4

    greater_is_better : bool, default=True
        Whether `score_func` is a score function (default), meaning high is
        good, or a loss function, meaning low is good. In the latter case, the
        scorer object will sign-flip the outcome of the `score_func`.

    needs_proba : bool, default=False
        Whether `score_func` requires `predict_proba` to get probability
        estimates out of a classifier.

        If True, for binary `y_true`, the score function is supposed to accept
        a 1D `y_pred` (i.e., probability of the positive class, shape
        `(n_samples,)`).

        .. deprecated:: 1.4
           `needs_proba` is deprecated in version 1.4 and will be removed in
           1.6. Use `response_method="predict_proba"` instead.

    needs_threshold : bool, default=False
        Whether `score_func` takes a continuous decision certainty.
        This only works for binary classification using estimators that
        have either a `decision_function` or `predict_proba` method.

        If True, for binary `y_true`, the score function is supposed to accept
        a 1D `y_pred` (i.e., probability of the positive class or the decision
        function, shape `(n_samples,)`).

        For example `average_precision` or the area under the roc curve
        can not be computed using discrete predictions alone.

        .. deprecated:: 1.4
           `needs_threshold` is deprecated in version 1.4 and will be removed
           in 1.6. Use `response_method=("decision_function", "predict_proba")`
           instead to preserve the same behaviour.

    **kwargs : additional arguments
        Additional parameters to be passed to `score_func`.

    Returns
    -------
    scorer : callable
        Callable object that returns a scalar score; greater is better.

    Examples
    --------
    >>> from sklearn.metrics import fbeta_score, make_scorer
    >>> ftwo_scorer = make_scorer(fbeta_score, beta=2)
    >>> ftwo_scorer
    make_scorer(fbeta_score, response_method='predict', beta=2)
    >>> from sklearn.model_selection import GridSearchCV
    >>> from sklearn.svm import LinearSVC
    >>> grid = GridSearchCV(LinearSVC(), param_grid={'C': [1, 10]},
    ...                     scoring=ftwo_scorer)
    r   )r   r   )r}   r<   r   r   r   r@   r~   s          rC   make_scorerr   B  s2    ^ ++O "1rD:tV_==rE   F)r   c                      t        | |      d   S )Nr   r   r   r   s     rC   positive_likelihood_ratior         "662155rE   c                      t        | |      d   S )Nr   r   r   s     rC   negative_likelihood_ratior     r   rE   r   )r   r<   )r<   r   ovo)r<   multi_classweighted)r<   r   averageovrexplained_variancer2r#   r"   neg_median_absolute_errorneg_mean_absolute_error"neg_mean_absolute_percentage_errorneg_mean_squared_errorneg_mean_squared_log_errorneg_root_mean_squared_errorneg_root_mean_squared_log_errorneg_mean_poisson_devianceneg_mean_gamma_devianceaccuracytop_k_accuracyroc_aucroc_auc_ovrroc_auc_ovoroc_auc_ovr_weightedroc_auc_ovo_weightedbalanced_accuracyaverage_precisionneg_log_lossneg_brier_scorer   neg_negative_likelihood_ratior3   r9   r6   r4   r:   r7   r2   r8   r5   c                  <    t        t        j                               S )a  Get the names of all available scorers.

    These names can be passed to :func:`~sklearn.metrics.get_scorer` to
    retrieve the scorer object.

    Returns
    -------
    list of str
        Names of all available scorers.

    Examples
    --------
    >>> from sklearn.metrics import get_scorer_names
    >>> all_scorers = get_scorer_names()
    >>> type(all_scorers)
    <class 'list'>
    >>> all_scorers[:3]
    ['accuracy', 'adjusted_mutual_info_score', 'adjusted_rand_score']
    >>> "roc_auc" in all_scorers
    True
    )sortedr   r   rS   rE   rC   get_scorer_namesr  L  s    , (--/""rE   	precisionrecallf1jaccardbinary)r   )macromicrosamplesr   z{0}_{1})r   r   fit)r>   r   
allow_none)r  c                n   t        |t              rt        |      S t        |      ret	        |dd      }t        |d      rA|j                  d      r0|j                  d      s|j                  d      st        d|z        t        |      S |(t        | d      rt        |       S |ryt        d	| z        y)
a  Determine scorer from user options.

    A TypeError will be thrown if the estimator cannot be scored.

    Parameters
    ----------
    estimator : estimator object implementing 'fit'
        The object to use to fit the data.

    scoring : str or callable, default=None
        A string (see model evaluation documentation) or
        a scorer callable object / function with signature
        ``scorer(estimator, X, y)``.
        If None, the provided estimator object's `score` method is used.

    allow_none : bool, default=False
        If no scoring is specified and the estimator has no score function, we
        can either return None or raise an exception.

    Returns
    -------
    scoring : callable
        A scorer callable object / function with signature
        ``scorer(estimator, X, y)``.

    Examples
    --------
    >>> from sklearn.datasets import load_iris
    >>> from sklearn.metrics import check_scoring
    >>> from sklearn.tree import DecisionTreeClassifier
    >>> X, y = load_iris(return_X_y=True)
    >>> classifier = DecisionTreeClassifier(max_depth=2).fit(X, y)
    >>> scorer = check_scoring(classifier, scoring='accuracy')
    >>> scorer(classifier, X, y)
    0.96...
    ru   N
startswithzsklearn.metrics.zsklearn.metrics._scorerzsklearn.metrics.tests.zscoring value %r looks like it is a metric function rather than a scorer. A scorer should require an estimator as its first parameter. Please use `make_scorer` to convert a metric to a scorer.rQ   ziIf no scoring is specified, the estimator passed should have a 'score' method. The estimator %r does not.)
rV   r   r   r   getattrhasattrr  r   r   r   )r>   r   r  modules       rC   r   r   q  s    Z '3'"",5FL)!!"45%%&?@%%&>? ")	)  '""9g&%i00DFOP  rE   rS   rJ   )rw   r   r   collectionsr   	functoolsr   inspectr   	tracebackr   baser   utilsr	   utils._param_validationr
   r   r   r   utils._responser   utils.metadata_routingr   r   r   r   r   r   r   utils.validationr   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   clusterr2   r3   r4   r5   r6   r7   r8   r9   r:   rD   rG   rW   r   r   r   r   r   r   r   r   r   r   explained_variance_scorer	r2_scorermax_error_scorerneg_mean_squared_error_scorer!neg_mean_squared_log_error_scorerneg_mean_absolute_error_scorer)neg_mean_absolute_percentage_error_scorer neg_median_absolute_error_scorer"neg_root_mean_squared_error_scorer&neg_root_mean_squared_log_error_scorer neg_mean_poisson_deviance_scorerneg_mean_gamma_deviance_scoreraccuracy_scorerbalanced_accuracy_scorermatthews_corrcoef_scorerr   r    positive_likelihood_ratio_scorer$neg_negative_likelihood_ratio_scorertop_k_accuracy_scorerroc_auc_scoreraverage_precision_scorerroc_auc_ovo_scorerroc_auc_ovo_weighted_scorerroc_auc_ovr_scorerroc_auc_ovr_weighted_scorerneg_log_loss_scorerneg_brier_score_scorerbrier_score_loss_scoreradjusted_rand_scorerrand_scorerhomogeneity_scorercompleteness_scorerv_measure_scorermutual_info_scoreradjusted_mutual_info_scorernormalized_mutual_info_scorerfowlkes_mallows_scorerr   r   r  r^   metricr   formatqualified_namer   r   rS   rE   rC   <module>rG     s  (          U U 2   6      6
 
 
Z
 Z
zo$ od.Ok .Ob C4( #'	//d7 7>Vr.b jHI	
 ([!6*l^*D#EF%vj,.H'IJ #'$  d>d>P ((@A !	yEB  +,>RW X $/e% ! "-5"  -8"e- ) $/U$   &1u& " *55* & $/U$   "-5" 
 n-&'>? &'89 66 $//H#I  '2( $
 $: 
 :
 ':  !?  *#	  !?  *#	  "  %  &  ##67 *% !23 !"45 /  !23 )*DE  +,H I $%:;   %0%% % /	%
 ?% ;% (Q% 9%  A% !C% %K% ?% ;% % )%  !%" ##%$ #%%& 5'%( 5)%* /+%, /-%. %/%0 +1%2 ?3%4 #G5%8 -9%: ;%< )=%> +?%@ %A%B )C%D  ;E%F "?G%H 1I%P#4 /"|	8	 	XLD& !:HTN< X"))$8#.vw#W X	X  '(s#3#5674H k
 #'A AArE   