§
    ¨éUgR�  ã                   ó’  — d dl mZ d dlmZmZ d dlZddlmZm	Z	m
Z
mZmZ ddlmZ ddlmZ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! ddl"m#Z# ddl$m%Z% ddl&m'Z'm(Z( ddl)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0 d„ Z1d„ Z2 G d„ de	e
e¦  «        Z3 G d„ de3¦  «        Z4 G d„ de¦  «        Z5d„ Z6d„ Z7 G d„ de3¦  «        Z8dS )é    )ÚMutableMapping)ÚIntegralÚRealNé   )ÚBaseEstimatorÚClassifierMixinÚMetaEstimatorMixinÚ_fit_contextÚclone)ÚNotFittedError)Úcheck_scoringÚget_scorer_names)Ú_BaseScorer)Ú_safe_indexing)Ú
HasMethodsÚIntervalÚ
RealNotIntÚ
StrOptions)Ú_get_response_values_binary)ÚMetadataRouterÚMethodMappingÚ_raise_for_paramsÚprocess_routing)Úavailable_if)Útype_of_target)ÚParallelÚdelayed)Ú_check_method_paramsÚ_num_samplesÚcheck_is_fittedÚ	indexableé   )ÚStratifiedShuffleSplitÚcheck_cvc                 ó   ‡ — ˆ fd„}|S )zªCheck if we can delegate a method to the underlying estimator.

    First, we check the fitted estimator if available, otherwise we
    check the unfitted estimator.
    c                 ó~   •— t          | d¦  «        rt          | j        ‰¦  «         nt          | j        ‰¦  «         dS )NÚ
estimator_T)ÚhasattrÚgetattrr'   Ú	estimator)ÚselfÚattrs    €úp/var/www/surfInsights/venv3-11/lib/python3.11/site-packages/sklearn/model_selection/_classification_threshold.pyÚcheckz_estimator_has.<locals>.check/   sA   ø€ Ý�4˜Ñ&Ô&ð 	*Ý�D”O TÑ*Ô*Ð*Ð*å�D”N DÑ)Ô)Ð)Øˆtó    © )r,   r.   s   ` r-   Ú_estimator_hasr1   (   s#   ø€ ðð ð ð ð ð €Lr/   c                 ó,  — |€t          j        ddg¦  «        }nRt          j        ||k    ¦  «        d         }t          j        ||k    ¦  «        d         }t          j        ||g¦  «        }||| |k                         t          ¦  «                          S )z;Threshold `y_score` and return the associated class labels.Nr   r"   )ÚnpÚarrayÚflatnonzeroÚastypeÚint)Úy_scoreÚ	thresholdÚclassesÚ	pos_labelÚmap_thresholded_score_to_labelÚpos_label_idxÚneg_label_idxs          r-   Ú!_threshold_scores_to_class_labelsr?   9   s‹   € àÐÝ)+¬°1°a°&Ñ)9Ô)9Ð&Ð&åœ w°)Ò';Ñ<Ô<¸QÔ?ˆÝœ w°)Ò';Ñ<Ô<¸QÔ?ˆÝ)+¬°=À-Ð2PÑ)QÔ)QÐ&àÐ1°7¸iÒ3G×2OÒ2OÕPSÑ2TÔ2TÔUÔVÐVr/   c                   ó|  — e Zd ZU dZdgZ eddg¦  «         eddg¦  «        g eh d£¦  «        gdœZee	d<   d	d
œd„Z
d„ Z ed¬¦  «        d„ ¦   «         Zed„ ¦   «         Z e ed¦  «        ¦  «        d„ ¦   «         Z e ed¦  «        ¦  «        d„ ¦   «         Z e ed¦  «        ¦  «        d„ ¦   «         Zd„ ZdS )ÚBaseThresholdClassifiera  Base class for binary classifiers that set a non-default decision threshold.

    In this base class, we define the following interface:

    - the validation of common parameters in `fit`;
    - the different prediction methods that can be used with the classifier.

    .. versionadded:: 1.5

    Parameters
    ----------
    estimator : estimator instance
        The binary classifier, fitted or not, for which we want to optimize
        the decision threshold used during `predict`.

    response_method : {"auto", "decision_function", "predict_proba"}, default="auto"
        Methods by the classifier `estimator` corresponding to the
        decision function for which we want to find a threshold. It can be:

        * if `"auto"`, it will try to invoke, for each classifier,
          `"predict_proba"` or `"decision_function"` in that order.
        * otherwise, one of `"predict_proba"` or `"decision_function"`.
          If the method is not implemented by the classifier, it will raise an
          error.
    r*   ÚfitÚpredict_probaÚdecision_function>   ÚautorC   rD   ©r*   Úresponse_methodÚ_parameter_constraintsrE   ©rG   c                ó"   — || _         || _        d S ©NrF   )r+   r*   rG   s      r-   Ú__init__z BaseThresholdClassifier.__init__i   s   € Ø"ˆŒØ.ˆÔÐÐr/   c                 ó4   — | j         dk    rddg}n| j         }|S )zDefine the response method.rE   rC   rD   rI   )r+   rG   s     r-   Ú_get_response_methodz,BaseThresholdClassifier._get_response_methodm   s+   € àÔ 6Ò)Ð)Ø.Ð0CÐDˆOˆOà"Ô2ˆOØÐr/   F)Úprefer_skip_nested_validationc                 óV  — t          || d¦  «         t          ||¦  «        \  }}t          |d¬¦  «        }|dk    rt          d|› �¦  «        ‚ | j        ||fi |¤Ž t          | j        d¦  «        r| j        j        | _        t          | j        d¦  «        r| j        j        | _        | S )áÆ  Fit the classifier.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training data.

        y : array-like of shape (n_samples,)
            Target values.

        **params : dict
            Parameters to pass to the `fit` method of the underlying
            classifier.

        Returns
        -------
        self : object
            Returns an instance of self.
        NÚy)Ú
