o
    Z&ilX                     @   s   d dl Z d dlZddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZmZmZmZmZ d
d ZG dd dZdS )    N   )is_regressor)LabelEncoder)_safe_indexing)check_matplotlib_support)_get_response_values)_get_adapter_from_container)_is_arraylike_not_scalar_is_pandas_df_is_polars_df_num_featurescheck_is_fittedc                 C   sT   t | d}|rt| jd rd}t||dkr&t| r d}|S g d}|S |}|S )aF  Validate the response methods to be used with the fitted estimator.

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

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

    class_of_interest : int, float, bool, str or None
        The class considered when plotting the decision. Cannot be None if
        multiclass and `response_method` is 'predict_proba' or 'decision_function'.

        .. 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predict)decision_functionpredict_probar   )hasattrr	   r   
ValueErrorr   )	estimatorresponse_methodclass_of_interestZhas_classesmsgprediction_method r   UC:\wamp64\www\opt\env\Lib\site-packages\sklearn/inspection/_plot/decision_boundary.py_check_boundary_response_method   s   
r   c                   @   sN   e Zd ZdZddddddZdddZed	d
dddddddd	ddZdS )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>`.

    For a detailed example comparing the decision boundaries of multinomial and
    one-vs-rest logistic regression, please see
    :ref:`sphx_glr_auto_examples_linear_model_plot_logistic_multinomial.py`.

    .. 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) or             (grid_resolution, grid_resolution, n_classes)
        Values of the response function.

    multiclass_colors : list of str or str, default=None
        Specifies how to color each class when plotting all classes of multiclass
        problem. Ignored for binary problems and multiclass problems when plotting a
        single prediction value per point.
        Possible inputs are:

        * list: list of Matplotlib
          `color <https://matplotlib.org/stable/users/explain/colors/colors.html#colors-def>`_
          strings, of length `n_classes`
        * str: name of :class:`matplotlib.colors.Colormap`
        * None: 'viridis' colormap is used to sample colors

        Single color colormaps will be generated from the colors in the list or
        colors taken from the colormap and passed to the `cmap` parameter of
        the `plot_method`.

        .. versionadded:: 1.7

    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` or list of such objects
        If `plot_method` is 'contour' or 'contourf', `surface_` is
        :class:`QuadContourSet <matplotlib.contour.QuadContourSet>`. If
        `plot_method` is 'pcolormesh', `surface_` is
        :class:`QuadMesh <matplotlib.collections.QuadMesh>`.

    multiclass_colors_ : array of shape (n_classes, 4)
        Colors used to plot each class in multiclass problems.
        Only defined when `color_of_interest` is None.

        .. versionadded:: 1.7

    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)multiclass_colorsxlabelylabelc                C   s(   || _ || _|| _|| _|| _|| _d S Nxx0xx1responser   r   r    )selfr#   r$   r%   r   r   r    r   r   r   __init__   s   
z DecisionBoundaryDisplay.__init__contourfc                    s  t d ddl ddlm} |dvrtd| d|du r$| \}}t||}| jjdkr>|| j	| j
| jfi || _n| jjd }	d	D ]}
|
|v rXtd
|
 d ||
= qF| jdu sdt| jtr| jdu rr|	dkrodnd}n| j}|dkr|	dkr|ddjd|	 }nB|dkr|	dkr|ddjd|	 }n.|||	}t|ds|tdd|	}n|j}nt| jtrǇ fdd| jD }ntd|| _|dkr| jjdd}|| j	| j
|fd|i|| _nC fddt|D }g | _t|D ]0\}}tjj| jdddd|f | jjdd|k d}| j|| j	| j
|fd|i| q|dus6| sE|du r>| jn|}| | |dusO|! s^|du rW| j"n|}|#| || _$|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.
        DecisionBoundaryDisplay.plotr   Nr(   contourZ
pcolormeshz@plot_method must be 'contourf', 'contour', or 'pcolormesh'. Got 	 instead.   )cmapcolors'z' is ignored in favor of 'multiclass_colors' in the multiclass case when the response method is 'decision_function' or 'predict_proba'.
   Ztab10Zgist_rainbowZtab20   r0      c                    s   g | ]} j |qS r   )r0   Zto_rgba).0colorZmplr   r   
<listcomp>   s    z0DecisionBoundaryDisplay.plot.<locals>.<listcomp>z,'multiclass_colors' must be a list or a str.r+   Zaxisc              
      s:   g | ]\}\}}}} j jd | d|||dfgqS )Z	colormap_)      ?r:   r:   r:   r:   )r0   ZLinearSegmentedColormap	from_list)r5   	class_idxrgb_r7   r   r   r8     s    )maskr/   )'r   
matplotlibZmatplotlib.pyplotpyplotr   Zsubplotsgetattrr%   ndimr#   r$   Zsurface_shapewarningswarnr   
isinstancestrZget_cmapr0   r   nplinspacelistZmulticlass_colors_Zargmax	enumeratemaarrayappendZ
get_xlabelr   Z
set_xlabelZ
get_ylabelr    Z
set_ylabelZax_ZfigureZfigure_)r&   plot_methodaxr   r    kwargsZpltr@   Z	plot_funcZn_responseskwargr/   r0   Z	class_mapZmulticlass_cmapsr<   r%   r   r7   r   plot   s   








r)   d   r:   r   )	grid_resolutionepsrR   r   r   r   r   r    rS   c       	   #   
      s  t | j d t| ddl |dkstd| d|dks(td| dd}||vr>d	|}td
| d| dt|}|dkrNtd| d|dv r|durt|drt|j	 }dkrt
|trt||kr|td| dt| dt fdd|D rtd| t
|tr| j vrtd| t|dddt|ddd}}| | | | }}| | | | }}tt|||t|||\}}tj| | f }t|st|rt|}|j|||jd}t|||}zt||||dd\}}}W n! ty1 } zdt|v r,td| d|j	 | d}~ww |dkrIt|drIt } |j	| _	|  |}|j!dkrV|j"|j# }n3t$|r_td|dur{t%|j	|kd }!|dd|!f j"|j# }n|j"g |j#|j#d  R  }|	du rt|d!r|jd nd"}	|
du rt|d!r|jd nd"}
| |||||	|
d#}"|"j&d%||d$|S )&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', 'decision_function', 'predict_proba',                 'predict'}, default='auto'
            Specifies whether to use :term:`decision_function`,
            :term:`predict_proba` or :term:`predict` as the target response.
            If set to 'auto', the response method is tried in the order as
            listed above.

            .. versionchanged:: 1.6
                For multiclass problems, 'auto' no longer defaults to 'predict'.

        class_of_interest : int, float, bool or str, default=None
            The class to be plotted when `response_method` is 'predict_proba'
            or 'decision_function'. If None, `estimator.classes_[1]` is considered
            the positive class for binary classifiers. For multiclass
            classifiers, if None, all classes will be represented in the
            decision boundary plot; the class with the highest response value
            at each point is plotted. The color of each class can be set via
            `multiclass_colors`.

            .. versionadded:: 1.4

        multiclass_colors : list of str, or str, default=None
            Specifies how to color each class when plotting multiclass
            'predict_proba' or 'decision_function' and `class_of_interest` is
            None. Ignored in all other cases.

            Possible inputs are:

            * list: list of Matplotlib
              `color <https://matplotlib.org/stable/users/explain/colors/colors.html#colors-def>`_
              strings, of length `n_classes`
            * str: name of :class:`matplotlib.colors.Colormap`
            * None: 'tab10' colormap is used to sample colors if the number of
                classes is less than or equal to 10, otherwise 'gist_rainbow'
                colormap.

            Single color colormaps will be generated from the colors in the list or
            colors taken from the colormap, and passed to the `cmap` parameter of
            the `plot_method`.

            .. versionadded:: 1.7

        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_estimatorr   Nr4   z,grid_resolution must be greater than 1. Got 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 )r   r   r   r   z[When 'multiclass_colors' is a list, it must be of the same length as 'estimator.classes_' (z), got: .c                 3   s    | ]
} j | V  qd S r!   )r0   Zis_color_like)r5   colr7   r   r   	<genexpr>  s    
z9DecisionBoundaryDisplay.from_estimator.<locals>.<genexpr>z[When 'multiclass_colors' is a list, it can only contain valid Matplotlib color names. Got: zSWhen 'multiclass_colors' is a string, it must be a valid Matplotlib colormap. Got: r9   )columnsT)r   Z	pos_labelZreturn_response_method_usedzis not a valid labelzclass_of_interest=z+ is not a valid label: It should be one of r   z)Multi-output regressors are not supportedr.   r]    r"   )rS   rR   r   )'r   __name__r   rB   r   joinr   r   lenr   rI   rM   anyrJ   rC   Z	colormapsr   minmaxrK   ZmeshgridrL   Zc_Zravelr
   r   r   Zcreate_containerr]   r   r   r   Z	transformrE   ZreshaperF   r   ZflatnonzerorV   )#clsr   XrX   rY   rR   r   r   r   r   r    rS   rT   Zpossible_plot_methodsZavailable_methodsZnum_featuresZ	n_classesZx0x1Zx0_minZx0_maxZx1_minZx1_maxr#   r$   ZX_gridadapterr   r%   r@   Zresponse_method_usedexcencoderZcol_idxdisplayr   r7   r   from_estimator(  s    	









z&DecisionBoundaryDisplay.from_estimator)r(   NNN)r_   
__module____qualname____doc__r'   rV   classmethodrl   r   r   r   r   r   ?   s     g

xr   )rG   numpyrK   baser   Zpreprocessingr   utilsr   Zutils._optional_dependenciesr   Zutils._responser   Zutils._set_outputr   Zutils.validationr	   r
   r   r   r   r   r   r   r   r   r   <module>   s   	(