Ë
    íì�iš  ã                   óh  — 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mZ d dlmZ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! 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/m0Z0m1Z1m2Z2m3Z3 d„ Z4 G d„ de	e
e«      Z5 G d„ de5«      Z6d„ Z7d„ Z8 G d„ de5«      Z9y)é    )ÚMutableMapping)ÚIntegralÚRealN)ÚBaseEstimatorÚClassifierMixinÚMetaEstimatorMixinÚ_fit_contextÚclone)ÚNotFittedError)Úcheck_scoringÚget_scorer_names)Ú_CurveScorerÚ!_threshold_scores_to_class_labels)ÚStratifiedShuffleSplitÚcheck_cv)Ú_safe_indexingÚget_tags)Ú
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Ú_estimator_hasÚ_num_samplesÚcheck_is_fittedÚ	indexablec                 óf   — 	 t        | j                  «       y # t        $ r t        | d«       Y y w xY w)NÚ
estimator_)r$   Ú	estimatorr   )r(   s    ú–/var/www/ITT-ServiceAPI-Services/ITT-Document-Scan/mrzscanner/mrzenv/lib/python3.12/site-packages/sklearn/model_selection/_classification_threshold.pyÚ_check_is_fittedr*   )   s.   € ð1Ü˜	×+Ñ+Õ,øÜò 1Ü˜	 <Ö0ð1ús   ‚ ˜0¯0c                   ó&  ‡ — e Zd ZU d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ˆ fd„Zˆ xZ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.
    ÚfitÚpredict_probaÚdecision_function>   Úautor.   r/   ©r(   Úresponse_methodÚ_parameter_constraintsr0   ©r2   c                ó    — || _         || _        y ©Nr1   )Úselfr(   r2   s      r)   Ú__init__z BaseThresholdClassifier.__init__S   s   € Ø"ˆŒØ.ˆÕó    c                 óH   — | j                   dk(  rddg}|S | j                   }|S )zDefine the response method.r0   r.   r/   r4   )r7   r2   s     r)   Ú_get_response_methodz,BaseThresholdClassifier._get_response_methodW   s6   € à×Ñ 6Ò)Ø.Ð0CÐDˆOð Ðð #×2Ñ2ˆOØÐr9   F)Úprefer_skip_nested_validationc                 ój  — t        || d«       t        ||«      \  }}t        |d¬«      }|dk7  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Ú_fitÚhasattrr'   rB   rC   )r7   ÚXr?   ÚparamsÚy_types        r)   r-   zBaseThresholdClassifier.fit_   s©   € ô0 	˜& $¨Ô-ä˜˜A‹‰ˆˆ1ä ¨cÔ2ˆØ�XÒÜØOÐPVÈxÐXóð ð 	ˆ�	‰	�!�QÑ!˜&Ò!ä�4—?‘?Ð$4Ô5Ø"&§/¡/×"@Ñ"@ˆDÔÜ�4—?‘?Ð$7Ô8Ø%)§_¡_×%FÑ%FˆDÔ"àˆr9   c                 ó.   — | j                   j                  S )zClasses labels.)r'   Úclasses_)r7   s    r)   rK   z BaseThresholdClassifier.classes_Š   s   € ð �‰×'Ñ'Ð'r9   c                 óh   — t        | «       t        | d| j                  «      }|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*   Úgetattrr(   r.   ©r7   rG   r(   s      r)   r.   z%BaseThresholdClassifier.predict_proba�   s/   € ô 	˜ÔÜ˜D ,°·±Ó?ˆ	Ø×&Ñ& qÓ)Ð)r9   Úpredict_log_probac                 óh   — t        | «       t        | d| j                  «      }|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*   rM   r(   rO   rN   s      r)   rO   z)BaseThresholdClassifier.predict_log_proba¢   ó/   € ô 	˜ÔÜ˜D ,°·±Ó?ˆ	Ø×*Ñ*¨1Ó-Ð-r9   c                 óh   — t        | «       t        | d| j                  «      }|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*   rM   r(   r/   rN   s      r)   r/   z)BaseThresholdClassifier.decision_functionµ   rQ   r9   c                 ó¶   •— t         ‰| �  «       }d|j                  _        t	        | j
                  «      j                  j                  |j                  _        |S )NF)ÚsuperÚ__sklearn_tags__Úclassifier_tagsÚmulti_classr   r(   Ú
input_tagsÚsparse)r7   ÚtagsÚ	__class__s     €r)   rU   z(BaseThresholdClassifier.__sklearn_tags__È   sD   ø€ Ü‰wÑ'Ó)ˆØ+0ˆ×ÑÔ(Ü!)¨$¯.©.Ó!9×!DÑ!D×!KÑ!Kˆ�‰ÔØˆr9   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r3   ÚdictÚ__annotations__r8   r;   r	   r-   ÚpropertyrK   r   r"   r.   rO   r/   rU   Ú__classcell__©r[   s   @r)   r,   r,   0   sí   ø… ññ8 ˜˜Ð/Ó0Ù˜Ð2Ð3Ó4ð
ñ 'Ò'UÓVÐWñ$Ð˜Dó ð 6<ô /òñ à&+ôñ%ó	ð%ðN ñ(ó ð(ñ ‘. Ó1Ó2ñ*ó 3ð*ñ$ ‘.Ð!4Ó5Ó6ñ.ó 7ð.ñ$ ‘.Ð!4Ó5Ó6ñ.ó 7ð.÷$ð r9   r,   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e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]]
    r0   ÚbooleanN)Ú	thresholdÚ	pos_labelr3   )rh   ri   r2   c                óD   •— t         ‰| �  ||¬«       || _        || _        y ©Nr1   )rT   r8   ri   rh   )r7   r(   rh   ri   r2   r[   s        €r)   r8   z!FixedThresholdClassifier.__init__-  s%   ø€ ô 	‰Ñ 9¸oÐÔNØ"ˆŒØ"ˆ�r9   c                 óÊ   — t        | dd «      x}r|j                  S 	 t        | j                  «       | j                  j                  S # t        $ r t        d«      t        ‚w xY w)Nr'   z+The underlying estimator is not fitted yet.)rM   rK   r$   r(   r   ÚAttributeError)r7   r(   s     r)   rK   z!FixedThresholdClassifier.classes_9  se   € ä  l°DÓ9Ð9ˆ9Ð9Ø×%Ñ%Ð%ð	"Ü˜DŸN™NÔ+Ø—>‘>×*Ñ*Ð*øÜò 	"Ü Ø=óä!ð"ð	"ús   �*A ÁA"c                 ó    — t        | dfi |¤Ž} t        | j                  «      j                  ||fi |j                  j                  ¤Ž| _        | S )r>   r-   )r   r
   r(   r-   r'   )r7   rG   r?   rH   Úrouted_paramss        r)   rE   zFixedThresholdClassifier._fitE  sJ   € ô( (¨¨eÑ>°vÑ>ˆØ3œ% §¡Ó/×3Ñ3°A°qÑX¸M×<SÑ<S×<WÑ<WÑXˆŒØˆr9   c                 ó,  — t        | «       t        | d| j                  «      }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)ri   Úreturn_response_method_usedr0   r.   g      à?ç        )	r*   rM   r(   r   r;   ri   rh   r   rK   )r7   rG   r(   Úy_scoreÚ_Úresponse_method_usedÚdecision_thresholds          r)   Úpredictz FixedThresholdClassifier.predict]  s“   € ô 	˜Ôä˜D ,°·±Ó?ˆ	ä+FØØØ×%Ñ%Ó'Ø—n‘nØ(,ô,
Ñ(ˆ�Ð(ð �>‰>˜VÒ#Ø(<ÀÒ(O¡ÐUXÑà!%§¡Ðä0ØÐ'¨¯©¸¿¹ó
ð 	
r9   c                 ó†   — t        | ¬«      j                  | j                  t        «       j                  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.
        ©Úownerr-   ©ÚcalleeÚcaller©r(   Úmethod_mapping)r   Úaddr(   r   ©r7   Úrouters     r)   Úget_metadata_routingz-FixedThresholdClassifier.get_metadata_routing  sA   € ô   dÔ+×/Ñ/Ø—n‘nÜ(›?×.Ñ.°eÀEÐ.ÓJð 0ó 
ˆð ˆr9   )r\   r]   r^   r_   r,   r3   r   r   Ústrr`   ra   r8   rb   rK   rE   rx   r…   rc   rd   s   @r)   rf   rf   Ï   s{   ø… ñUðn$Ø
!×
8Ñ
8ð$á  & Ó*¨DÐ1Ø˜C ¨DÐ1ò$Ð˜Dó ð ØØö
#ð ñ	"ó ð	"òò0 
öDr9   rf   c                óê   — |�at        ||«      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 outputs a single score value as `curve_scorer`
        outputs 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.
    ©Úindices)r   r!   r-   )Ú
classifierrG   r?   Ú
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�   € ðp ÐÜ'¨¨9Ó5´~ÀaÈÓ7Q�ˆÜ'¨¨9Ó5´~ÀaÈÓ7Q�ˆÜ/°°:ÀyÔQÐÜ/°°<ÈÔQÐØˆ
�‰�w Ñ<Ð+;Ó<à)*¨A¨|Ð&ˆuˆá˜
 E¨5ÑEÐ4DÑEÐEr9   c                 ó    — t        j                  t        ||«      D ��cg c]  \  }}t        j                  | ||«      ‘Œ c}}d¬«      S c c}}w )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.
    r   )Úaxis)ÚnpÚmeanÚzipÚinterp)Útarget_thresholdsÚcv_thresholdsÚ	cv_scoresÚsplit_thresholdsÚsplit_scores        r)   Ú_mean_interpolated_scorer¢   Ö  sR   € ô& �7‰7ô 25°]ÀIÓ1N÷	
á-Ð  +ô �I‰IÐ'Ð)9¸;ÕGó	
ð ôð ùó	
s   Ÿ!A

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

        - str: string associated to a scoring function for binary classification,
          see :ref:`scoring_string_names` for options.
        - callable: a scorer callable object (e.g., function) with signature
          ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details.

    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>
    é   NÚleft)Úclosedz
array-likeÚ	cv_objectÚprefitrs   g      ð?Úneitherrg   Úrandom_state)ÚscoringÚ
thresholdsÚcvÚrefitÚn_jobsr«   Ústore_cv_resultsr3   Úbalanced_accuracyr0   éd   TF)r¬   r2   r­   r®   r¯   r°   r«   r±   c                óŠ   •— t         ‰
| �  ||¬«       || _        || _        || _        || _        || _        || _        |	| _        y rk   )	rT   r8   r¬   r­   r®   r¯   r°   r«   r±   )r7   r(   r¬   r2   r­   r®   r¯   r°   r«   r±   r[   s             €r)   r8   z#TunedThresholdClassifierCV.__init__©  sJ   ø€ ô 	‰Ñ 9¸oÐÔNØˆŒØ$ˆŒØˆŒØˆŒ
ØˆŒØ(ˆÔØ 0ˆÕr9   c           
      ó  ‡ ‡‡‡‡‡— t        ‰ j                  t        «      r;d‰ j                  cxk  rdk  r&n n#t        d‰ j                  ‰ j                  ¬«      Šn�‰ j                  dk(  r=‰ j
                  du rt        d«      ‚	 t        ‰ j                  d«       ‰ j                  ŠnDt        ‰ j                  ‰d¬
«      Š‰ j
                  du r‰j                  «       dkD  rt        d«      ‚t        ‰ dfi |¤ŽŠ‰ j                  «       ‰ _        ‰dk(  r6‰ j                  ‰ _        ‰ j                  Šd	t!        t#        ‰«      «      fg}�n
t%        ‰ j                  «      ‰ _        t%        ‰ j                  «      Š ‰j&                  ‰‰fi ‰j(                  j&                  ¤Ž}‰ j
                  r‰‰‰j                  j*                  }}}nnt-         ‰j&                  ‰‰fi ‰j(                  j&                  ¤Ž«      \  }	}
t/        ‰|	«      }t/        ‰|	«      }t1        ‰‰j                  j*                  |	¬«      } ‰ j                  j*                  ||fi |¤Ž t3         t5        ‰ j6                  ¬«      ˆˆˆˆˆ ˆfd„|D «       «      Ž \  }}t9        d„ |D «       «      rt        d«      ‚t;        d„ |D «       «      }t=        d„ |D «       «      }t        ‰ j>                  t@        «      r#tC        jD                  ||‰ j>                  ¬«      }ntC        jF                  ‰ j>                  «      }tI        |||«      }|jK                  «       }||   ‰ _&        ||   ‰ _'        ‰ jP                  r
||dœ‰ _)        ‰ S # t        $ r}t        d«      |‚d	}~ww xY w)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.rK   z-When cv='prefit', `estimator` must be fitted.N)r?   rŠ   Fz1When cv has several folds, refit cannot be False.r-   rˆ   )r°   c              3   óâ   •K  — | ]f  \  }} t        t        «      ‰d k7  rt        ‰«      n‰‰‰‰j                  j                  ||‰j
                  ‰j                  j                  ¬«      –— Œh y­w)r©   )r‹   rŒ   r�   rŽ   r�   N)r    r–   r
   r(   r-   Ú_curve_scorerÚscorerÚscore)	Ú.0rŒ   r�   rG   rŠ   r®   ro   r7   r?   s	      €€€€€€r)   ú	<genexpr>z2TunedThresholdClassifierCV._fit.<locals>.<genexpr>  st   øè ø€ ò *ñ '�I˜wð 8”Ô6Ó7Ø)+¨xª”E˜*Ô%¸ZØØØ,×6Ñ6×:Ñ:Ø'Ø#Ø!%×!3Ñ!3Ø!.×!5Ñ!5×!;Ñ!;÷	ð 	ñ*ùs   ƒA,A/c              3   óT   K  — | ]   }t        j                  |d    |d   «      –— Œ" y­w)r   éÿÿÿÿN)r™   Úisclose)r¼   Úths     r)   r½   z2TunedThresholdClassifierCV._fit.<locals>.<genexpr>  s#   è ø€ ÒA¨RŒr�z‰z˜"˜Q™%  B¡×(ÑAùs   ‚&(zrThe provided estimator makes constant predictions. Therefore, it is impossible to optimize the decision threshold.c              3   ó<   K  — | ]  }|j                  «       –— Œ y ­wr6   )Úmin©r¼   r    s     r)   r½   z2TunedThresholdClassifierCV._fit.<locals>.<genexpr>  ó   è ø€ ò 
Ø'7Ð× Ñ ×"ñ
ùó   ‚c              3   ó<   K  — | ]  }|j                  «       –— Œ y ­wr6   )ÚmaxrÄ   s     r)   r½   z2TunedThresholdClassifierCV._fit.<locals>.<genexpr>  rÅ   rÆ   )Únum)r­   Úscores)*Ú
isinstancer®   r   r   r«   r¯   rD   r$   r(   r   r   Úget_n_splitsr   Ú_get_curve_scorerr¹   r'   Úranger#   r
   ÚsplitÚsplitterr-   Únextr   r!   r›   r   r°   ÚanyrÃ   rÈ   r­   r   r™   ÚlinspaceÚasarrayr¢   ÚargmaxÚbest_score_Úbest_threshold_r±   Úcv_results_)r7   rG   r?   rH   ÚexcÚsplitsr�   r’   r”   rŒ   ru   rŸ   rž   Úmin_thresholdÚmax_thresholdÚdecision_thresholdsÚobjective_scoresÚbest_idxrŠ   r®   ro   s   ```               @@@r)   rE   zTunedThresholdClassifierCV._fit¿  s=  ý€ ô( �d—g‘gœtÔ$¨¨T¯W©W¬°q­Ü'Ø d§g¡g¸D×<MÑ<Mô‰Bð �W‰W˜Ò Ø�z‰z˜TÑ!Ü Ð!JÓKÐKðÜ §¡°
Ô;ð
 —‘‰Bä˜$Ÿ'™' Q°4Ô8ˆBØ�z‰z˜UÑ" r§¡Ó'8¸1Ò'<Ü Ð!TÓUÐUä'¨¨eÑ>°vÑ>ˆØ!×3Ñ3Ó5ˆÔð �Š>Ø"Ÿn™nˆDŒOØŸ™ˆJØœU¤<°£?Ó3Ð4Ð5ŠFä# D§N¡NÓ3ˆDŒOÜ˜tŸ~™~Ó.ˆJØ�R—X‘X˜a ÑC m×&<Ñ&<×&BÑ&BÑCˆFà�zŠzà56¸¸=×;RÑ;R×;VÑ;VÐ"2˜‘ô  $ H B§H¡H¨Q°Ñ$R°]×5KÑ5K×5QÑ5QÑ$RÓS‘�	˜1Ü(¨¨IÓ6�Ü(¨¨IÓ6�Ü#7Ø�}×.Ñ.×2Ñ2¸Iô$Ð ð  ˆD�O‰O×Ñ ¨ÑEÐ4DÒEä#&Ø)ŒX˜TŸ[™[Ô)÷ *ð *ð +1ô*ó ð$
Ñ ˆ	�=ô  ÑA°=ÔAÔAÜðAóð ô ñ 
Ø;Hô
ó 
ˆô ñ 
Ø;Hô
ó 
ˆô �d—o‘o¤xÔ0Ü"$§+¡+Ø˜}°$·/±/ô#Ñô #%§*¡*¨T¯_©_Ó"=Ðä3Ø °	ó
Ðð $×*Ñ*Ó,ˆØ+¨HÑ5ˆÔØ2°8Ñ<ˆÔØ× Ò à1Ø*ñ ˆDÔð
 ˆøôq "ò Ü$ØGóàðûðús   ÂM, Í,	NÍ5NÎNc                 óæ   — t        | d«       | j                  j                  «       }t        | j                  || j                  «       |¬«      \  }}t        || j                  | j                  |«      S )rq   r'   )ri   )	r$   r¹   Ú_get_pos_labelr   r'   r;   r   r×   rK   )r7   rG   ri   rt   ru   s        r)   rx   z"TunedThresholdClassifierCV.predict6  sk   € ô 	˜˜lÔ+Ø×&Ñ&×5Ñ5Ó7ˆ	Ü0Ø�O‰OØØ×%Ñ%Ó'Øô	
‰
ˆ�ô 1Ø�T×)Ñ)¨4¯=©=¸)ó
ð 	
r9   c                 ó^  — t        | ¬«      j                  | j                  t        «       j                  dd¬«      ¬«      j                  | j                  t        «       j                  dd¬«      ¬«      j                  | j                  «       t        «       j                  dd¬«      ¬«      }|S )	rz   r{   r-   r}   r€   rÏ   )rÐ   r�   r»   )rº   r�   )r   r‚   r(   r   r®   rÍ   rƒ   s     r)   r…   z/TunedThresholdClassifierCV.get_metadata_routingP  s¢   € ô  Ô&ß‰SØŸ.™.Ü,›×2Ñ2¸%ÈÐ2ÓNð ó ÷ ‰SØŸ™Ü,›×2Ñ2¸'È%Ð2ÓPð ó ÷ ‰SØ×-Ñ-Ó/Ü,›×2Ñ2¸'È%Ð2ÓPð ó ð 	ð ˆr9   c                 ó¦   — t        | j                  | j                  ¬«      }t        j                  || j                  «       | j                  «      }|S )z8Get the curve scorer based on the objective metric used.)r¬   )r   r(   r¬   r   Úfrom_scorerr;   r­   )r7   r¬   rŽ   s      r)   rÍ   z,TunedThresholdClassifierCV._get_curve_scorerm  sB   € ä §¡¸¿¹ÔEˆÜ#×/Ñ/Ø�T×.Ñ.Ó0°$·/±/ó
ˆð Ðr9   )r\   r]   r^   r_   r,   r3   r   Úsetr   Úcallabler   r   r   r   r`   ra   r8   rE   rx   r…   rÍ   rc   rd   s   @r)   r¤   r¤   ò  sÎ   ø… ñaðF$Ø
!×
8Ñ
8ð$ñ ‘sÑ+Ó-Ó.Ó/ØØð
ñ
   ¨!¨T¸&ÔAÀ<ÐPàÙ˜�zÓ"Ù�Z  c°)Ô<ð
ð
 �Ø˜TÐ"Ø'Ð(Ø&˜Kò!$Ð˜Dó ð. $ØØØØØØØö1ò,uòn
ò4ö:r9   r¤   ):Úcollections.abcr   Únumbersr   r   Únumpyr™   Úsklearn.baser   r   r   r	   r
   Úsklearn.exceptionsr   Úsklearn.metricsr   r   Úsklearn.metrics._scorerr   r   Úsklearn.model_selection._splitr   r   Úsklearn.utilsr   r   Úsklearn.utils._param_validationr   r   r   r   Úsklearn.utils._responser   Úsklearn.utils.metadata_routingr   r   r   r   Úsklearn.utils.metaestimatorsr   Úsklearn.utils.multiclassr   Úsklearn.utils.parallelr   r    Úsklearn.utils.validationr!   r"   r#   r$   r%   r*   r,   rf   r–   r¢   r¤   © r9   r)   ú<module>rø      s˜   ðõ +ß "ã ÷õ õ .ß ;ß Sß Kß 2ß XÓ XÝ ?÷ó õ 6Ý 3ß 4÷õ ò1ô\˜oÐ/AÀ=ô \ô~@Ð6ô @òFAFòHô8AÐ!8õ Ar9   