input_nameÚbinaryz=Only binary classification is supported. Unknown label type: Ún_features_in_Úfeature_names_in_)	r   r!   r   Ú
ValueErrorÚ_fitr(   r'   rU   rV   )r+   ÚXrR   ÚparamsÚy_types        r-   rB   zBaseThresholdClassifier.fitu   sË   € õ0 	˜& $¨Ñ-Ô-Ð-å˜˜A‰Œ‰ˆˆ1å ¨cÐ2Ñ2Ô2ˆØ�XÒÐÝØXÐPVÐXÐXñô ð ð 	ˆŒ	�!�QÐ!Ð!˜&Ð!Ð!Ð!å�4”?Ð$4Ñ5Ô5ð 	AØ"&¤/Ô"@ˆDÔÝ�4”?Ð$7Ñ8Ô8ð 	GØ%)¤_Ô%FˆDÔ"àˆr/   c                 ó   — | j         j        S )zClasses labels.)r'   Úclasses_©r+   s    r-   r]   z BaseThresholdClassifier.classes_    s   € ð ŒÔ'Ð'r/   c                 óV   — t          | d¦  «         | j                             |¦  «        S )aÔ  Predict class probabilities for `X` using the fitted estimator.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training vectors, where `n_samples` is the number of samples and
            `n_features` is the number of features.

        Returns
        -------
        probabilities : ndarray of shape (n_samples, n_classes)
            The class probabilities of the input samples.
        r'   )r    r'   rC   ©r+   rY   s     r-   rC   z%BaseThresholdClassifier.predict_proba¥   s*   € õ 	˜˜lÑ+Ô+Ð+ØŒ×,Ò,¨QÑ/Ô/Ð/r/   Úpredict_log_probac                 óV   — t          | d¦  «         | j                             |¦  «        S )aì  Predict logarithm class probabilities for `X` using the fitted estimator.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training vectors, where `n_samples` is the number of samples and
            `n_features` is the number of features.

        Returns
        -------
        log_probabilities : ndarray of shape (n_samples, n_classes)
            The logarithm class probabilities of the input samples.
        r'   )r    r'   ra   r`   s     r-   ra   z)BaseThresholdClassifier.predict_log_proba·   ó*   € õ 	˜˜lÑ+Ô+Ð+ØŒ×0Ò0°Ñ3Ô3Ð3r/   c                 óV   — t          | d¦  «         | j                             |¦  «        S )aÎ  Decision function for samples in `X` using the fitted estimator.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training vectors, where `n_samples` is the number of samples and
            `n_features` is the number of features.

        Returns
        -------
        decisions : ndarray of shape (n_samples,)
            The decision function computed the fitted estimator.
        r'   )r    r'   rD   r`   s     r-   rD   z)BaseThresholdClassifier.decision_functionÉ   rc   r/   c                 ó   — ddddœdœS )NTz*Threshold at probability 0.5 does not holdzÁDue to the cross-validation and sample ordering, removing a sample is not strictly equal to putting is weight to zero. Specific unit tests are added for TunedThresholdClassifierCV specifically.)Úcheck_classifiers_trainÚcheck_sample_weights_invariance)Úbinary_onlyÚ_xfail_checksr0   r^   s    r-   Ú
_more_tagsz"BaseThresholdClassifier._more_tagsÛ   s'   € àà+WðTðð ð

ð 

ð 
	
