U
    }h<                  $   @   s  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ZddlmZ dd	lmZ dd
l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 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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZA dd ZBG dd dZCG dd deZDG dd deDZEG dd deDZFG dd deDZGedeHeIdgiddd d! ZJG d"d# d#ZKd$d% ZLeeIgd&gd&gd&gd'dddd(d(d)d*d+ZMeMe&ZNeMe4ZOeMe+d(d,ZPeMe0d(d,ZQeMe1d(d,ZReMe,d(d,ZSeMe-d(d,ZTeMe2d(d,ZUeMe0d(d(d-ZVeMe/d(d,ZWeMe.d(d,ZXeMe!ZYeMe#ZZeMe*Z[d.d/ Z\d0d1 Z]eMe\Z^eMe]d(d,Z_eMe7ddd2Z`eMe6ddd2ZaeMe"dd3ZbeMe6dd4d5ZceMe6dd4d6d7ZdeMe6dd8d5ZeeMe6dd8d6d7ZfeMe)d(dd9ZgeMe$d(dd9ZheMe$d(dd9ZieMe:ZjeMe@ZkeMe=ZleMe;ZmeMeAZneMe>ZoeMe9ZpeMe?ZqeMe<ZreseNeOePe[eUeSeTeQeReVeWeXeYe`eaeeecefedeZebegehe^e_ejekelemeneoepeqerd:"Ztd;d< Zud=e3fd>e5fd?e'fd@e(ffD ]D\ZvZweMewdAdBetev< dCD ]$ZxdDyevexZzeMewdexdEetez< qqeedFgee{eu eIdgd&gdGdddKd(dHdIdJZ|dS )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)
format_exc   )is_regressorBunch)
HasMethods
StrOptionsvalidate_params_get_response_values)MetadataRequestMetadataRouter_MetadataRequester_routing_enabledget_routing_for_objectprocess_routing)type_of_target   )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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                 O   sH   | dk	r|| kr| | S t |f|d|i|\}}| dk	rD|| |< |S )z/Call estimator with method and args and kwargs.Nresponse_methodr   )cache	estimatorr7   argskwargsresult_ r>   ;/tmp/pip-unpacked-wheel-ig1s1lm8/sklearn/metrics/_scorer.py_cached_callQ   s    
r@   c                   @   s6   e Zd ZdZddddZdd Zdd	 Zd
d ZdS )_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                C   s   || _ || _d S N)_scorers
_raise_exc)selfscorersrB   r>   r>   r?   __init__s   s    z_MultimetricScorer.__init__c                    s   i }|  |ri nd}tt|}t r4t| d }ntf  fdd| jD }| j D ]\}}	zLt|	t	r|	j
||f|||j}
n|	|f|||j}
|
||< W qX tk
r } z| jr|n
t ||< W 5 d}~X Y qXX qX|S )z!Evaluate predicted target values.Nscorec                    s   i | ]}|t  d qS )rI   r   ).0namer;   r>   r?   
<dictcomp>   s      z/_MultimetricScorer.__call__.<locals>.<dictcomp>)
_use_cacher   r@   r   r   r	   rD   items
isinstance_BaseScorer_scoregetrI   	ExceptionrE   r   )rF   r9   r:   r;   Zscoresr8   Zcached_callZrouted_paramsrL   scorerrI   er>   rM   r?   __call__w   s4    

 
z_MultimetricScorer.__call__c                    s   t | jdkrdS tdd | j D  t fddtttfD rJdS  t r|t|rf t rfdS  t r|t	|ds|dS dS )	a  Return True if using a cache is beneficial.

        Caching may be beneficial when one of these conditions holds:
          - `_ProbaScorer` will be called twice.
          - `_PredictScorer` will be called twice.
          - `_ThresholdScorer` will be called twice.
          - `_ThresholdScorer` and `_PredictScorer` are called and
             estimator is a regressor.
          - `_ThresholdScorer` and `_ProbaScorer` are called and
             estimator does not have a `decision_function` attribute.

        r   Fc                 S   s   g | ]}t |qS r>   )type)rK   vr>   r>   r?   
<listcomp>   s     z1_MultimetricScorer._use_cache.<locals>.<listcomp>c                 3   s   | ]} | d kV  qdS )r   Nr>   )rK   Z
known_typecounterr>   r?   	<genexpr>   s   z0_MultimetricScorer._use_cache.<locals>.<genexpr>Tdecision_function)
lenrD   r   valuesany_PredictScorer_ProbaScorer_ThresholdScorerr   hasattrrF   r9   r>   r\   r?   rO      s    z_MultimetricScorer._use_cachec                 C   s    t | jjdjf | 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.
        ownerZmethod_mappingrI   )r   	__class____name__addrD   rF   r>   r>   r?   get_metadata_routing   s
    z'_MultimetricScorer.get_metadata_routingN)rk   
__module____qualname____doc__rH   rX   rO   rn   r>   r>   r>   r?   rA   `   s
   rA   c                   @   sF   e Zd Zdd Zdd Zdd Zddd	Zd
d Zdd Zdd Z	dS )rR   c                 C   s   || _ || _|| _d S rC   )_kwargs_score_func_sign)rF   
score_funcsignr;   r>   r>   r?   rH      s    z_BaseScorer.__init__c                 C   s6   d| j kr| j d S t| jj}d|kr2|d jS d S )N	pos_label)rr   r   rs   
parametersdefault)rF   Zscore_func_paramsr>   r>   r?   _get_pos_label   s    


