
    rho                     r    d dl Z d dlZddlmZ ddlmZmZmZm	Z	m
Z
mZ ddlmZ ddlmZmZ  G d d	e      Zy)
    N   )_safe_indexing)"_BinaryClassifierCurveDisplayMixin_check_param_lengths_convert_to_list_leaving_none_deprecate_estimator_name_despine_validate_style_kwargs)_get_response_values_binary   )auc	roc_curvec                        e Zd ZdZddddddZ fdZ	 dddddddd	Zedd
ddddddddd
d       Ze	 ddd
ddddddddd
d       Z	edd
ddddddddd
d       Z
 xZS )RocCurveDisplaya  ROC Curve visualization.

    It is recommended to use
    :func:`~sklearn.metrics.RocCurveDisplay.from_estimator` or
    :func:`~sklearn.metrics.RocCurveDisplay.from_predictions` or
    :func:`~sklearn.metrics.RocCurveDisplay.from_cv_results` to create
    a :class:`~sklearn.metrics.RocCurveDisplay`. All parameters are
    stored as attributes.

    For general information regarding `scikit-learn` visualization tools, see
    the :ref:`Visualization Guide <visualizations>`.
    For guidance on interpreting these plots, refer to the :ref:`Model
    Evaluation Guide <roc_metrics>`.

    Parameters
    ----------
    fpr : ndarray or list of ndarrays
        False positive rates. Each ndarray should contain values for a single curve.
        If plotting multiple curves, list should be of same length as `tpr`.

        .. versionchanged:: 1.7
            Now accepts a list for plotting multiple curves.

    tpr : ndarray or list of ndarrays
        True positive rates. Each ndarray should contain values for a single curve.
        If plotting multiple curves, list should be of same length as `fpr`.

        .. versionchanged:: 1.7
            Now accepts a list for plotting multiple curves.

    roc_auc : float or list of floats, default=None
        Area under ROC curve, used for labeling each curve in the legend.
        If plotting multiple curves, should be a list of the same length as `fpr`
        and `tpr`. If `None`, ROC AUC scores are not shown in the legend.

        .. versionchanged:: 1.7
            Now accepts a list for plotting multiple curves.

    name : str or list of str, default=None
        Name for labeling legend entries. The number of legend entries is determined
        by the `curve_kwargs` passed to `plot`, and is not affected by `name`.
        To label each curve, provide a list of strings. To avoid labeling
        individual curves that have the same appearance, this cannot be used in
        conjunction with `curve_kwargs` being a dictionary or None. If a
        string is provided, it will be used to either label the single legend entry
        or if there are multiple legend entries, label each individual curve with
        the same name. If still `None`, no name is shown in the legend.

        .. versionadded:: 1.7

    pos_label : int, float, bool or str, default=None
        The class considered as the positive class when computing the roc auc
        metrics. By default, `estimators.classes_[1]` is considered
        as the positive class.

        .. versionadded:: 0.24

    estimator_name : str, default=None
        Name of estimator. If None, the estimator name is not shown.

        .. deprecated:: 1.7
            `estimator_name` is deprecated and will be removed in 1.9. Use `name`
            instead.

    Attributes
    ----------
    line_ : matplotlib Artist or list of matplotlib Artists
        ROC Curves.

        .. versionchanged:: 1.7
            This attribute can now be a list of Artists, for when multiple curves
            are plotted.

    chance_level_ : matplotlib Artist or None
        The chance level line. It is `None` if the chance level is not plotted.

        .. versionadded:: 1.3

    ax_ : matplotlib Axes
        Axes with ROC Curve.

    figure_ : matplotlib Figure
        Figure containing the curve.

    See Also
    --------
    roc_curve : Compute Receiver operating characteristic (ROC) curve.
    RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic
        (ROC) curve given an estimator and some data.
    RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic
        (ROC) curve given the true and predicted values.
    roc_auc_score : Compute the area under the ROC curve.

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> from sklearn import metrics
    >>> y_true = np.array([0, 0, 1, 1])
    >>> y_score = np.array([0.1, 0.4, 0.35, 0.8])
    >>> fpr, tpr, thresholds = metrics.roc_curve(y_true, y_score)
    >>> roc_auc = metrics.auc(fpr, tpr)
    >>> display = metrics.RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc,
    ...                                   name='example estimator')
    >>> display.plot()
    <...>
    >>> plt.show()
    N