r/   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú_required_parametersr   r   rH   ÚdictÚ__annotations__rL   rN   r
   rB   Úpropertyr]   r   r1   rC   ra   rD   rj   r0   r/   r-   rA   rA   E   s©  € € € € € € ðð ð4 (˜=Ðð ˆJ˜˜Ð/Ñ0Ô0ØˆJ˜Ð2Ð3Ñ4Ô4ð
ð '˜JÐ'UÐ'UÐ'UÑVÔVÐWð$ð $Ð˜Dð ð ñ ð 6<ð /ð /ð /ð /ð /ðð ð ð €\à&+ðñ ô ð%ð %ñ	ô ð%ðN ð(ð (ñ „Xð(ð €\�.�. Ñ1Ô1Ñ2Ô2ð0ð 0ñ 3Ô2ð0ð" €\�.�.Ð!4Ñ5Ô5Ñ6Ô6ð4ð 4ñ 7Ô6ð4ð" €\�.�.Ð!4Ñ5Ô5Ñ6Ô6ð4ð 4ñ 7Ô6ð4ð"
ð 
ð 
ð 
ð 
r/   rA   c                   ó†   ‡ — e Zd ZU dZi ej        ¥ edh¦  «        egeeddgdœ¥Ze	e
d<   ddddœˆ fd„
Zd	„ Zd
„ Zd„ Zˆ xZS )ÚFixedThresholdClassifiera§  Binary classifier that manually sets the decision threshold.

    This classifier allows to change the default decision threshold used for
    converting posterior probability estimates (i.e. output of `predict_proba`) or
    decision scores (i.e. output of `decision_function`) into a class label.

    Here, the threshold is not optimized and is set to a constant value.

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

    .. versionadded:: 1.5

    Parameters
    ----------
    estimator : estimator instance
        The binary classifier, fitted or not, for which we want to optimize
        the decision threshold used during `predict`.

    threshold : {"auto"} or float, default="auto"
        The decision threshold to use when converting posterior probability estimates
        (i.e. output of `predict_proba`) or decision scores (i.e. output of
        `decision_function`) into a class label. When `"auto"`, the threshold is set
        to 0.5 if `predict_proba` is used as `response_method`, otherwise it is set to
        0 (i.e. the default threshold for `decision_function`).

    pos_label : int, float, bool or str, default=None
        The label of the positive class. Used to process the output of the
        `response_method` method. When `pos_label=None`, if `y_true` is in `{-1, 1}` or
        `{0, 1}`, `pos_label` is set to 1, otherwise an error will be raised.

    response_method : {"auto", "decision_function", "predict_proba"}, default="auto"
        Methods by the classifier `estimator` corresponding to the
        decision function for which we want to find a threshold. It can be:

        * if `"auto"`, it will try to invoke `"predict_proba"` or `"decision_function"`
          in that order.
        * otherwise, one of `"predict_proba"` or `"decision_function"`.
          If the method is not implemented by the classifier, it will raise an
          error.

    Attributes
    ----------
    estimator_ : estimator instance
        The fitted classifier used when predicting.

    classes_ : ndarray of shape (n_classes,)
        The class labels.

    n_features_in_ : int
        Number of features seen during :term:`fit`. Only defined if the
        underlying estimator exposes such an attribute when fit.

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Only defined if the
        underlying estimator exposes such an attribute when fit.

    See Also
    --------
    sklearn.model_selection.TunedThresholdClassifierCV : Classifier that post-tunes
        the decision threshold based on some metrics and using cross-validation.
    sklearn.calibration.CalibratedClassifierCV : Estimator that calibrates
        probabilities.

    Examples
    --------
    >>> from sklearn.datasets import make_classification
    >>> from sklearn.linear_model import LogisticRegression
    >>> from sklearn.metrics import confusion_matrix
    >>> from sklearn.model_selection import FixedThresholdClassifier, train_test_split
    >>> X, y = make_classification(
    ...     n_samples=1_000, weights=[0.9, 0.1], class_sep=0.8, random_state=42
    ... )
    >>> X_train, X_test, y_train, y_test = train_test_split(
    ...     X, y, stratify=y, random_state=42
    ... )
    >>> classifier = LogisticRegression(random_state=0).fit(X_train, y_train)
    >>> print(confusion_matrix(y_test, classifier.predict(X_test)))
    [[217   7]
     [ 19   7]]
    >>> classifier_other_threshold = FixedThresholdClassifier(
    ...     classifier, threshold=0.1, response_method="predict_proba"
    ... ).fit(X_train, y_train)
    >>> print(confusion_matrix(y_test, classifier_other_threshold.predict(X_test)))
    [[184  40]
     [  6  20]]
    rE   ÚbooleanN)r9   r;   rH   )r9   r;   rG   c                ój   •— t          ¦   «                              ||¬¦  «         || _        || _        d S ©NrF   )ÚsuperrL   r;   r9   )r+   r*   r9   r;   rG   Ú	__class__s        €r-   rL   z!FixedThresholdClassifier.__init__G  s4   ø€ õ 	‰Œ×Ò 9¸oÐÑNÔNÐNØ"ˆŒØ"ˆŒˆˆr/   c                 ó‚   — t          | dfi |¤Ž} t          | j        ¦  «        j        ||fi |j        j        ¤Ž| _        | S )rQ   rB   )r   r   r*   rB   r'   )r+   rY   rR   rZ   Úrouted_paramss        r-   rX   zFixedThresholdClassifier._fitS  sN   € õ( (¨¨eÐ>Ð>°vÐ>Ð>ˆØ3�% ¤Ñ/Ô/Ô3°A°qÐXÐX¸MÔ<SÔ<WÐXÐXˆŒØˆr/   c                 óü   — t          | d¦  «         t          | j        ||                      ¦   «         | j        d¬¦  «        \  }}}| j        dk    r|dk    rdnd}n| j        }t          ||| j        | j        ¦  «        S )áO  Predict the target of new samples.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            The samples, as accepted by `estimator.predict`.

        Returns
        -------
        class_labels : ndarray of shape (n_samples,)
            The predicted class.
        r'   T)r;   Úreturn_response_method_usedrE   rC   g      à?ç        )r    r   r'   rN   r;   r9   r?   r]   )r+   rY   r8   Ú_Úresponse_method_usedÚdecision_thresholds         r-   Úpredictz FixedThresholdClassifier.predictk  sž   € õ 	˜˜lÑ+Ô+Ð+Ý+FØŒOØØ×%Ò%Ñ'Ô'Ø”nØ(,ð,
ñ ,
ô ,
Ñ(ˆ�Ð(ð Œ>˜VÒ#Ð#Ø(<ÀÒ(OÐ(O  ÐUXÐÐà!%¤Ðå0ØÐ'¨¬¸¼ñ
ô 
ð 	
r/   c                 ó°   — t          | j        j        ¬¦  «                             | j        t          ¦   «                              dd¬¦  «        ¬¦  «        }|S )áK  Get metadata routing of this object.

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

        Returns
        -------
        routing : MetadataRouter
            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
            routing information.
        ©ÚownerrB   ©ÚcalleeÚcaller©r*   Úmethod_mapping)r   ry   rk   Úaddr*   r   ©r+   Úrouters     r-   Úget_metadata_routingz-FixedThresholdClassifier.get_metadata_routingŠ  sU   € õ   d¤nÔ&=Ð>Ñ>Ô>×BÒBØ”nÝ(™?œ?×.Ò.°eÀEÐ.ÑJÔJð Cñ 
ô 
ˆð ˆr/   )rk   rl   rm   rn   rA   rH   r   r   Ústrrp   rq   rL   rX   rƒ   r�   Ú__classcell__©ry   s   @r-   rt   rt   é   sÜ   ø€ € € € € € ðUð Uðn$Ø
!Ô
8ð$à �j & Ñ*Ô*¨DÐ1Ø˜C ¨DÐ1ð$ð $ð $Ð˜Dð ð ñ ð ØØð
#ð 
#ð 
#ð 
#ð 
#ð 
#ð 
#ðð ð ð0
ð 
ð 
ð>ð ð ð ð ð ð r/   rt   c                   ó>   ‡ — 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          ¦   «                              ||||¬¦  «         || _        d S )N)Ú
score_funcÚsignÚkwargsrG   )rx   rL   Ú_thresholds)r+   r—   r˜   r™   Ú
thresholdsrG   ry   s         €r-   rL   z_CurveScorer.__init__·  s@   ø€ Ý‰Œ×ÒØ!ØØØ+ð	 	ñ 	
ô 	
ð 	
ð &ˆÔÐÐr/   c                 óv   —  | |j         |j        |||j        ¬¦  «        }|                     ¦   «         |_        |S )z0Create a continuous scorer from a normal scorer.)r—   r˜   rG   r›   r™   )Ú_score_funcÚ_signÚ_kwargsÚ_get_metadata_requestÚ_metadata_request)ÚclsÚscorerrG   r›   Úinstances        r-   Úfrom_scorerz_CurveScorer.from_scorerÀ  sK   € ð �3ØÔ)Ø”Ø+Ø!Ø”>ð
ñ 
ô 
ˆð &,×%AÒ%AÑ%CÔ%CˆÔ"Øˆr/   c                 ó¬  ‡ ‡‡‡‡	‡
— ‰                       ¦   «         Š |‰‰ j        |‰¬¦  «        Š
i ‰ j        ¥|¥Š	t          ‰ j        t
          ¦  «        r@t          j        t          j        ‰