z_BaseScorer._get_pos_labelc                 C   s@   d dd | j D }d| jj| jdkr0dnd|  |f S )N c                 S   s$   g | ]\}}d t |t |f qS )z, %s=%s)str)rK   krZ   r>   r>   r?   r[      s     z(_BaseScorer.__repr__.<locals>.<listcomp>zmake_scorer(%s%s%s%s)r   z, greater_is_better=False)joinrr   rP   rs   rk   rt   _factory_args)rF   Zkwargs_stringr>   r>   r?   __repr__   s    z_BaseScorer.__repr__Nc                 K   sF   |rt  stdt|}|dk	r,||d< | jttd|||f|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.
        zbkwargs is only supported if enable_metadata_routing=True. See the User Guide for more information.Nsample_weight)r   
ValueErrorcopydeepcopyrS   r   r@   )rF   r9   Xy_truer   r;   rr   r>   r>   r?   rX      s     

z_BaseScorer.__call__c                 C   s   dS )z2Return non-default make_scorer arguments for repr.r{   r>   rm   r>   r>   r?   r     s    z_BaseScorer._factory_argsc                 C   sJ   | j dkrt nt| j  }|| }|rFt| d| t dS )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: )rr   setkeysintersectionwarningswarnUserWarning)rF   messager;   rr   overlapr>   r>   r?   _warn_overlap  s     z_BaseScorer._warn_overlapc                 K   sF   | j d|d t| jjd| _| D ]\}}| jjj||d q&| 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}``.
        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;   rh   )paramalias)r   r   rj   rk   Z_metadata_requestrP   rI   Zadd_request)rF   r;   r   r   r>   r>   r?   set_score_request  s    	z_BaseScorer.set_score_request)N)
rk   ro   rp   rH   rz   r   rX   r   r   r   r>   r>   r>   r?   rR      s   
,rR   c                   @   s   e Zd Zdd ZdS )rc   c                 K   s:   | j d|d ||d|}| j|}| j| j||f| S )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. Must have a `predict`
            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.

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

            .. versionadded:: 1.3

        Returns
        -------
        score : float
            Score function applied to prediction of estimator on X.
        There 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   predict)r   rr   rt   rs   )rF   method_callerr9   r   r   r;   y_predscoring_kwargsr>   r>   r?   rS   ;  s    
z_PredictScorer._scoreN)rk   ro   rp   rS   r>   r>   r>   r?   rc   :  s   rc   c                   @   s   e Zd Zdd Zdd ZdS )rd   c                 K   sB   | j d|d ||d||  d}| j|}| j| j||f| S )a  Evaluate predicted probabilities for X relative to y_true.

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

        clf : object
            Trained classifier 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 clf.predict_proba.

        y : array-like
            Gold standard target values for X. These must be class labels,
            not probabilities.

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

            .. versionadded:: 1.3

        Returns
        -------
        score : float
            Score function applied to prediction of estimator on X.
        r   r   predict_probarw   )r   rz   rr   rt   rs   )rF   r   clfr   yr;   r   r   r>   r>   r?   rS   g  s    	
