
    h$,f_;                     n    d dl ZddlmZ ddlmZ ddlmZmZ ddl	m
Z
 ddlmZmZmZ d Z G d	 d
      Zy)    N   )is_regressor)LabelEncoder)_safe_indexingcheck_matplotlib_support)_get_response_values)_is_arraylike_not_scalar_num_featurescheck_is_fittedc                    t        | d      }|r%t        | j                  d         rd}t        |      |r8t	        | j                        dkD  r |dvr|d}t        |      |dk(  rd}|S |}|S |dk(  rt        |       rd}|S g d	}|S |}|S )
a  Validate the response methods to be used with the fitted estimator.

    Parameters
    ----------
    estimator : object
        Fitted estimator to check.

    response_method : {'auto', 'predict_proba', 'decision_function', 'predict'}
        Specifies whether to use :term:`predict_proba`,
        :term:`decision_function`, :term:`predict` as the target response.
        If set to 'auto', the response method is tried in the following order:
        :term:`decision_function`, :term:`predict_proba`, :term:`predict`.

    class_of_interest : int, float, bool, str or None
        The class considered when plotting the decision. If the label is specified, it
        is then possible to plot the decision boundary in multiclass settings.

        .. versionadded:: 1.4

    Returns
    -------
    prediction_method : list of str or str
        The name or list of names of the response methods to use.
    classes_r   zFMulti-label and multi-output multi-class classifiers are not supported   >   autopredictzMulticlass classifiers are only supported when `response_method` is 'predict' or 'auto'. Else you must provide `class_of_interest` to plot the decision boundary of a specific class.r   r   )decision_functionpredict_probar   )hasattrr	   r   
ValueErrorlenr   )	estimatorresponse_methodclass_of_interesthas_classesmsgprediction_methods         Jlib/python3.12/site-packages/sklearn/inspection/_plot/decision_boundary.py_check_boundary_response_methodr      s    2 )Z0K/	0B0B10EFVos9--.2"55:K:SB 
 S/!)8F)BI  IX  
F	"	" ) 	 !R  ,    c            
       J    e Zd ZdZddddZddZedddd	ddddd
d       Zy)DecisionBoundaryDisplaya	  Decisions boundary visualization.

    It is recommended to use
    :func:`~sklearn.inspection.DecisionBoundaryDisplay.from_estimator`
    to create a :class:`DecisionBoundaryDisplay`. All parameters are stored as
    attributes.

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

    .. versionadded:: 1.1

    Parameters
    ----------
    xx0 : ndarray of shape (grid_resolution, grid_resolution)
        First output of :func:`meshgrid <numpy.meshgrid>`.

    xx1 : ndarray of shape (grid_resolution, grid_resolution)
        Second output of :func:`meshgrid <numpy.meshgrid>`.

    response : ndarray of shape (grid_resolution, grid_resolution)
        Values of the response function.

    xlabel : str, default=None
        Default label to place on x axis.

    ylabel : str, default=None
        Default label to place on y axis.

    Attributes
    ----------
    surface_ : matplotlib `QuadContourSet` or `QuadMesh`
        If `plot_method` is 'contour' or 'contourf', `surface_` is a
        :class:`QuadContourSet <matplotlib.contour.QuadContourSet>`. If
        `plot_method` is 'pcolormesh', `surface_` is a
        :class:`QuadMesh <matplotlib.collections.QuadMesh>`.

    ax_ : matplotlib Axes
        Axes with decision boundary.

    figure_ : matplotlib Figure
        Figure containing the decision boundary.

    See Also
    --------
    DecisionBoundaryDisplay.from_estimator : Plot decision boundary given an estimator.

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> from sklearn.datasets import load_iris
    >>> from sklearn.inspection import DecisionBoundaryDisplay
    >>> from sklearn.tree import DecisionTreeClassifier
    >>> iris = load_iris()
    >>> feature_1, feature_2 = np.meshgrid(
    ...     np.linspace(iris.data[:, 0].min(), iris.data[:, 0].max()),
    ...     np.linspace(iris.data[:, 1].min(), iris.data[:, 1].max())
    ... )
    >>> grid = np.vstack([feature_1.ravel(), feature_2.ravel()]).T
    >>> tree = DecisionTreeClassifier().fit(iris.data[:, :2], iris.target)
    >>> y_pred = np.reshape(tree.predict(grid), feature_1.shape)
    >>> display = DecisionBoundaryDisplay(
    ...     xx0=feature_1, xx1=feature_2, response=y_pred
    ... )
    >>> display.plot()
    <...>
    >>> display.ax_.scatter(
    ...     iris.data[:, 0], iris.data[:, 1], c=iris.target, edgecolor="black"
    ... )
    <...>
    >>> plt.show()
    N)xlabelylabelc                J    || _         || _        || _        || _        || _        y )Nxx0xx1responser!   r"   )selfr%   r&   r'   r!   r"   s         r   __init__z DecisionBoundaryDisplay.__init__   s%     r   contourfc                    t        d       ddlm} |dvrt        d      ||j	                         \  }}t        ||      } || j                  | j                  | j                  fi || _	        ||j                         s!|| j                  n|}|j                  |       ||j                         s!|| j                  n|}|j                  |       || _        |j"                  | _        | S )a  Plot visualization.

        Parameters
        ----------
        plot_method : {'contourf', 'contour', 'pcolormesh'}, default='contourf'
            Plotting method to call when plotting the response. Please refer
            to the following matplotlib documentation for details:
            :func:`contourf <matplotlib.pyplot.contourf>`,
            :func:`contour <matplotlib.pyplot.contour>`,
            :func:`pcolormesh <matplotlib.pyplot.pcolormesh>`.

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

        xlabel : str, default=None
            Overwrite the x-axis label.

        ylabel : str, default=None
            Overwrite the y-axis label.

        **kwargs : dict
            Additional keyword arguments to be passed to the `plot_method`.

        Returns
        -------
        display: :class:`~sklearn.inspection.DecisionBoundaryDisplay`
            Object that stores computed values.
        zDecisionBoundaryDisplay.plotr   Nr*   contour