¦  «        t          j	        ‰
¦  «        ‰ j        ¦  «        }nt          j
        ‰ j        ¦  «        }ˆˆˆ	ˆ ˆ
ˆfd„|D ¦   «         }t          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.

        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;   c                 óh   •— g | ].}‰j          ‰j        ‰t          ‰|‰j        ‰¦  «        fi ‰¤Žz  ‘Œ/S r0   )rž   r�   r?   r]   )Ú.0Úthr*   r;   Úscoring_kwargsr+   r8   Úy_trues     €€€€€€r-   ú
<listcomp>z'_CurveScorer._score.<locals>.<listcomp>ø  so   ø€ ð 

ð 

ð 

ð ð ŒJØˆdÔØÝ1Ø˜R Ô!3°Yñô ðð ð
 !ðð ñð

ð 

ð 

r/   )Ú_get_pos_labelÚ_response_methodrŸ   Ú
isinstancerš   r   r3   ÚlinspaceÚminÚmaxÚasarrayr4   )r+   Úmethod_callerr*   rY   r¬   r™   Úpotential_thresholdsÚscore_thresholdsr;   r«   r8   s   ` ` `   @@@r-   Ú_scorez_CurveScorer._scoreÎ  s  øøøøøø€ ð< ×'Ò'Ñ)Ô)ˆ	Ø�-Ø�tÔ,¨a¸9ð
ñ 
ô 
ˆð 4˜DœLÐ3¨FÐ3ˆÝ�dÔ&­Ñ1Ô1ð 	@Ý#%¤;Ý”�w‘”¥¤¨¡¤°$Ô2Bñ$ô $Ð Ð õ $&¤:¨dÔ.>Ñ#?Ô#?Ð ð

ð 

ð 

ð 

ð 

ð 

ð 

ð 

ð 

ð +ð

ñ 

ô 

Ðõ ŒxÐ(Ñ)Ô)Ð+?Ð?Ð?r/   )	rk   rl   rm   rn   rL   Úclassmethodr¥   r¸   r’   r“   s   @r-   r•   r•   �  ss   ø€ € € € € ðð ð2&ð &ð &ð &ð &ð ðð ñ „[ðð5@ð 5@ð 5@ð 5@ð 5@ð 5@ð 5@r/   r•   c                ó  — |�tt          ||¦  «        t          ||¦  «        }	}t          ||¦  «        t          ||¦  «        }}
t          |||¬¦  «        }t          |||¬¦  «        } | j        ||
fi |¤Ž n|||}}}	 || |	|fi |¤ŽS )aÆ  Fit a classifier and compute the scores for different decision thresholds.

    Parameters
    ----------
    classifier : estimator instance
        The classifier to fit and use for scoring. If `classifier` is already fitted,
        it will be used as is.

    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        The entire dataset.

    y : array-like of shape (n_samples,)
        The entire target vector.

    fit_params : dict
        Parameters to pass to the `fit` method of the underlying classifier.

    train_idx : ndarray of shape (n_train_samples,) or None
        The indices of the training set. If `None`, `classifier` is expected to be
        already fitted.

    val_idx : ndarray of shape (n_val_samples,)
        The indices of the validation set used to score `classifier`. If `train_idx`,
        the entire set will be used.

    curve_scorer : scorer instance
        The scorer taking `classifier` and the validation set as input and outputting
        decision thresholds and scores as a curve. Note that this is different from
        the usual scorer that output a single score value:

        * when `score_method` is one of the four constraint metrics, the curve scorer
          will output a curve of two scores parametrized by the decision threshold, e.g.
          TPR/TNR or precision/recall curves for each threshold;
        * otherwise, the curve scorer will output a single score value for each
          threshold.

    score_params : dict
        Parameters to pass to the `score` method of the underlying scorer.

    Returns
    -------
    scores : ndarray of shape (thresholds,) or tuple of such arrays
        The scores computed for each decision threshold. When TPR/TNR or precision/
        recall are computed, `scores` is a tuple of two arrays.

    potential_thresholds : ndarray of shape (thresholds,)
        The decision thresholds used to compute the scores. They are returned in
        ascending order.
    N©Úindices)r   r   rB   )Ú
classifierrY   rR   Ú
fit_paramsÚ	train_idxÚval_idxÚcurve_scorerÚscore_paramsÚX_trainÚX_valÚy_trainÚy_valÚfit_params_trainÚscore_params_vals                 r-   Ú_fit_and_score_over_thresholdsrÉ     sº   € ðz ÐÝ'¨¨9Ñ5Ô5µ~ÀaÈÑ7QÔ7Q�ˆÝ'¨¨9Ñ5Ô5µ~ÀaÈÑ7QÔ7Q�ˆÝ/°°:ÀyÐQÑQÔQÐÝ/°°<ÈÐQÑQÔQÐØˆ
Œ�w Ð<Ð<Ð+;Ð<Ð<Ð<Ð<à)*¨A¨|Ð&ˆuˆàˆ<˜
 E¨5ÐEÐEÐ4DÐEÐEÐEr/   c                 ód   ‡ — t          j        ˆ fd„t          ||¦  «        D ¦   «         d¬¦  «        S )al  Compute the mean interpolated score across folds by defining common thresholds.

    Parameters
    ----------
    target_thresholds : ndarray of shape (thresholds,)
        The thresholds to use to compute the mean score.

    cv_thresholds : ndarray of shape (n_folds, thresholds_fold)
        The thresholds used to compute the scores for each fold.

    cv_scores : ndarray of shape (n_folds, thresholds_fold)
        The scores computed for each threshold for each fold.

    Returns
    -------
    mean_score : ndarray of shape (thresholds,)
        The mean score across all folds for each target threshold.
    c                 óB   •— g | ]\  }}t          j        ‰||¦  «        ‘ŒS r0   )r3   Úinterp)r©   Úsplit_thresholdsÚsplit_scoreÚtarget_thresholdss      €r-   r­   z,_mean_interpolated_score.<locals>.<listcomp>c  s>   ø€ ð 	
ð 	
ð 	
á-Ð  +õ ŒIÐ'Ð)9¸;ÑGÔGð	
ð 	
ð 	
r/   r   )Úaxis)r3   ÚmeanÚzip)rÏ   Úcv_thresholdsÚ	cv_scoress   `  r-   Ú_mean_interpolated_scorerÕ   O  sS   ø€ õ& Œ7ð	
ð 	
ð 	
ð 	
å14°]ÀIÑ1NÔ1Nð	
ñ 	
ô 	
ð ðñ ô ð r/   c                   ó  ‡ — e Zd ZU dZi ej        ¥ e e e¦   «         ¦  «        ¦  «        e	e
g eeddd¬¦  «        dgd edh¦  «         eed	d
d¬¦  «        gdgedgdgdgdœ¥Zeed<   dddddddddœˆ fd„
Zd„ Zd„ Zd„ Zd„ Zˆ xZS )ÚTunedThresholdClassifierCVa>  Classifier that post-tunes the decision threshold using cross-validation.

    This estimator post-tunes the decision threshold (cut-off point) that is
    used for converting posterior probability estimates (i.e. output of
    `predict_proba`) or decision scores (i.e. output of `decision_function`)
    into a class label. The tuning is done by optimizing a binary metric,
    potentially constrained by a another metric.

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

    .. versionadded:: 1.5

    Parameters
    ----------
    estimator : estimator instance
        The classifier, fitted or not, for which we want to optimize
        the decision threshold used during `predict`.

    scoring : str or callable, default="balanced_accuracy"
        The objective metric to be optimized. Can be one of:

        * a string associated to a scoring function for binary classification
          (see model evaluation documentation);
        * a scorer callable object created with :func:`~sklearn.metrics.make_scorer`;

    response_method : {"auto", "decision_function", "predict_proba"}, default="auto"
        Methods by the classifier `estimator` corresponding to the
        decision function for which we want to find a threshold. It can be:

        * if `"auto"`, it will try to invoke, for each classifier,
          `"predict_proba"` or `"decision_function"` in that order.
        * otherwise, one of `"predict_proba"` or `"decision_function"`.
          If the method is not implemented by the classifier, it will raise an
          error.

    thresholds : int or array-like, default=100
        The number of decision threshold to use when discretizing the output of the
        classifier `method`. Pass an array-like to manually specify the thresholds
        to use.

    cv : int, float, cross-validation generator, iterable or "prefit", default=None
        Determines the cross-validation splitting strategy to train classifier.
        Possible inputs for cv are:

        * `None`, to use the default 5-fold stratified K-fold cross validation;
        * An integer number, to specify the number of folds in a stratified k-fold;
        * A float number, to specify a single shuffle split. The floating number should
          be in (0, 1) and represent the size of the validation set;
        * An object to be used as a cross-validation generator;
        * An iterable yielding train, test splits;
        * `"prefit"`, to bypass the cross-validation.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. warning::
            Using `cv="prefit"` and passing the same dataset for fitting `estimator`
            and tuning the cut-off point is subject to undesired overfitting. You can
            refer to :ref:`TunedThresholdClassifierCV_no_cv` for an example.

            This option should only be used when the set used to fit `estimator` is
            different from the one used to tune the cut-off point (by calling
            :meth:`TunedThresholdClassifierCV.fit`).

    refit : bool, default=True
        Whether or not to refit the classifier on the entire training set once
        the decision threshold has been found.
        Note that forcing `refit=False` on cross-validation having more
        than a single split will raise an error. Similarly, `refit=True` in
        conjunction with `cv="prefit"` will raise an error.

    n_jobs : int, default=None
        The number of jobs to run in parallel. When `cv` represents a
        cross-validation strategy, the fitting and scoring on each data split
        is done in parallel. ``None`` means 1 unless in a
        :obj:`joblib.parallel_backend` context. ``-1`` means using all
        processors. See :term:`Glossary <n_jobs>` for more details.

    random_state : int, RandomState instance or None, default=None
        Controls the randomness of cross-validation when `cv` is a float.
        See :term:`Glossary <random_state>`.

    store_cv_results : bool, default=False
        Whether to store all scores and thresholds computed during the cross-validation
        process.

    Attributes
    ----------
    estimator_ : estimator instance
        The fitted classifier used when predicting.

    best_threshold_ : float
        The new decision threshold.

    best_score_ : float or None
        The optimal score of the objective metric, evaluated at `best_threshold_`.

    cv_results_ : dict or None
        A dictionary containing the scores and thresholds computed during the
        cross-validation process. Only exist if `store_cv_results=True`. The
        keys are `"thresholds"` and `"scores"`.

    classes_ : ndarray of shape (n_classes,)
        The class labels.

    n_features_in_ : int
        Number of features seen during :term:`fit`. Only defined if the
        underlying estimator exposes such an attribute when fit.

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Only defined if the
        underlying estimator exposes such an attribute when fit.

    See Also
    --------
    sklearn.model_selection.FixedThresholdClassifier : Classifier that uses a
        constant threshold.
    sklearn.calibration.CalibratedClassifierCV : Estimator that calibrates
        probabilities.

    Examples
    --------
    >>> from sklearn.datasets import make_classification
    >>> from sklearn.ensemble import RandomForestClassifier
    >>> from sklearn.metrics import classification_report
    >>> from sklearn.model_selection import TunedThresholdClassifierCV, train_test_split
    >>> X, y = make_classification(
    ...     n_samples=1_000, weights=[0.9, 0.1], class_sep=0.8, random_state=42
    ... )
    >>> X_train, X_test, y_train, y_test = train_test_split(
    ...     X, y, stratify=y, random_state=42
    ... )
    >>> classifier = RandomForestClassifier(random_state=0).fit(X_train, y_train)
    >>> print(classification_report(y_test, classifier.predict(X_test)))
                  precision    recall  f1-score   support
    <BLANKLINE>
               0       0.94      0.99      0.96       224
               1       0.80      0.46      0.59        26
    <BLANKLINE>
        accuracy                           0.93       250
       macro avg       0.87      0.72      0.77       250
    weighted avg       0.93      0.93      0.92       250
    <BLANKLINE>
    >>> classifier_tuned = TunedThresholdClassifierCV(
    ...     classifier, scoring="balanced_accuracy"
    ... ).fit(X_train, y_train)
    >>> print(
    ...     f"Cut-off point found at {classifier_tuned.best_threshold_:.3f}"
    ... )
    Cut-off point found at 0.342
    >>> print(classification_report(y_test, classifier_tuned.predict(X_test)))
                  precision    recall  f1-score   support
    <BLANKLINE>
               0       0.96      0.95      0.96       224
               1       0.61      0.65      0.63        26
    <BLANKLINE>
        accuracy                           0.92       250
       macro avg       0.78      0.80      0.79       250
    weighted avg       0.92      0.92      0.92       250
    <BLANKLINE>
    r"   NÚleft)Úclosedz