deprecated)roc_aucname	pos_labelestimator_namec                `    || _         || _        || _        t        ||d      | _        || _        y )Nz1.7)fprtprr   r   r   r   )selfr   r   r   r   r   r   s          r/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/sklearn/metrics/_plot/roc_curve.py__init__zRocCurveDisplay.__init__   s0     -ndEJ	"    c                n   t         |   ||      \  | _        | _        }t	        | j
                        }t	        | j                        }t	        | j                        }t	        |      }d|i}t        |t              r!t        |      dk7  r|j                  d|i       t        ||d|d       ||||fS )Naxr   zself.roc_auc   z'name' (or self.name))zself.fprzself.tprr   )requiredoptional
class_name)super_validate_plot_paramsax_figure_r   r   r   r   
isinstancelistlenupdater   )r   r   r   r   r   r   r"   	__class__s          r   r%   z%RocCurveDisplay._validate_plot_params   s    ',w'DQU'D'V$$,+DHH5+DHH5/=,T2"G,dD!c$i1nOO4d;<"%37(	

 C$&&r   F)r   curve_kwargsplot_chance_levelchance_level_kwdespinec                   | j                  ||      \  }}	}
}t        |      }t        |t              s9|dkD  r4|
r,t	        j
                  |
      t	        j                  |
      d}nddd}n|
|
ndg|z  }
d|
i} | j                  |||dfd|i|}dd	d
d}|i }t        ||      }g | _	        t        ||	|      D ]=  \  }}	}| j                  j                   | j                  j                  ||	fi |       ? t        | j                        dk(  r| j                  d   | _	        | j                  d| j                   dnd}d|z   }d|z   }| j                  j                  |d|dd       |r$ | j                  j                  di |\  | _        nd| _        |rt#        | j                         |d   j%                  d      |r-|j%                  d      | j                  j'                  d       | S )a
  Plot visualization.

        Parameters
        ----------
        ax : matplotlib axes, default=None
            Axes object to plot on. If `None`, a new figure and axes is
            created.

        name : str or list of str, default=None
            Name for labeling legend entries. The number of legend entries
            is determined by `curve_kwargs`, and is not affected by `name`.
            To label each curve, provide a list of strings. To avoid labeling
            individual curves that have the same appearance, this cannot be used in
            conjunction with `curve_kwargs` being a dictionary or None. If a
            string is provided, it will be used to either label the single legend entry
            or if there are multiple legend entries, label each individual curve with
            the same name. If `None`, set to `name` provided at `RocCurveDisplay`
            initialization. If still `None`, no name is shown in the legend.

            .. versionadded:: 1.7

        curve_kwargs : dict or list of dict, default=None
            Keywords arguments to be passed to matplotlib's `plot` function
            to draw individual ROC curves. For single curve plotting, should be
            a dictionary. For multi-curve plotting, if a list is provided the
            parameters are applied to the ROC curves of each CV fold
            sequentially and a legend entry is added for each curve.
            If a single dictionary is provided, the same parameters are applied
            to all ROC curves and a single legend entry for all curves is added,
            labeled with the mean ROC AUC score.

            .. versionadded:: 1.7

        plot_chance_level : bool, default=False
            Whether to plot the chance level.

            .. versionadded:: 1.3

        chance_level_kw : dict, default=None
            Keyword arguments to be passed to matplotlib's `plot` for rendering
            the chance level line.

            .. versionadded:: 1.3

        despine : bool, default=False
            Whether to remove the top and right spines from the plot.

            .. versionadded:: 1.6

        **kwargs : dict
            Keyword arguments to be passed to matplotlib's `plot`.

            .. deprecated:: 1.7
                kwargs is deprecated and will be removed in 1.9. Pass matplotlib
                arguments to `curve_kwargs` as a dictionary instead.

        Returns
        -------
        display : :class:`~sklearn.metrics.RocCurveDisplay`
            Object that stores computed values.
        r   r    )meanstdNmetricAUCr-   zChance level (AUC = 0.5)kz--)labelcolor	linestyler   z (Positive label: ) zFalse Positive RatezTrue Positive Rate)g{Gzg)\(?equal)xlabelxlimylabelylimaspectr7   zlower right)loc)r   r    rC   )r%   r*   r(   r)   npr2   r3   _validate_curve_kwargsr
   line_zipextendr&   plotr   setchance_level_r	   getlegend)r   r   r   r-   r.   r/   r0   kwargsr   r   r   n_curveslegend_metricdefault_chance_level_line_kwline_kwinfo_pos_labelr=   r?   s                     r   rI   zRocCurveDisplay.plot   s,   P #'"<"<"<"NS'4s8,-(Q,)+)9"&&/ R)-d ;!(!4g4&8:KG%w/M2t22	

 &
 
 0(
$ " O0(/
 
!$S#|!< 	BCgJJmdhhmmC@@A	B tzz?aADJ 7;nn6P  02VX 	 '7%6 	 	
 $1DHHMM$TO$T!T!%DTXX?w'3/"5"5g">"JHHOOO.r   Tauto)
sample_weightdrop_intermediateresponse_methodr   r   r   r-   r.   r/   r0   c       
         t    | j                  ||||||      \  }}} | j                  d|||||||	|
|||d|S )a^  Create a ROC Curve display from an estimator.

        For general information regarding `scikit-learn` visualization tools,
        see the :ref:`Visualization Guide <visualizations>`.
        For guidance on interpreting these plots, refer to the :ref:`Model
        Evaluation Guide <roc_metrics>`.

        Parameters
        ----------
        estimator : estimator instance
            Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline`
            in which the last estimator is a classifier.

        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Input values.

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

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights.

        drop_intermediate : bool, default=True
            Whether to drop thresholds where the resulting point is collinear
            with its neighbors in ROC space. This has no effect on the ROC AUC
            or visual shape of the curve, but reduces the number of plotted
            points.

        response_method : {'predict_proba', 'decision_function', 'auto'}                 default='auto'
            Specifies whether to use :term:`predict_proba` or
            :term:`decision_function` as the target response. If set to 'auto',
            :term:`predict_proba` is tried first and if it does not exist
            :term:`decision_function` is tried next.

        pos_label : int, float, bool or str, default=None
            The class considered as the positive class when computing the ROC AUC.
            By default, `estimators.classes_[1]` is considered
            as the positive class.

        name : str, default=None
            Name of ROC Curve for labeling. If `None`, use the name of the
            estimator.

        ax : matplotlib axes, default=None
            Axes object to plot on. If `None`, a new figure and axes is created.

        curve_kwargs : dict, default=None
            Keywords arguments to be passed to matplotlib's `plot` function.

            .. versionadded:: 1.7

        plot_chance_level : bool, default=False
            Whether to plot the chance level.

            .. versionadded:: 1.3

        chance_level_kw : dict, default=None
            Keyword arguments to be passed to matplotlib's `plot` for rendering
            the chance level line.

            .. versionadded:: 1.3

        despine : bool, default=False
            Whether to remove the top and right spines from the plot.

            .. versionadded:: 1.6

        **kwargs : dict
            Keyword arguments to be passed to matplotlib's `plot`.

            .. deprecated:: 1.7
                kwargs is deprecated and will be removed in 1.9. Pass matplotlib
                arguments to `curve_kwargs` as a dictionary instead.

        Returns
        -------
        display : :class:`~sklearn.metrics.RocCurveDisplay`
            The ROC Curve display.

        See Also
        --------
        roc_curve : Compute Receiver operating characteristic (ROC) curve.
        RocCurveDisplay.from_predictions : ROC Curve visualization given the
            probabilities of scores of a classifier.
        roc_auc_score : Compute the area under the ROC curve.

        Examples
        --------
        >>> import matplotlib.pyplot as plt
        >>> from sklearn.datasets import make_classification
        >>> from sklearn.metrics import RocCurveDisplay
        >>> from sklearn.model_selection import train_test_split
        >>> from sklearn.svm import SVC
        >>> X, y = make_classification(random_state=0)
        >>> X_train, X_test, y_train, y_test = train_test_split(
        ...     X, y, random_state=0)
        >>> clf = SVC(random_state=0).fit(X_train, y_train)
        >>> RocCurveDisplay.from_estimator(
        ...    clf, X_test, y_test)
        <...>
        >>> plt.show()
        )rW   r   r   )y_truey_scorerU   rV   r   r   r   r-   r.   r/   r0    )!_validate_and_get_response_valuesfrom_predictions)cls	estimatorXyrU   rV   rW   r   r   r   r-   r.   r/   r0   rN   rZ   s                   r   from_estimatorzRocCurveDisplay.from_estimator3  s{    t $'#H#H+ $I $
 D $s## 
'/%/+
 
 	
r   )
rU   rV   r   r   r   r-   r.   r/   r0   y_predc       
   	      d   | t        |t              r|dk(  st        d      t        |t              r|dk(  st        j                  dt
               |}| j                  |||||      \  }}t        |||||      \  }}}t        ||      } | |||||      } |j                  d|||	|
