Ë
    ÷Q(h0€  ã                   ó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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/m0Z0 ddl1m2Z2m3Z3 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)Ú_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Ú	indexableé   )ÚStratifiedShuffleSplitÚcheck_cvc                 óf   — 	 t        | j                  «       y # t        $ r t        | d«       Y y w xY w)NÚ
estimator_)r#   Ú	estimatorr   )r*   s    úo/var/www/skyplay_api_hub/venv/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>   Úautor0   r1   ©r*   Úresponse_methodÚ_parameter_constraintsr2   ©r4   c                ó    — || _         || _        y ©Nr3   )Úselfr*   r4   s      r+   Ú__init__z BaseThresholdClassifier.__init__Y   s   € Ø"ˆŒØ.ˆÕó    c                 óH   — | j                   dk(  rddg}|S | j                   }|S )zDefine the response method.r2   r0   r1   r6   )r9   r4   s     r+   Ú_get_response_methodz,BaseThresholdClassifier._get_response_method]   s6   € à×Ñ 6Ò)Ø.Ð0CÐDˆOð Ðð #×2Ñ2ˆOØÐr;   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)   rD   rE   )r9   ÚXrA   ÚparamsÚy_types        r+   r/   zBaseThresholdClassifier.fite   s©   € ô0 	˜& $¨Ô-ä˜˜A‹‰ˆˆ1ä ¨cÔ2ˆØ�XÒÜØOÐPVÈxÐXóð ð 	ˆ�	‰	�!�QÑ!˜&Ò!ä�4—?‘?Ð$4Ô5Ø"&§/¡/×"@Ñ"@ˆDÔÜ�4—?‘?Ð$7Ô8Ø%)§_¡_×%FÑ%FˆDÔ"àˆr;   c                 ó.   — | j                   j                  S )zClasses labels.)r)   Úclasses_)r9   s    r+   rM   z BaseThresholdClassifier.classes_�   s   € ð �‰×'Ñ'Ð'r;   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*   r0   ©r9   rI   r*   s      r+   r0   z%BaseThresholdClassifier.predict_proba•   s/   € ô 	˜ÔÜ˜D ,°·±Ó?ˆ	Ø×&Ñ& qÓ)Ð)r;   Ú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,   rO   r*   rQ   rP   s      r+   rQ   z)BaseThresholdClassifier.predict_log_proba¨   ó/   € ô 	˜ÔÜ˜D ,°·±Ó?ˆ	Ø×*Ñ*¨1Ó-Ð-r;   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,   rO   r*   r1   rP   s      r+   r1   z)BaseThresholdClassifier.decision_function»   rS   r;   c                 ó¶   •— t         ‰| �  «       }d|j                  _        t	        | j
                  «      j                  j                  |j                  _        |S )NF)ÚsuperÚ__sklearn_tags__Úclassifier_tagsÚmulti_classr   r*   Ú
input_tagsÚsparse)r9   ÚtagsÚ	__class__s     €r+   rW   z(BaseThresholdClassifier.__sklearn_tags__Î   sD   ø€ Ü‰wÑ'Ó)ˆØ+0ˆ×ÑÔ(Ü!)¨$¯.©.Ó!9×!DÑ!D×!KÑ!Kˆ�‰ÔØˆr;   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r5   ÚdictÚ__annotations__r:   r=   r
   r/   ÚpropertyrM   r   r!   r0   rQ   r1   rW   Ú__classcell__©r]   s   @r+   r.   r.   6   sí   ø… ññ8 ˜˜Ð/Ó0Ù˜Ð2Ð3Ó4ð