z_ProbaScorer._scorec                 C   s   dS )Nz, needs_proba=Truer>   rm   r>   r>   r?   r     s    z_ProbaScorer._factory_argsNrk   ro   rp   rS   r   r>   r>   r>   r?   rd   f  s   ,rd   c                   @   s   e Zd Zdd Zdd ZdS )re   c           
   	   K   s   | j d|d t|}|dkr,td|t|rB||d|}n|  }z4||d||d}t|tr|t	dd	 |D j
}W nH ttfk
r   ||d
||d}t|trt	dd	 |D j
}Y nX | j|}	| j| j||f|	 S )a'  Evaluate decision function output for X relative to y_true.

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

        clf : object
            Trained classifier to use for scoring. Must have either a
            decision_function method or 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 clf.decision_function or
            clf.predict_proba.

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

            .. versionadded:: 1.3

        Returns
        -------
        score : float
            Score function applied to prediction of estimator on X.
        r   r   )binaryzmultilabel-indicatorz{0} format is not supportedr   r_   r   c                 S   s   g | ]}|qS r>   r>   rK   pr>   r>   r?   r[     s     z+_ThresholdScorer._score.<locals>.<listcomp>r   c                 S   s   g | ]}|d d df qS )Nr>   r   r>   r>   r?   r[     s     )r   r   r   formatr   rz   rQ   listnpZvstackTNotImplementedErrorAttributeErrorrr   rt   rs   )
rF   r   r   r   r   r;   Zy_typer   rw   r   r>   r>   r?   rS     s(    !	


z_ThresholdScorer._scorec                 C   s   dS )Nz, needs_threshold=Truer>   rm   r>   r>   r?   r     s    z_ThresholdScorer._factory_argsNr   r>   r>   r>   r?   re     s   Are   scoringT)Zprefer_skip_nested_validationc                 C   sH   t | tr@ztt|  }W qD tk
r<   td|  Y qDX n| }|S )az  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.
    z]%r is not a valid scoring value. Use sklearn.metrics.get_scorer_names() to get valid options.)rQ   r|   r   r   _SCORERSKeyErrorr   )r   rV   r>   r>   r?   
get_scorer  s    
r   c                   @   s$   e Zd Zdd Zdd Zdd ZdS )_PassthroughScorerc                 C   s
   || _ d S rC   )
_estimatorrg   r>   r>   r?   rH   
  s    z_PassthroughScorer.__init__c                 O   s   |j ||S )z!Method that wraps estimator.scorerJ   )rF   r9   r:   r;   r>   r>   r?   rX     s    z_PassthroughScorer.__call__c                 C   s"   t | jjjd}t| j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.
        rh   )r   r   rj   rk   r   rI   )rF   resr>   r>   r?   rn     s    z'_PassthroughScorer.get_metadata_routingN)rk   ro   rp   rH   rX   rn   r>   r>   r>   r?   r   	  s   r   c              
      sr  d|d}t |tttfrd}zt|}W n, tk