pcolormeshz:plot_method must be 'contourf', 'contour', or 'pcolormesh')r   matplotlib.pyplotpyplotr   subplotsgetattrr%   r&   r'   surface_
get_xlabelr!   
set_xlabel
get_ylabelr"   
set_ylabelax_figurefigure_)	r(   plot_methodaxr!   r"   kwargsplt_	plot_funcs	            r   plotzDecisionBoundaryDisplay.plot   s    < 	!!?@'CCL  :LLNEArB,	!$((DHHdmmNvNR]]_$*NT[[FMM&!R]]_$*NT[[FMM&!yyr   d   g      ?r   )grid_resolutionepsr;   r   r   r!   r"   r<   c                   t        | j                   d       t        |       |dkD  st        d| d      |dk\  st        d| d      d}||vr#dj	                  |      }t        d	| d
| d      t        |      }|dk7  rt        d| d      t        |dd      t        |dd      }}|j                         |z
  |j                         |z   }}|j                         |z
  |j                         |z   }}t        j                  t        j                  |||      t        j                  |||            \  }}t        |d      rd|j                  g ddf   j                         }|j                         |j                  dddf<   |j                         |j                  dddf<   n1t        j                   |j                         |j                         f   }t#        |||      }	 t%        ||||d      \  }}}|dk(  r8t        |d      r,t+               }|j(                  |_        |j-                  |      }|j.                  dk7  rDt1        |      rt        d      t        j2                  |j(                  |k(        d   }|dd|f   }|t        |d      r|j4                  d   nd}|	t        |d      r|j4                  d   nd}	 | |||j7                  |j8                        ||	      } |j:                  d|