ñ 'Ò'UÓVÐWñ$Ð˜Dó ð 6<ô /òñ à&+ôñ%ó	ð%ðN ñ(ó ð(ñ ‘. Ó1Ó2ñ*ó 3ð*ñ$ ‘.Ð!4Ó5Ó6ñ.ó 7ð.ñ$ ‘.Ð!4Ó5Ó6ñ.ó 7ð.÷$ð r;   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]]
    r2   ÚbooleanN)Ú	thresholdÚ	pos_labelr5   )rj   rk   r4   c                óD   •— t         ‰| �  ||¬«       || _        || _        y ©Nr3   )rV   r:   rk   rj   )r9   r*   rj   rk   r4   r]   s        €r+   r:   z!FixedThresholdClassifier.__init__3  s%   ø€ ô 	‰Ñ 9¸oÐÔNØ"ˆŒØ"ˆ�r;   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.)rO   rM   r#   r*   r   ÚAttributeError)r9   r*   s     r+   rM   z!FixedThresholdClassifier.classes_?  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)   )r9   rI   rA   rJ   Úrouted_paramss        r+   rG   zFixedThresholdClassifier._fitK  sJ   € ô( (¨¨eÑ>°vÑ>ˆØ3œ% §¡Ó/×3Ñ3°A°qÑX¸M×<SÑ<S×<WÑ<WÑXˆŒØˆr;   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)rk   Úreturn_response_method_usedr2   r0   g      à?ç        )	r,   rO   r*   r   r=   rk   rj   r   rM   )r9   rI   r*   Úy_scoreÚ_Úresponse_method_usedÚdecision_thresholds          r+   Úpredictz FixedThresholdClassifier.predictc  s“   € ô 	˜Ôä˜D ,°·±Ó?ˆ	ä+FØØØ×%Ñ%Ó'Ø—n‘nØ(,ô,