|d|S )	u|  Plot ROC curve given the true and predicted values.

        For general information regarding `scikit-learn` visualization tools,
        see the :ref:`Visualization Guide <visualizations>`.
        For guidance on interpreting these plots, refer to the :ref:`Model
        Evaluation Guide <roc_metrics>`.

        .. versionadded:: 1.0

        Parameters
        ----------
        y_true : array-like of shape (n_samples,)
            True labels.

        y_score : array-like of shape (n_samples,)
            Target scores, can either be probability estimates of the positive
            class, confidence values, or non-thresholded measure of decisions
            (as returned by “decision_function” on some classifiers).

            .. versionadded:: 1.7
                `y_pred` has been renamed to `y_score`.

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights.

        drop_intermediate : bool, default=True
            Whether to drop thresholds where the resulting point is collinear
            with its neighbors in ROC space. This has no effect on the ROC AUC
            or visual shape of the curve, but reduces the number of plotted
            points.

        pos_label : int, float, bool or str, default=None
            The label of the positive class when computing the ROC AUC.
            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.

        name : str, default=None
            Name of ROC curve for legend labeling. If `None`, name will be set to
            `"Classifier"`.

        ax : matplotlib axes, default=None
            Axes object to plot on. If `None`, a new figure and axes is
            created.

        curve_kwargs : dict, default=None
            Keywords arguments to be passed to matplotlib's `plot` function.

            .. versionadded:: 1.7

        plot_chance_level : bool, default=False
            Whether to plot the chance level.

            .. versionadded:: 1.3

        chance_level_kw : dict, default=None
            Keyword arguments to be passed to matplotlib's `plot` for rendering
            the chance level line.

            .. versionadded:: 1.3

        despine : bool, default=False
            Whether to remove the top and right spines from the plot.

            .. versionadded:: 1.6

        y_pred : array-like of shape (n_samples,)
            Target scores, can either be probability estimates of the positive
            class, confidence values, or non-thresholded measure of decisions
            (as returned by “decision_function” on some classifiers).

            .. deprecated:: 1.7
                `y_pred` is deprecated and will be removed in 1.9. Use
                `y_score` instead.

        **kwargs : dict
            Additional keywords arguments passed to matplotlib `plot` function.

            .. deprecated:: 1.7
                kwargs is deprecated and will be removed in 1.9. Pass matplotlib
                arguments to `curve_kwargs` as a dictionary instead.

        Returns
        -------
        display : :class:`~sklearn.metrics.RocCurveDisplay`
            Object that stores computed values.

        See Also
        --------
        roc_curve : Compute Receiver operating characteristic (ROC) curve.
        RocCurveDisplay.from_estimator : ROC Curve visualization given an
            estimator and some data.
        roc_auc_score : Compute the area under the ROC curve.

        Examples
        --------
        >>> import matplotlib.pyplot as plt
        >>> from sklearn.datasets import make_classification
        >>> from sklearn.metrics import RocCurveDisplay
        >>> from sklearn.model_selection import train_test_split
        >>> from sklearn.svm import SVC
        >>> X, y = make_classification(random_state=0)
        >>> X_train, X_test, y_train, y_test = train_test_split(
        ...     X, y, random_state=0)
        >>> clf = SVC(random_state=0).fit(X_train, y_train)
        >>> y_score = clf.decision_function(X_test)
        >>> RocCurveDisplay.from_predictions(y_test, y_score)
        <...>
        >>> plt.show()
        r   z`y_pred` and `y_score` cannot be both specified. Please use `y_score` only as `y_pred` is deprecated in 1.7 and will be removed in 1.9.zUy_pred is deprecated in 1.7 and will be removed in 1.9. Please use `y_score` instead.)rU   r   r   r   rU   rV   r   r   r   r   r   r   r-   r.   r/   r0   r[   )