array-likeÚ	cv_objectÚprefitr   g      ð?Úneitherru   Úrandom_state)Úscoringr›   ÚcvÚrefitÚn_jobsrÝ   Ústore_cv_resultsrH   Úbalanced_accuracyrE   éd   TF)rÞ   rG   r›   rß   rà   rá   rÝ   râ   c                ó°   •— t          ¦   «                              ||¬¦  «         || _        || _        || _        || _        || _        || _        |	| _        d S rw   )	rx   rL   rÞ   r›   rß   rà   rá   rÝ   râ   )r+   r*   rÞ   rG   r›   rß   rà   rá   rÝ   râ   ry   s             €r-   rL   z#TunedThresholdClassifierCV.__init__!  s[   ø€ õ 	‰Œ×Ò 9¸oÐÑNÔNÐNØˆŒØ$ˆŒØˆŒØˆŒ
ØˆŒØ(ˆÔØ 0ˆÔÐÐr/   c           
      óÔ  ‡ ‡‡‡‡‡— t          ‰ j        t          ¦  «        r2d‰ j        cxk     rdk     r n nt          d‰ j        ‰ j        ¬¦  «        Šn«‰ j        dk    rY‰ j        du rt          d¦  «        ‚	 t          ‰ j        d¦  «         n"# t          $ r}t          d¦  «        |‚d	}~ww xY w‰ j        ŠnGt          ‰ j        ‰d¬
¦  «        Š‰ j        du r'‰                     ¦   «         dk    rt          d¦  «        ‚t          ‰ dfi |¤ŽŠ‰                      ¦   «         ‰ _        ‰dk    r3‰ j        ‰ _        ‰ j        Šd	t!          t#          ‰¦  «        ¦  «        fg}n×t%          ‰ j        ¦  «        ‰ _        t%          ‰ j        ¦  «        Š ‰j        ‰‰fi ‰j        j        ¤Ž}‰ j        r‰‰‰j        j        }}}net-           ‰j        ‰‰fi ‰j        j        ¤Ž¦  «        \  }	}
t/          ‰|	¦  «        }t/          ‰|	¦  «        }t1          ‰‰j        j        |	¬¦  «        } ‰ j        j        ||fi |¤Ž t3           t5          ‰ j        ¬¦  «        ˆˆˆˆˆ ˆfd„|D ¦   «         ¦  «        Ž \  }}t9          d„ |D ¦   «         ¦  «        rt          d¦  «        ‚t;          d„ |D ¦   «         ¦  «        }t=          d„ |D ¦   «         ¦  «        }t          ‰ j        t@          ¦  «        rtC          j"        ||‰ j        ¬¦  «        }ntC          j#        ‰ j        ¦  «        }tI          |||¦  «        }| %                    ¦   «         }||         ‰ _&        ||         ‰ _'        ‰ j(        r
||dœ‰ _)        ‰ S )a  Fit the classifier and post-tune the decision threshold.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training data.

        y : array-like of shape (n_samples,)
            Target values.

        **params : dict
            Parameters to pass to the `fit` method of the underlying
            classifier and to the `scoring` scorer.

        Returns
        -------
        self : object
            Returns an instance of self.
        r   r"   )Ún_splitsÚ	test_sizerÝ   rÛ   Tz'When cv='prefit', refit cannot be True.r]   z-When cv='prefit', `estimator` must be fitted.N)rR   r½   Fz1When cv has several folds, refit cannot be False.rB   r»   )rá   c              3   óÄ   •K  — | ]Z\  }} t          t          ¦  «        ‰d k    rt          ‰¦  «        n‰‰‰‰j        j        ||‰j        ‰j        j        ¬¦  «        V — Œ[dS )rÛ   )r¾   r¿   rÀ   rÁ   rÂ   N)r   rÉ   r   r*   rB   Ú_curve_scorerr£   Úscore)	r©   r¿   rÀ   rY   r½   rß   r{   r+   rR   s	      €€€€€€r-   ú	<genexpr>z2TunedThresholdClassifierCV._fit.<locals>.<genexpr>}  s“   øè è € ð *ð *ñ '�I˜wð 8•Õ6Ñ7Ô7Ø)+¨xª¨•E˜*Ñ%Ô%Ð%¸ZØØØ,Ô6Ô:Ø'Ø#Ø!%Ô!3Ø!.Ô!5Ô!;ð	ñ 	ô 	ð*ð *ð *ð *ð *ð *r/   c              3   óX   K  — | ]%}t          j        |d          |d         ¦  «        V — Œ&dS )r   éÿÿÿÿN)r3   Úisclose)r©   rª   s     r-   rì   z2TunedThresholdClassifierCV._fit.<locals>.<genexpr>Œ  s6   è è € ÐAÐA¨R�rŒz˜"˜Qœ%  B¤Ñ(Ô(ÐAÐAÐAÐAÐAÐAr/   zrThe provided estimator makes constant predictions. Therefore, it is impossible to optimize the decision threshold.c              3   ó>   K  — | ]}|                      ¦   «         V — Œd S rK   )r²   ©r©   rÍ   s     r-   rì   z2TunedThresholdClassifierCV._fit.<locals>.<genexpr>“  ó@   è è € ð 
