
    sg+                     b   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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!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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z? ddl@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZI d ZJ G d d      ZK G d de      ZL G d deL      ZM edeNeOdgid      d        ZP G d de      ZQd ZRd  ZS eeOgdeTeU eh d!       e ed"h            gd#gd$d      d"dd%d&       ZV eVe,      ZW eVe:      ZX eVe1d'(      ZY eVe1d'(      ZZd)Z[e[eZ_\         eVe6d'(      Z] eVe7d'(      Z^ eVe2d'(      Z_ eVe3d'(      Z` eVe8d'(      Za eVe=d'(      Zb eVe>d'(      Zc eVe5d'(      Zd eVe4d'(      Ze eVe+      Zf eVe&      Zg eVe(      Zh eVe0      Zid* Zjd+ Zk eVej      Zl eVekd'(      Zm eVe?dd,-      Zn eVe<dd,-      Zo eVe'd,.      Zp eVe<d/d01      Zq eVe<d/d0d23      Zr eVe<d/d41      Zs eVe<d/d4d23      Zt eVe/d'd/-      Zu eVe)d'd/-      Zv eVe)d'd/-      Zw eVeB      Zx eVeH      Zy eVeE      Zz eVeC      Z{ eVeI      Z| eVeF      Z} eVeA      Z~ eVeG      Z eVeD      Z edji d5eWd6eXd7eYd8eid9ead:e_d;e`d<e]d=e^d>ebd?ecd@eddAeedBefdCegdDendEeodFesdGeqdHetdIerdJehdKepdLeudMevdNeldOemdPexdQeydRezdSe{dTe|dUe}dVe~dWedXeZdY ZdZe9fd[e;fd\e-fd]e.ffD ]:  \  ZZ eVed^_      ee<   d`D ]#  Zdaj                  ee      Z eVedeb      ee<   % <  e edc      dg e e e                   eOeTeeUedgd#gd#gddd      dkd'ddedf       Zdg Z G dh dieL      Zy)laH  
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)Integral)
format_exc   )is_regressor)Bunch)
HasMethodsHidden
StrOptionsvalidate_params_get_response_values)MetadataRequestMetadataRouterMethodMapping_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d2_absolute_error_score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          J/var/www/html/venv/lib/python3.12/site-packages/sklearn/metrics/_scorer.py_cached_callrG   U   sZ    _5_%%$*9=CIFA !'oM    c                   4    e Zd ZdZdddZ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scorersrK   s      rF   __init__z_MultimetricScorer.__init__w   s    #rH   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rT    )
_use_cacher   rG   r   r   r
   rN   items
isinstance_BaseScorer_scoregetrT   	ExceptionrO   r   )rP   rA   rB   rC   scoresr@   cached_callrouted_paramsnamescorerrT   es               rF   __call__z_MultimetricScorer.__call__{   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                 r    dj                  | j                  D cg c]  }d| d
 c}      }d| dS c c}w )N, "zMultiMetricScorer())joinrN   )rP   srQ   s      rF   __repr__z_MultimetricScorer.__repr__   s;    ))t}}=!q1X=>#G9A.. >s   4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   NrV   ).0vals     rF   	<genexpr>z0_MultimetricScorer._use_cache.<locals>.<genexpr>   s     33sQw3s   T)
lenrN   r   valuesrY   rZ   r   _response_method__name__any)rP   rA   rb   counters       rF   rW   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t               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_mappingrT   )callercalleerV   )r   	__class__rt   addrN   r   rP   s    rF   get_metadata_routingz'_MultimetricScorer.get_metadata_routing   sO     A~DNN$;$;<@@ 
mm
(?..gg.N
 	
rH   N)	rt   
__module____qualname____doc__rR   rd   rk   rW   r   rV   rH   rF   rJ   rJ   d   s%    $ .2 $</*
rH   rJ   c                   8    e Zd ZdZd	dZd Zd Zd
dZd Zd Z	y)rZ   a>  Base scorer that is used as `scorer(estimator, X, y_true)`.

    Parameters
    ----------
    score_func : callable
        The score function to use. It will be called as
        `score_func(y_true, y_pred, **kwargs)`.

    sign : int
        Either 1 or -1 to returns the score with `sign * score_func(estimator, X, y)`.
        Thus, `sign` defined if higher scores are better or worse.

    kwargs : dict
        Additional parameters to pass to the score function.

    response_method : str
        The method to call on the estimator to get the response values.
    c                 J    || _         || _        || _        || _        d | _        y rM   )_score_func_sign_kwargsrs   _deprecation_msg)rP   
score_funcsignrC   r?   s        rF   rR   z_BaseScorer.__init__   s(    %
 / $rH   c                     d| j                   v r| j                   d   S t        | j                        j                  }d|v r|d   j                  S y )N	pos_label)r   r   r   
parametersdefault)rP   score_func_paramss     rF   _get_pos_labelz_BaseScorer._get_pos_label   sQ    $,,&<<,,%d&6&67BB++$[1999rH   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=rf   =zmake_scorer(rh   )r   rs   ri   r   rX   r   rt   )rP   sign_stringresponse_method_stringkvkwargs_strings         rF   rk   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                     | j                   &t        j                  | j                   t        d       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.
        Nr   )category
stacklevelsample_weight)
r   warningswarnDeprecationWarningr   copydeepcopyr[   r   rG   )rP   rA   Xy_truer   rC   r   s          rF   rd   z_BaseScorer.__call__   s{    B   ,MM%%0Bq 	&$---'$'4GO$t{{7<6	1fXPWXXrH   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intersectionr   r   UserWarning)rP   messagerC   r   overlaps        rF   _warn_overlapz_BaseScorer._warn_overlap"  sc      <</#%S9J9J9L5M&&v{{}5MM)8	BK rH   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}``.
        This 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   rC   rx   paramalias)
r   RuntimeErrorr   r   r}   rt   _metadata_requestrX   rT   add_requestrP   rC   r   r   s       rF   set_score_requestz_BaseScorer.set_score_request/  s      !E  	:
  	 	
 "1t~~7N7N!O"LLN 	OLE5""((4454N	OrH   )predictrM   )
rt   r   r   r   rR   r   rk   rd   r   r   rV   rH   rF   rZ   rZ      s'    &%
,Y\!rH   rZ   c                       e Zd Zd Zy)_Scorerc                    | j                  d|       t        |      rdn| j                         }t        || j                        } ||t        |      ||      }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   rs   _get_response_method_namer   r   r   )
rP   method_callerrA   r   r   rC   r   r?   y_predscoring_kwargss
             rF   r[   z_Scorer._scoreT  s    : 	.  	 	
 )3D9L9L9N	0D<Q<QR%o6	
 4DLL3F3zz,D,,VVN~NNNrH   N)rt   r   r   r[   rV   rH   rF   r   r   S  s    0OrH   r   scoringT)prefer_skip_nested_validationc                     t        | t              r+	 | dk(  rt        }n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
    r&   z]%r is not a valid scoring value. Use sklearn.metrics.get_scorer_names() to get valid options.)rY   strmax_error_scorerr   r   _SCORERSKeyError
ValueError)r   rb   s     rF   
get_scorerr     st    T '3	+% *x'89 M M  	(*12 	s   (A   Ac                   *    e Zd Zd Zd Zd Zd Zd Zy)_PassthroughScorerc                 p   || _         t        | j                  j                        }	 t	        j
                  |j                  j                        |_        || _        y # t        $ rM 	 t	        j
                  |j                         j                        |_        n# t        $ r Y nw xY wY || _        y w xY w)Nrx   )

_estimatorr   r}   rt   r   r   r   rT   AttributeError_get_default_requests)rP   rA   requestss      rF   rR   z_PassthroughScorer.__init__  s    #")@)@A	!]]9+F+F+L+LMHN "*  	!%y/N/N/P/V/V!W!  "*	s5   .A 	B5)2BB5	B(%B5'B((B54B5c                 &     |j                   |i |S )z!Method that wraps estimator.scorerU   )rP   rA   rB   rC   s       rF   rd   z_PassthroughScorer.__call__  s    y///rH   c                 4    | j                   j                   dS )Nz.score)r   r}   r   s    rF   rk   z_PassthroughScorer.__repr__  s    //++,F33rH   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   r   s    rF   r   z'_PassthroughScorer.get_metadata_routing  s     &d&<&<==rH   c                     t               st        d      |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.5

        Parameters
        ----------
        kwargs : dict
            Arguments should be of the form ``param_name=alias``, and `alias`
            can be one of ``{True, False, None, str}``.
        r   r   )r   r   rX   r   rT   r   r   s       rF   r   z$_PassthroughScorer.set_score_request  s^      !E  #LLN 	OLE5""((4454N	OrH   N)rt   r   r   rR   rd   rk   r   r   rV   rH   rF   r   r     s    *04> rH   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rM   rY   r   rn   r   s     rF   rp   z-_check_multimetric_scoring.<locals>.<genexpr>:  s     8az!S)8   c              3   2   K   | ]  }t        |        y wrM   )callabler   s     rF   rp   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rM   r   r   s     rF   rp   z-_check_multimetric_scoring.<locals>.<genexpr>O  s     4!:a%4r   zCNon-string types were found in the keys of the given dict. scoring=zAn empty dict was passed. )rY   listtupler   	TypeErrorr   rq   allru   check_scoringdictrX   )	rA   r   err_msg_genericerr_msgr   rc   rb   rQ   keys	            rF   _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    	 | j                   S # t        $ r t        | j                        cY S w xY wrM   )rt   r   r   funcr?   s    rF   r   r   `  s3    ?''' ?()=)=>>?s    //>   r   predict_probadecision_functionr   boolean)r   r?   greater_is_better)r?   r   c                v    |rdnd}|t        j                  dt               d}n|dk(  r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_callable>`.

    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

        .. deprecated:: 1.6
            None is equivalent to 'predict' and is deprecated. It will be removed in
            version 1.8.

    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`.

    **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   zresponse_method=None is deprecated in version 1.6 and will be removed in version 1.8. Leave it to its default value to avoid this warning.r   r   )r   r   FutureWarningr   )r   r?   r   rC   r   s        rF   make_scorerr   g  sN    ^ "1rDS	

 $	I	%#:tV_==rH   F)r   z`Scoring method max_error was renamed to neg_max_error in version 1.6 and will be removed in 1.8.c                      t        | |      d   S )Nr   r   r   r   s     rF   positive_likelihood_ratior         "662155rH   c                      t        | |      d   S )Nr   r   r   s     rF   negative_likelihood_ratior     r   rH   )r   r   )r   r?   r   r   ovo)r?   multi_classweighted)r?   r   averageovrexplained_variancer2neg_max_errorr%   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_deviancer    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_ratior6   r<   r9   r7   r=   r:   r5   r;   r8   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   rV   rH   rF   get_scorer_namesr  c  s    , (--/""rH   	precisionrecallf1jaccardbinary)r   )macromicrosamplesr   z{0}_{1})r   r   fit)rA   r   
allow_nonerK   )r#  rK   c                   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        |t        t        t        t        f      rt        | |      }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' or None, default=None
        The object to use to fit the data. If `None`, then this function may error
        depending on `allow_none`.

    scoring : str, callable, list, tuple, set, or dict, default=None
        Scorer to use. If `scoring` represents a single score, one can use:

        - a single string (see :ref:`scoring_parameter`);
        - a callable (see :ref:`scoring_callable`) that returns a single value.

        If `scoring` represents multiple scores, one can use:

        - a list, tuple or set of unique strings;
        - a callable returning a dictionary where the keys are the metric names and the
          values are the metric scorers;
        - a dictionary with metric names as keys and callables a values. The callables
          need to have the signature `callable(estimator, X, y)`.

        If None, the provided estimator object's `score` method is used.

    allow_none : bool, default=False
        Whether to return None or raise an error if no `scoring` is specified and the
        estimator has no `score` method.

    raise_exc : bool, default=True
        Whether to raise an exception (if a subset of the scorers in multimetric scoring
        fails) or to return an error code.

        - If set to `True`, raises the failing scorer's exception.
        - If set to `False`, a formatted string of the exception details is passed as
          result of the failing scorer(s).

        This applies if `scoring` is list, tuple, set, or dict. Ignored if `scoring` is
        a str or a callable.

        .. versionadded:: 1.6

    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...

    >>> from sklearn.metrics import make_scorer, accuracy_score, mean_squared_log_error
    >>> X, y = load_iris(return_X_y=True)
    >>> y *= -1
    >>> clf = DecisionTreeClassifier().fit(X, y)
    >>> scoring = {
    ...     "accuracy": make_scorer(accuracy_score),
    ...     "mean_squared_log_error": make_scorer(mean_squared_log_error),
    ... }
    >>> scoring_call = check_scoring(estimator=clf, scoring=scoring, raise_exc=False)
    >>> scores = scoring_call(clf, X, y)
    >>> scores
    {'accuracy': 1.0, 'mean_squared_log_error': 'Traceback ...'}
    r   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.r   )rQ   rK   rT   ziIf no scoring is specified, the estimator passed should have a 'score' method. The estimator %r does not.)rY   r   r   r   getattrhasattrr%  r   r   r   r   r   r   rJ   r   r   )rA   r   r#  rK   modulerQ   s         rF   r   r     s    t '3'"",5FL)!!"45%%&?@%%&>? ")	)  '""'D%d34,YH!'YGG9g&%i00DFOP  rH   c                    |t        j                  ddg      }nMt        j                  ||k(        d   }t        j                  ||k7        d   }t        j                  ||g      }||| |k\  j                  t                    S )z;Threshold `y_score` and return the associated class labels.r   r   )nparrayflatnonzeroastypeint)y_score	thresholdclassesr   map_thresholded_score_to_labelpos_label_idxneg_label_idxs          rF   !_threshold_scores_to_class_labelsr5    s    )+1a&)9&w)';<Q?w)';<Q?)+=-2P)Q&17i3G2O2OPS2TUVVrH   c                   8     e Zd ZdZ fdZed        Zd Z xZS )_CurveScorera  Scorer taking a continuous response and output a score for each threshold.

    Parameters
    ----------
    score_func : callable
        The score function to use. It will be called as
        `score_func(y_true, y_pred, **kwargs)`.

    sign : int
        Either 1 or -1 to returns the score with `sign * score_func(estimator, X, y)`.
        Thus, `sign` defined if higher scores are better or worse.

    kwargs : dict
        Additional parameters to pass to the score function.

    thresholds : int or array-like
        Related to the number of decision thresholds for which we want to compute the
        score. If an integer, it will be used to generate `thresholds` thresholds
        uniformly distributed between the minimum and maximum predicted scores. If an
        array-like, it will be used as the thresholds.

    response_method : str
        The method to call on the estimator to get the response values.
    c                 :    t         |   ||||       || _        y )N)r   r   rC   r?   )superrR   _thresholds)rP   r   r   rC   
thresholdsr?   r}   s         rF   rR   z_CurveScorer.__init__*  s+    !+	 	 	
 &rH   c                      | |j                   |j                  |||j                        }|j                         |_        |S )z0Create a continuous scorer from a normal scorer.)r   r   r?   r;  rC   )r   r   r   _get_metadata_requestr   )clsrb   r?   r;  instances        rF   from_scorerz_CurveScorer.from_scorer3  sC     ))+!>>
 &,%A%A%C"rH   c                 0   | j                         } ||| j                  ||      }i | j                  |}t        | j                  t
              rHt        j                  t        j                  |      t        j                  |      | j                        }	nt        j                  | j                        }	|	D 
cg c]9  }
| j                   | j                  |t        ||
|j                  |      fi |z  ; }}
t        j                  |      |	fS c c}
w )a  Evaluate predicted target values for X relative to 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} of shape (n_samples, n_features)
            Test data that will be fed to estimator.predict.

        y_true : array-like of shape (n_samples,)
            Gold standard target values for X.

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

        Returns
        -------
        scores : ndarray of shape (thresholds,)
            The scores associated to each threshold.

        potential_thresholds : ndarray of shape (thresholds,)
            The potential thresholds used to compute the scores.
        r   )r   rs   r   rY   r:  r   r*  linspaceminmaxasarrayr   r   r5  classes_r+  )rP   r   rA   r   r   rC   r   r/  r   potential_thresholdsthscore_thresholdss               rF   r[   z_CurveScorer._scoreA  s   < '')	t,,a9
 4DLL3F3d&&1#%;;w$2B2B$  $&::d.>.>#?  +

  JJd1R!3!3Y
 !

 

 xx()+???

s   <>D)	rt   r   r   r   rR   classmethodr@  r[   __classcell__)r}   s   @rF   r7  r7    s'    2&  5@rH   r7  rV   )NN)r   r   r   collectionsr   	functoolsr   inspectr   numbersr   	tracebackr   numpyr*  baser	   utilsr
   utils._param_validationr   r   r   r   utils._responser   utils.metadata_routingr   r   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/   r0   r1   r2   r3   r4   clusterr5   r6   r7   r8   r9   r:   r;   r<   r=   rG   rJ   rZ   r   r   r   r   r   r   r   r   r   r   explained_variance_scorer	r2_scorerneg_max_error_scorerr   deprecation_msgr   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d2_absolute_error_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  ra   metricr   formatqualified_namer   r   r5  r7  rV   rH   rF   <module>r     sa  $            U U 2	 	 	 6      8
 
 
_
 _
DJ$ JZ1Ok 1Oh C4( #'	44n@+ @FVr? jHI:yk*+
 ([
 #' $-M>M>b ((@A !	"9F yEB  
 %4  ! +,>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)&* 5+&, /-&. //&0 %1&2 +3&4 ?5&6 #G7&: -;&< =&> )?&@ +A&B %C&D )E&F  ;G&H "?I&J 1K&R#4 /"|	8	 	XLD& !:HTN< X"))$8#.vw#W X	X  '.s+-./
 !k[ #'"het h#"hV	Wf@; f@rH   