Ñ(ˆ�Ð(ð �>‰>˜VÒ#Ø(<ÀÒ(O¡ÐUXÑà!%§¡Ðä0ØÐ'¨¯©¸¿¹ó
ð 	
r;   c                 ó®   — t        | j                  j                  ¬«      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   r]   r^   Úaddr*   r   ©r9   Úrouters     r+   Úget_metadata_routingz-FixedThresholdClassifier.get_metadata_routing…  sL   € ô   d§n¡n×&=Ñ&=Ô>×BÑBØ—n‘nÜ(›?×.Ñ.°eÀEÐ.ÓJð Có 
ˆð ˆr;   )r^   r_   r`   ra   r.   r5   r   r   Ústrrb   rc   r:   rd   rM   rG   rz   r‡   re   rf   s   @r+   rh   rh   Õ   s{   ø… ñUðn$Ø
!×
8Ñ
8ð$á  & Ó*¨DÐ1Ø˜C ¨DÐ1ò$Ð˜Dó ð ØØö
#ð ñ	"ó ð	"òò0 
öDr;   rh   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 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.
    ©Úindices)r   r    r/   )Ú
classifierrI   rA   Ú
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´~ÀaÈÓ7Q�ˆÜ'¨¨9Ó5´~ÀaÈÓ7Q�ˆÜ/°°:ÀyÔQÐÜ/°°<ÈÔQÐØˆ
�‰�w Ñ<Ð+;Ó<à)*¨A¨|Ð&ˆuˆá˜
 E¨5ÑEÐ4DÑEÐEr;   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 )ÚTunedThresholdClassifierCVa8  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 :ref:`scoring_parameter`);
        * 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Úprefitru   g      ð?Úneitherri   Úrandom_state)ÚscoringÚ
thresholdsÚcvÚrefitÚn_jobsr¬   Ústore_cv_resultsr5   Úbalanced_accuracyr2   éd   TF)r­   r4   r®   r¯   r°   r±   r¬   r²   c                óŠ   •— t         ‰
| �  ||¬«       || _        || _        || _        || _        || _        || _        |	| _        y rm   )	rV   r:   r­   r®   r¯   r°   r±   r¬   r²   )r9   r*   r­   r4   r®   r¯   r°   r±   r¬   r²   r]   s             €r+   r:   z#TunedThresholdClassifierCV.__init__³  sJ   ø€ ô 	‰Ñ 9¸oÐÔNØˆŒØ$ˆŒØˆŒØˆŒ
ØˆŒØ(ˆÔØ 0ˆÕr;   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.rM   z-When cv='prefit', `estimator` must be fitted.N)rA   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�   rI   rŒ   r¯   rq   r9   rA   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r8   )Úmin©r½   r¢   s     r+   r¾   z2TunedThresholdClassifierCV._fit.<locals>.<genexpr>%  ó   è ø€ ò 
Ø'7Ð× Ñ ×"ñ
ùó   ‚c              3   ó<   K  — | ]  }|j                  «       –— Œ y ­wr8   )ÚmaxrÅ   s     r+   r¾   z2TunedThresholdClassifierCV._fit.<locals>.<genexpr>(  rÆ   rÇ   )Únum)r®   Úscores)*Ú
isinstancer¯   r   r&   r¬   r°   rF   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_)r9   rI   rA   rJ   ÚexcÚsplitsr’   r”   r–   rŽ   rw   r¡   r    Úmin_thresholdÚmax_thresholdÚdecision_thresholdsÚobjective_scoresÚbest_idxrŒ   r¯   rq   s   ```               @@@r+   rG   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 )rs   r)   )rk   )	r#   rº   Ú_get_pos_labelr   r)   r=   r   rØ   rM   )r9   rI   rk   rv   rw   s        r+   rz   z"TunedThresholdClassifierCV.predict@  sk   € ô 	˜˜lÔ+Ø×&Ñ&×5Ñ5Ó7ˆ	Ü0Ø�O‰OØØ×%Ñ%Ó'Øô	
‰
ˆ�ô 1Ø�T×)Ñ)¨4¯=©=¸)ó
ð 	
r;   c                 ó†  — t        | j                  j                  ¬«      j                  | j                  t        «       j                  dd¬«      ¬«      j                  | j                  t        «       j                  dd¬«      ¬«      j                  | j                  «       t        «       j                  dd¬«      ¬«      }|S )	r|   r}   r/   r   r‚   rÐ   )rÑ   rƒ   r¼   )r»   rƒ   )r   r]   r^   r„   r*   r   r¯   rÎ   r…   s     r+   r‡   z/TunedThresholdClassifierCV.get_metadata_routingZ  s¬   € ô  §¡×!8Ñ!8Ô9ß‰SØŸ.™.Ü,›×2Ñ2¸%ÈÐ2ÓNð ó ÷ ‰SØŸ™Ü,›×2Ñ2¸'È%Ð2ÓPð ó ÷ ‰SØ×-Ñ-Ó/Ü,›×2Ñ2¸'È%Ð2ÓPð ó ð 	ð ˆr;   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®   )r9   r­   r�   s      r+   rÎ   z,TunedThresholdClassifierCV._get_curve_scorerw  sB   € ä §¡¸¿¹ÔEˆÜ#×/Ñ/Ø�T×.Ñ.Ó0°$·/±/ó
ˆð Ðr;   )r^   r_   r`   ra   r.   r5   r   Úsetr   Úcallabler   r   r   r   rb   rc   r:   rG   rz   r‡   rÎ   re   rf   s   @r+   r¦   r¦   ý  sÎ   ø… ñ`ðD$Ø
!×
8Ñ
8ð$ñ ‘sÑ+Ó-Ó.Ó/ØØð
ñ
   ¨!¨T¸&ÔAÀ<ÐPàÙ˜�zÓ"Ù�Z  c°)Ô<ð
ð
 �Ø˜TÐ"Ø'Ð(Ø&˜Kò!$Ð˜Dó ð. $ØØØØØØØö1ò,uòn
ò4ö:r;   r¦   ):Úcollections.abcr   Únumbersr   r   Únumpyr›   Úbaser   r   r	   r
   r   Ú
exceptionsr   Úmetricsr   r   Úmetrics._scorerr   r   Úutilsr   r   Ú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#   r$   Ú_splitr&   r'   r,   r.   rh   r˜   r¤   r¦   © r;   r+   ú<module>rù      s    ðõ +ß "ã ÷õ õ (÷÷÷ -ß RÓ RÝ 9÷ó õ 0Ý -ß .÷õ ÷ 5ò1ô\˜oÐ/AÀ=ô \ô~@Ð6ô @òFFFòRô8@Ð!8õ @r;   