ð 
Ø'7Ð× Ò Ñ"Ô"ð
ð 
ð 
ð 
ð 
ð 
r/   c              3   ó>   K  — | ]}|                      ¦   «         V — Œd S rK   )r³   rñ   s     r-   rì   z2TunedThresholdClassifierCV._fit.<locals>.<genexpr>–  rò   r/   )Únum)r›   Úscores)*r°   rß   r   r#   rÝ   rà   rW   r    r*   r   r$   Úget_n_splitsr   Ú_get_curve_scorerrê   r'   Úranger   r   ÚsplitÚsplitterrB   Únextr   r   rÒ   r   rá   Úanyr²   r³   r›   r   r3   r±   r´   rÕ   ÚargmaxÚbest_score_Úbest_threshold_râ   Úcv_results_)r+   rY   rR   rZ   ÚexcÚsplitsrÃ   rÅ   rÇ   r¿   r€   rÔ   rÓ   Úmin_thresholdÚmax_thresholdÚdecision_thresholdsÚobjective_scoresÚbest_idxr½   rß   r{   s   ```               @@@r-   rX   zTunedThresholdClassifierCV._fit7  s4  øøøøøø€ õ( �d”g�tÑ$Ô$ð 	V¨¨T¬W¨¨ª¨°qª¨¨¨¨Ý'Ø d¤g¸DÔ<Mðñ ô ˆBˆBð ŒW˜Ò Ð ØŒz˜TÐ!Ð!Ý Ð!JÑKÔKÐKðÝ ¤°
Ñ;Ô;Ð;Ð;øÝ!ð ð ð Ý$ØGñô àðøøøøðøøøð ”ˆBˆBå˜$œ' Q°4Ð8Ñ8Ô8ˆBØŒz˜UÐ"Ð" r§¢Ñ'8Ô'8¸1Ò'<Ð'<Ý Ð!TÑUÔUÐUå'¨¨eÐ>Ð>°vÐ>Ð>ˆØ!×3Ò3Ñ5Ô5ˆÔð �Š>ˆ>Ø"œnˆDŒOØœˆJØ�U¥<°¡?¤?Ñ3Ô3Ð4Ð5ˆFˆFå# D¤NÑ3Ô3ˆDŒOÝ˜tœ~Ñ.Ô.ˆJØ�R”X˜a ÐCÐC mÔ&<Ô&BÐCÐCˆFàŒzð 
à56¸¸=Ô;RÔ;VÐ"2˜��õ  $ H B¤H¨Q°Ð$RÐ$R°]Ô5KÔ5QÐ$RÐ$RÑSÔS‘�	˜1Ý(¨¨IÑ6Ô6�Ý(¨¨IÑ6Ô6�Ý#7Ø�}Ô.Ô2¸Ið$ñ $ô $Ð ð  ˆDŒOÔ ¨ÐEÐEÐ4DÐEÐEÐEå#&Ø)�X˜Tœ[Ð)Ñ)Ô)ð *ð *ð *ð *ð *ð *ð *ð *ð *ð +1ð*ñ *ô *ñ ô ð$
Ñ ˆ	�=õ  ÐAÐA°=ÐAÑAÔAÑAÔAð 	ÝðAñô ð õ ð 
ð 
Ø;Hð
ñ 
ô 
ñ 
ô 
ˆõ ð 
ð 
Ø;Hð
ñ 
ô 
ñ 
ô 
ˆõ �d”o¥xÑ0Ô0ð 	>Ý"$¤+Ø˜}°$´/ð#ñ #ô #ÐÐõ #%¤*¨T¬_Ñ"=Ô"=Ðå3Ø °	ñ
ô 
Ðð $×*Ò*Ñ,Ô,ˆØ+¨HÔ5ˆÔØ2°8Ô<ˆÔØÔ ð 	à1Ø*ð ð  ˆDÔð
 ˆs   Á7B Â