r(   str
ValueErrorwarningswarnFutureWarning!_validate_from_predictions_paramsr   r   rI   )r^   rY   rZ   rU   rV   r   r   r   r-   r.   r/   r0   rc   rN   pos_label_validatedr   r   _r   vizs                       r   r]   z RocCurveDisplay.from_predictions  s   @ vs#,(>U  63'Fl,BMM4  G$'$I$IG=ITX %J %
!T  '/
S! c3-)
 sxx 
%/+
 
 	
r   )
rU   rV   rW   r   r   r   r-   r.   chance_level_kwargsr0   c       
            | j                  |||||      }g g g }}}t        |d   |d   d         D ]  \  }}t        ||      }t        |t        ||      ||      \  }}|dnt        ||      }t	        |||||      \  }}}t        ||      }|j                  |       |j                  |       |j                  |         | ||||	|      }|j                  ||
|||	      S )
aW  Create a multi-fold ROC curve display given cross-validation results.

        .. versionadded:: 1.7

        Parameters
        ----------
        cv_results : dict
            Dictionary as returned by :func:`~sklearn.model_selection.cross_validate`
            using `return_estimator=True` and `return_indices=True` (i.e., dictionary
            should contain the keys "estimator" and "indices").

        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Input values.

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

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights.

        drop_intermediate : bool, default=True
            Whether to drop some suboptimal thresholds which would not appear
            on a plotted ROC curve. This is useful in order to create lighter
            ROC curves.

        response_method : {'predict_proba', 'decision_function', 'auto'}                 default='auto'
            Specifies whether to use :term:`predict_proba` or
            :term:`decision_function` as the target response. If set to 'auto',
            :term:`predict_proba` is tried first and if it does not exist
            :term:`decision_function` is tried next.

        pos_label : int, float, bool or str, default=None
            The class considered as the positive class when computing the ROC AUC
            metrics. By default, `estimators.classes_[1]` is considered
            as the positive class.

        ax : matplotlib axes, default=None
            Axes object to plot on. If `None`, a new figure and axes is
            created.

        name : str or list of str, default=None
            Name for labeling legend entries. The number of legend entries
            is determined by `curve_kwargs`, and is not affected by `name`.
            To label each curve, provide a list of strings. To avoid labeling
            individual curves that have the same appearance, this cannot be used in
            conjunction with `curve_kwargs` being a dictionary or None. If a
            string is provided, it will be used to either label the single legend entry
            or if there are multiple legend entries, label each individual curve with
            the same name. If `None`, no name is shown in the legend.

        curve_kwargs : dict or list of dict, default=None
            Keywords arguments to be passed to matplotlib's `plot` function
            to draw individual ROC curves. If a list is provided the
            parameters are applied to the ROC curves of each CV fold
            sequentially and a legend entry is added for each curve.
            If a single dictionary is provided, the same parameters are applied
            to all ROC curves and a single legend entry for all curves is added,
            labeled with the mean ROC AUC score.

        plot_chance_level : bool, default=False
            Whether to plot the chance level.

        chance_level_kwargs : dict, default=None
            Keyword arguments to be passed to matplotlib's `plot` for rendering
            the chance level line.

        despine : bool, default=False
            Whether to remove the top and right spines from the plot.

        Returns
        -------
        display : :class:`~sklearn.metrics.RocCurveDisplay`
            The multi-fold ROC curve display.

        See Also
        --------
        roc_curve : Compute Receiver operating characteristic (ROC) curve.
            RocCurveDisplay.from_estimator : ROC Curve visualization given an
            estimator and some data.
        RocCurveDisplay.from_predictions : ROC Curve visualization given the
            probabilities of scores of a classifier.
        roc_auc_score : Compute the area under the ROC curve.

        Examples
        --------
        >>> import matplotlib.pyplot as plt
        >>> from sklearn.datasets import make_classification
        >>> from sklearn.metrics import RocCurveDisplay
        >>> from sklearn.model_selection import cross_validate
        >>> from sklearn.svm import SVC
        >>> X, y = make_classification(random_state=0)
        >>> clf = SVC(random_state=0)
        >>> cv_results = cross_validate(
        ...     clf, X, y, cv=3, return_estimator=True, return_indices=True)
        >>> RocCurveDisplay.from_cv_results(cv_results, X, y)
        <...>
        >>> plt.show()
        )rU   r   r_   indicestest)rW   r   Nre   rf   rg   ) _validate_from_cv_results_paramsrG   r   r   r   r   appendrI   )r^   
cv_resultsr`   ra   rU   rV   rW   r   r   r   r-   r.   rq   r0   
pos_label_	fpr_folds	tpr_folds	auc_foldsr_   test_indicesrY   rc   ro   sample_weight_foldr   r   r   rp   s                               r   from_cv_resultszRocCurveDisplay.from_cv_resultst  sJ   j 99' : 

 +-b"i9	'*{#Z	%:6%B(
 	&#I| $A|4F3q,/ /$	IFA !( #M<@ 
 $$0"3KCa #smGS!S!W%5	&8  
 xx%//  
 	
r   )N)__name__
__module____qualname____doc__r   r%   rI   classmethodrb   r]   r~   __classcell__)r,   s   @r   r   r      s    kd ## '( K KZ  O
 O
b  l

 l
 l
\   f
 f
r   r   )rj   numpyrD   utilsr   utils._plottingr   r   r   r   r	   r
   utils._responser   _rankingr   r   r   r[   r   r   <module>r      s1   
   #  ; %E
8 E
r   