|d|S # t        $ r/}dt'        |      v rt        d| d|j(                         | d}~ww xY w)a  Plot decision boundary given an estimator.

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

        Parameters
        ----------
        estimator : object
            Trained estimator used to plot the decision boundary.

        X : {array-like, sparse matrix, dataframe} of shape (n_samples, 2)
            Input data that should be only 2-dimensional.

        grid_resolution : int, default=100
            Number of grid points to use for plotting decision boundary.
            Higher values will make the plot look nicer but be slower to
            render.

        eps : float, default=1.0
            Extends the minimum and maximum values of X for evaluating the
            response function.

        plot_method : {'contourf', 'contour', 'pcolormesh'}, default='contourf'
            Plotting method to call when plotting the response. Please refer
            to the following matplotlib documentation for details:
            :func:`contourf <matplotlib.pyplot.contourf>`,
            :func:`contour <matplotlib.pyplot.contour>`,
            :func:`pcolormesh <matplotlib.pyplot.pcolormesh>`.

        response_method : {'auto', 'predict_proba', 'decision_function',                 'predict'}, default='auto'
            Specifies whether to use :term:`predict_proba`,
            :term:`decision_function`, :term:`predict` as the target response.
            If set to 'auto', the response method is tried in the following order:
            :term:`decision_function`, :term:`predict_proba`, :term:`predict`.
            For multiclass problems, :term:`predict` is selected when
            `response_method="auto"`.

        class_of_interest : int, float, bool or str, default=None
            The class considered when plotting the decision. If None,
            `estimator.classes_[1]` is considered as the positive class
            for binary classifiers. For multiclass classifiers, passing
            an explicit value for `class_of_interest` is mandatory.

            .. versionadded:: 1.4

        xlabel : str, default=None
            The label used for the x-axis. If `None`, an attempt is made to
            extract a label from `X` if it is a dataframe, otherwise an empty
            string is used.

        ylabel : str, default=None
            The label used for the y-axis. If `None`, an attempt is made to
            extract a label from `X` if it is a dataframe, otherwise an empty
            string is used.

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

        **kwargs : dict
            Additional keyword arguments to be passed to the
            `plot_method`.

        Returns
        -------
        display : :class:`~sklearn.inspection.DecisionBoundaryDisplay`
            Object that stores the result.

        See Also
        --------
        DecisionBoundaryDisplay : Decision boundary visualization.
        sklearn.metrics.ConfusionMatrixDisplay.from_estimator : Plot the
            confusion matrix given an estimator, the data, and the label.
        sklearn.metrics.ConfusionMatrixDisplay.from_predictions : Plot the
            confusion matrix given the true and predicted labels.

        Examples
        --------
        >>> import matplotlib.pyplot as plt
        >>> from sklearn.datasets import load_iris
        >>> from sklearn.linear_model import LogisticRegression
        >>> from sklearn.inspection import DecisionBoundaryDisplay
        >>> iris = load_iris()
        >>> X = iris.data[:, :2]
        >>> classifier = LogisticRegression().fit(X, iris.target)
        >>> disp = DecisionBoundaryDisplay.from_estimator(
        ...     classifier, X, response_method="predict",
        ...     xlabel=iris.feature_names[0], ylabel=iris.feature_names[1],
        ...     alpha=0.5,
        ... )
        >>> disp.ax_.scatter(X[:, 0], X[:, 1], c=iris.target, edgecolor="k")
        <...>
        >>> plt.show()
        z.from_estimator   z,grid_resolution must be greater than 1. Got z	 instead.r   z,eps must be greater than or equal to 0. Got r,   z, zplot_method must be one of z. Got r   z#n_features must be equal to 2. Got )axisilocNT)r   	pos_labelreturn_response_method_usedzis not a valid labelzclass_of_interest=z+ is not a valid label: It should be one of r   r   z)Multi-output regressors are not supportedcolumns r$   )r<   r;    )r   __name__r   r   joinr
   r   minmaxnpmeshgridlinspacer   rH   copyravelc_r   r   strr   r   	transformndimr   flatnonzerorK   reshapeshaperA   ) clsr   XrC   rD   r;   r   r   r!   r"   r<   r=   possible_plot_methodsavailable_methodsnum_featuresx0x1x0_minx0_maxx1_minx1_maxr%   r&   X_gridr   r'   r?   response_method_usedexcencodercol_idxdisplays                                    r   from_estimatorz&DecisionBoundaryDisplay.from_estimator   st   \ 	!CLL>!AB	""#$I/ 
 ax>se9M  !F33 $		*? @-.?-@ A"m9. 
 %Q'15l^9M   11-~a/KBCCCC;;KK8KK8
S 1fVVBE]'')F #		FKK1 #		FKK1UU399;		34F;(9
	0D 1+,01-Ha-&  9,J1O"nG(11G((2H==AI& !LMM
 nnY%7%7;L%LMaPG7
+H>%,Q	%:QYYq\F>%,Q	%:QYYq\F%%cii0
 w||Er{EfEEQ  		%S1 !():(; <((1(:(:';=  		s   .L 	M*L>>M)r*   NNN)rN   
__module____qualname____doc__r)   rA   classmethodro   rM   r   r   r    r    @   sM    GR 6:$ 5n  MF MFr   r    )numpyrR   baser   preprocessingr   utilsr   r   utils._responser   utils.validationr	   r
   r   r   r    rM   r   r   <module>rz      s2       ) = 3 /dVF VFr   