B,ÂB'Â'B,c                 óæ   — t          | d¦  «         | j                             ¦   «         }t          | j        ||                      ¦   «         |¬¦  «        \  }}t          || j        | j        |¦  «        S )r}   r'   r§   )	r    rê   r®   r   r'   rN   r?   rÿ   r]   )r+   rY   r;   r8   r€   s        r-   rƒ   z"TunedThresholdClassifierCV.predict®  s|   € õ 	˜˜lÑ+Ô+Ð+ØÔ&×5Ò5Ñ7Ô7ˆ	Ý0ØŒOØØ×%Ò%Ñ'Ô'Øð	
ñ 
ô 
‰
ˆ�õ 1Ø�TÔ)¨4¬=¸)ñ
ô 
ð 	
r/   c                 ó¶  — t          | j        j        ¬¦  «                             | j        t          ¦   «                              dd¬¦  «        ¬¦  «                             | j        t          ¦   «                              dd¬¦  «        ¬¦  «                             |                      ¦   «         t          ¦   «                              dd¬¦  «        ¬¦  «        }|S )	r…   r†   rB   rˆ   r‹   rù   )rú   rŒ   rë   )r£   rŒ   )r   ry   rk   r�   r*   r   rß   r÷   rŽ   s     r-   r�   z/TunedThresholdClassifierCV.get_metadata_routingÈ  sÊ   € õ  ¤Ô!8Ð9Ñ9Ô9ßŠSØœ.Ý,™œ×2Ò2¸%ÈÐ2ÑNÔNð ñ ô ÷ ŠSØœÝ,™œ×2Ò2¸'È%Ð2ÑPÔPð ñ ô ÷ ŠSØ×-Ò-Ñ/Ô/Ý,™œ×2Ò2¸'È%Ð2ÑPÔPð ñ ô ð 	ð ˆr/   c                 ó¢   — t          | j        | j        ¬¦  «        }t                               ||                      ¦   «         | j        ¦  «        }|S )z8Get the curve scorer based on the objective metric used.)rÞ   )r   r*   rÞ   r•   r¥   rN   r›   )r+   rÞ   rÁ   s      r-   r÷   z,TunedThresholdClassifierCV._get_curve_scorerå  sJ   € å ¤¸¼ÐEÑEÔEˆÝ#×/Ò/Ø�T×.Ò.Ñ0Ô0°$´/ñ
ô 
ˆð Ðr/   )rk   rl   rm   rn   rA   rH   r   Úsetr   Úcallabler   r   r   r   rp   rq   rL   rX   rƒ   r�   r÷   r’   r“   s   @r-   r×   r×   k  sp  ø€ € € € € € ð`ð `ðD$Ø
!Ô
8ð$ð ˆJ�s�sÐ+Ð+Ñ-Ô-Ñ.Ô.Ñ/Ô/ØØð
ð
  �x ¨!¨T¸&ÐAÑAÔAÀ<ÐPàØˆJ˜�zÑ"Ô"ØˆH�Z  c°)Ð<Ñ<Ô<ð