rX } zt||W 5 d}~X Y nX t|t|kr~t| d|n|t|dkrtdd |D std	d |D rt| d
|nt| d| fdd|D }nt| d|nrt |t	rft|}tdd |D s2td|t|dkrNtd| fdd|
 D }nt||S )a  Check the scoring parameter in cases when multiple metrics are allowed.

    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                 s   s   | ]}t |tV  qd S rC   rQ   r|   rK   r}   r>   r>   r?   r^   V  s     z-_check_multimetric_scoring.<locals>.<genexpr>c                 s   s   | ]}t |V  qd S rC   )callabler   r>   r>   r?   r^   W  s     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 c                    s   i | ]}|t  |d qS )r   check_scoring)rK   rV   r9   r>   r?   rN   c  s     z._check_multimetric_scoring.<locals>.<dictcomp>z Empty list was given. c                 s   s   | ]}t |tV  qd S rC   r   r   r>   r>   r?   r^   k  s     zCNon-string types were found in the keys of the given dict. scoring=zAn empty dict was passed. c                    s   i | ]\}}|t  |d qS r   r   )rK   keyrV   r   r>   r?   rN   r  s    )rQ   r   tupler   	TypeErrorr   r`   allrb   dictrP   )r9   r   Zerr_msg_genericerr_msgr   rW   rG   r>   r   r?   _check_multimetric_scoring'  sN    


r   boolean)ru   greater_is_betterneeds_probaneeds_thresholdF)r   r   r   c                K   s@   |rdnd}|r|rt d|r&t}n|r0t}nt}|| ||S )a  Make a scorer from a performance metric or loss function.

    This factory function wraps scoring functions for use in
    :class:`~sklearn.model_selection.GridSearchCV` and
    :func:`~sklearn.model_selection.cross_val_score`.
    It takes a score function, such as :func:`~sklearn.metrics.accuracy_score`,
    :func:`~sklearn.metrics.mean_squared_error`,
    :func:`~sklearn.metrics.adjusted_rand_score` or
    :func:`~sklearn.metrics.average_precision_score`
    and returns a callable that scores an estimator's output.
    The signature of the call is `(estimator, X, y)` where `estimator`
    is the model to be evaluated, `X` is the data and `y` is the
    ground truth labeling (or `None` in the case of unsupervised models).

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

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

    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.

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

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

    Notes
    -----
    If `needs_proba=False` and `needs_threshold=False`, the score
    function is supposed to accept the output of :term:`predict`. If
    `needs_proba=True`, the score function is supposed to accept the
    output of :term:`predict_proba` (For binary `y_true`, the score function is
    supposed to accept probability of the positive class). If
    `needs_threshold=True`, the score function is supposed to accept the
    output of :term:`decision_function` or :term:`predict_proba` when
    :term:`decision_function` is not present.

    Examples
    --------
    >>> from sklearn.metrics import fbeta_score, make_scorer
    >>> ftwo_scorer = make_scorer(fbeta_score, beta=2)
    >>> ftwo_scorer
    make_scorer(fbeta_score, 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   z@Set either needs_proba or needs_threshold to True, but not both.)r   rd   re   rc   )ru   r   r   r   r;   rv   clsr>   r>   r?   make_scorer{  s    ^r   )r   )r   Zsquaredc                 C   s   t | |d S )Nr   r   r   r   r>   r>   r?   positive_likelihood_ratio	  s    r   c                 C   s   t | |d S )Nr   r   r   r>   r>   r?   negative_likelihood_ratio  s    r   )r   r   )r   Zovo)r   multi_classweighted)r   r   averageZovr)r   r   )"Zexplained_varianceZr2r!   r    Zneg_median_absolute_errorZneg_mean_absolute_errorZ"neg_mean_absolute_percentage_errorZneg_mean_squared_errorZneg_mean_squared_log_errorZneg_root_mean_squared_errorZneg_mean_poisson_devianceZneg_mean_gamma_devianceZaccuracyZtop_k_accuracyZroc_aucZroc_auc_ovrZroc_auc_ovoZroc_auc_ovr_weightedZroc_auc_ovo_weightedZbalanced_accuracyZaverage_precisionZneg_log_lossZneg_brier_scorer   Zneg_negative_likelihood_ratior/   r5   r2   r0   r6   r3   r.   r4   r1   c                   C   s   t t S )zGet 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.
    )sortedr   r   r>   r>   r>   r?   get_scorer_namesd  s    r   Z	precisionZrecallf1Zjaccardr   )r   )macromicroZsamplesr   z{0}_{1})rw   r   Zfit)r9   r   
allow_none)r   c                C   s   t |trt|S t|rbt|dd}t|drZ|drZ|dsZ|dsZtd| t|S |dkrt| dr|t| S |rdS t	d	|  dS )
a3  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)``.
    ro   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.rI   ziIf no scoring is specified, the estimator passed should have a 'score' method. The estimator %r does not.)
rQ   r|   r   r   getattrrf   r   r   r   r   )r9   r   r   moduler>   r>   r?   r   ~  s8    "

r   )N)}rq   r   r   collectionsr   	functoolsr   inspectr   	tracebackr   Znumpyr   baser   utilsr	   Zutils._param_validationr
   r   r   Zutils._responser   Zutils.metadata_routingr   r   r   r   r   r   Zutils.multiclassr   r{   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   Zclusterr.   r/   r0   r1   r2   r3   r4   r5   r6   r@   rA   rR   rc   rd   re   r|   r   r   r   r   r   Zexplained_variance_scorerZ	r2_scorerZmax_error_scorerZneg_mean_squared_error_scorerZ!neg_mean_squared_log_error_scorerZneg_mean_absolute_error_scorerZ)neg_mean_absolute_percentage_error_scorerZ neg_median_absolute_error_scorerZ"neg_root_mean_squared_error_scorerZ neg_mean_poisson_deviance_scorerZneg_mean_gamma_deviance_scorerZaccuracy_scorerZbalanced_accuracy_scorerZmatthews_corrcoef_scorerr   r   Z positive_likelihood_ratio_scorerZ$neg_negative_likelihood_ratio_scorerZtop_k_accuracy_scorerZroc_auc_scorerZaverage_precision_scorerZroc_auc_ovo_scorerZroc_auc_ovo_weighted_scorerZroc_auc_ovr_scorerZroc_auc_ovr_weighted_scorerZneg_log_loss_scorerZneg_brier_score_scorerZbrier_score_loss_scorerZadjusted_rand_scorerZrand_scorerZhomogeneity_scorerZcompleteness_scorerZv_measure_scorerZmutual_info_scorerZadjusted_mutual_info_scorerZnormalized_mutual_info_scorerZfowlkes_mallows_scorerr   r   r   rL   Zmetricr   r   Zqualified_namer   r   r>   r>   r>   r?   <module>   sp   d,gs,1F 
&Td                       '