ð
 �Ø˜TÐ"Ø'Ð(Ø&˜Kð!$ð $ð $Ð˜Dð ð ñ ð. $ØØØØØØØð1ð 1ð 1ð 1ð 1ð 1ð 1ð,uð uð uðn
ð 
ð 
ð4ð ð ð:ð ð ð ð ð ð r/   r×   )9Úcollections.abcr   Únumbersr   r   Únumpyr3   Úbaser   r   r	   r
   r   Ú
exceptionsr   Úmetricsr   r   Úmetrics._scorerr   Úutilsr   Úutils._param_validationr   r   r   r   Úutils._responser   Úutils.metadata_routingr   r   r   r   Úutils.metaestimatorsr   Úutils.multiclassr   Úutils.parallelr   r   Úutils.validationr   r   r    r!   Ú_splitr#   r$   r1   r?   rA   rt   r•   rÉ   rÕ   r×   r0   r/   r-   ú<module>r     s  ðØ *Ð *Ð *Ð *Ð *Ð *Ø "Ð "Ð "Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð ðð ð ð ð ð ð ð ð ð ð ð ð ð ð (Ð 'Ð 'Ð 'Ð 'Ð 'ðð ð ð ð ð ð ð ð *Ð )Ð )Ð )Ð )Ð )Ø "Ð "Ð "Ð "Ð "Ð "Ø RÐ RÐ RÐ RÐ RÐ RÐ RÐ RÐ RÐ RÐ RÐ RØ 9Ð 9Ð 9Ð 9Ð 9Ð 9ðð ð ð ð ð ð ð ð ð ð ð ð 0Ð /Ð /Ð /Ð /Ð /Ø -Ð -Ð -Ð -Ð -Ð -Ø .Ð .Ð .Ð .Ð .Ð .Ð .Ð .ðð ð ð ð ð ð ð ð ð ð ð ð 5Ð 4Ð 4Ð 4Ð 4Ð 4Ð 4Ð 4ðð ð ð"	Wð 	Wð 	Wða
ð a
ð a
ð a
ð a
˜oÐ/AÀ=ñ a
ô a
ð a
ðHqð qð qð qð qÐ6ñ qô qð qðhf@ð f@ð f@ð f@ð f@�;ñ f@ô f@ð f@ðRFFð FFð FFðRð ð ð8@ð @ð @ð @ð @Ð!8ñ @ô @ð @ð @ð @r/   