
    0Ph                         d dl Z d dlmZ d dlm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mZmZmZ dd	lm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  G d d          Z dS )    N)chain)ceil)sparse)
mquantiles   )is_regressor)Bunch_safe_indexingcheck_arraycheck_random_state)_unique)check_matplotlib_support)_validate_style_kwargs)Paralleldelayed   )partial_dependence)_check_feature_names_get_feature_indexc                       e Zd ZdZddddddZeddddddd	d
dddddddddddddd            Zd Zd Zd Z	d Z
d Zddddddddddd
dZdS )PartialDependenceDisplaya!  Partial Dependence Plot (PDP).

    This can also display individual partial dependencies which are often
    referred to as: Individual Condition Expectation (ICE).

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

    Read more in
    :ref:`sphx_glr_auto_examples_miscellaneous_plot_partial_dependence_visualization_api.py`
    and the :ref:`User Guide <partial_dependence>`.

    .. versionadded:: 0.22

    Parameters
    ----------
    pd_results : list of Bunch
        Results of :func:`~sklearn.inspection.partial_dependence` for
        ``features``.

    features : list of (int,) or list of (int, int)
        Indices of features for a given plot. A tuple of one integer will plot
        a partial dependence curve of one feature. A tuple of two integers will
        plot a two-way partial dependence curve as a contour plot.

    feature_names : list of str
        Feature names corresponding to the indices in ``features``.

    target_idx : int

        - In a multiclass setting, specifies the class for which the PDPs
          should be computed. Note that for binary classification, the
          positive class (index 1) is always used.
        - In a multioutput setting, specifies the task for which the PDPs
          should be computed.

        Ignored in binary classification or classical regression settings.

    deciles : dict
        Deciles for feature indices in ``features``.

    kind : {'average', 'individual', 'both'} or list of such str,             default='average'
        Whether to plot the partial dependence averaged across all the samples
        in the dataset or one line per sample or both.

        - ``kind='average'`` results in the traditional PD plot;
        - ``kind='individual'`` results in the ICE plot;
        - ``kind='both'`` results in plotting both the ICE and PD on the same
          plot.

        A list of such strings can be provided to specify `kind` on a per-plot
        basis. The length of the list should be the same as the number of
        interaction requested in `features`.

        .. note::
           ICE ('individual' or 'both') is not a valid option for 2-ways
           interactions plot. As a result, an error will be raised.
           2-ways interaction plots should always be configured to
           use the 'average' kind instead.

        .. note::
           The fast ``method='recursion'`` option is only available for
           `kind='average'` and `sample_weights=None`. Computing individual
           dependencies and doing weighted averages requires using the slower
           `method='brute'`.

        .. versionadded:: 0.24
           Add `kind` parameter with `'average'`, `'individual'`, and `'both'`
           options.

        .. versionadded:: 1.1
           Add the possibility to pass a list of string specifying `kind`
           for each plot.

    subsample : float, int or None, default=1000
        Sampling for ICE curves when `kind` is 'individual' or 'both'.
        If float, should be between 0.0 and 1.0 and represent the proportion
        of the dataset to be used to plot ICE curves. If int, represents the
        maximum absolute number of samples to use.

        Note that the full dataset is still used to calculate partial
        dependence when `kind='both'`.

        .. versionadded:: 0.24

    random_state : int, RandomState instance or None, default=None
        Controls the randomness of the selected samples when subsamples is not
        `None`. See :term:`Glossary <random_state>` for details.

        .. versionadded:: 0.24

    is_categorical : list of (bool,) or list of (bool, bool), default=None
        Whether each target feature in `features` is categorical or not.
        The list should be same size as `features`. If `None`, all features
        are assumed to be continuous.

        .. versionadded:: 1.2

    Attributes
    ----------
    bounding_ax_ : matplotlib Axes or None
        If `ax` is an axes or None, the `bounding_ax_` is the axes where the
        grid of partial dependence plots are drawn. If `ax` is a list of axes
        or a numpy array of axes, `bounding_ax_` is None.

    axes_ : ndarray of matplotlib Axes
        If `ax` is an axes or None, `axes_[i, j]` is the axes on the i-th row
        and j-th column. If `ax` is a list of axes, `axes_[i]` is the i-th item
        in `ax`. Elements that are None correspond to a nonexisting axes in
        that position.

    lines_ : ndarray of matplotlib Artists
        If `ax` is an axes or None, `lines_[i, j]` is the partial dependence
        curve on the i-th row and j-th column. If `ax` is a list of axes,
        `lines_[i]` is the partial dependence curve corresponding to the i-th
        item in `ax`. Elements that are None correspond to a nonexisting axes
        or an axes that does not include a line plot.

    deciles_vlines_ : ndarray of matplotlib LineCollection
        If `ax` is an axes or None, `vlines_[i, j]` is the line collection
        representing the x axis deciles of the i-th row and j-th column. If
        `ax` is a list of axes, `vlines_[i]` corresponds to the i-th item in
        `ax`. Elements that are None correspond to a nonexisting axes or an
        axes that does not include a PDP plot.

        .. versionadded:: 0.23

    deciles_hlines_ : ndarray of matplotlib LineCollection
        If `ax` is an axes or None, `vlines_[i, j]` is the line collection
        representing the y axis deciles of the i-th row and j-th column. If
        `ax` is a list of axes, `vlines_[i]` corresponds to the i-th item in
        `ax`. Elements that are None correspond to a nonexisting axes or an
        axes that does not include a 2-way plot.

        .. versionadded:: 0.23

    contours_ : ndarray of matplotlib Artists
        If `ax` is an axes or None, `contours_[i, j]` is the partial dependence
        plot on the i-th row and j-th column. If `ax` is a list of axes,
        `contours_[i]` is the partial dependence plot corresponding to the i-th
        item in `ax`. Elements that are None correspond to a nonexisting axes
        or an axes that does not include a contour plot.

    bars_ : ndarray of matplotlib Artists
        If `ax` is an axes or None, `bars_[i, j]` is the partial dependence bar
        plot on the i-th row and j-th column (for a categorical feature).
        If `ax` is a list of axes, `bars_[i]` is the partial dependence bar
        plot corresponding to the i-th item in `ax`. Elements that are None
        correspond to a nonexisting axes or an axes that does not include a
        bar plot.

        .. versionadded:: 1.2

    heatmaps_ : ndarray of matplotlib Artists
        If `ax` is an axes or None, `heatmaps_[i, j]` is the partial dependence
        heatmap on the i-th row and j-th column (for a pair of categorical
        features) . If `ax` is a list of axes, `heatmaps_[i]` is the partial
        dependence heatmap corresponding to the i-th item in `ax`. Elements
        that are None correspond to a nonexisting axes or an axes that does not
        include a heatmap.

        .. versionadded:: 1.2

    figure_ : matplotlib Figure
        Figure containing partial dependence plots.

    See Also
    --------
    partial_dependence : Compute Partial Dependence values.
    PartialDependenceDisplay.from_estimator : Plot Partial Dependence.

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from sklearn.datasets import make_friedman1
    >>> from sklearn.ensemble import GradientBoostingRegressor
    >>> from sklearn.inspection import PartialDependenceDisplay
    >>> from sklearn.inspection import partial_dependence
    >>> X, y = make_friedman1()
    >>> clf = GradientBoostingRegressor(n_estimators=10).fit(X, y)
    >>> features, feature_names = [(0,)], [f"Features #{i}" for i in range(X.shape[1])]
    >>> deciles = {0: np.linspace(0, 1, num=5)}
    >>> pd_results = partial_dependence(
    ...     clf, X, features=0, kind="average", grid_resolution=5)
    >>> display = PartialDependenceDisplay(
    ...     [pd_results], features=features, feature_names=feature_names,
    ...     target_idx=0, deciles=deciles
    ... )
    >>> display.plot(pdp_lim={1: (-1.38, 0.66)})
    <...>
    >>> plt.show()
    averagei  N)kind	subsamplerandom_stateis_categoricalc                    || _         || _        || _        || _        || _        || _        || _        || _        |	| _        d S N	
pd_resultsfeaturesfeature_names
target_idxdecilesr   r   r   r   )
selfr    r!   r"   r#   r$   r   r   r   r   s
             k/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/inspection/_plot/partial_dependence.py__init__z!PartialDependenceDisplay.__init__   sL     % *$	"(,    autor   d   )皙?gffffff?r   F)sample_weightcategorical_featuresr"   targetresponse_methodn_colsgrid_resolutionpercentilesmethodn_jobsverboseline_kwice_lines_kw
pd_line_kw
contour_kwaxr   centeredr   r   c                &  
0 t          | j         d           ddlm} t	          d          rt          j        j                  dk    r|t          d          t          j	        j        |          }d|cxk    rt          j                  k     rn nj        |         |k    r"t          d                    |                    nd}t	          d          s+t          j                  st          d	t          
          j        d         }t#                    t%          |t&                    r|gt          |          z  n|}t          |          t          |          k    r0t          dt          |           dt          |           d          g g }}t)          ||          D ]\  }}t%          |t*          j        t&          f          r|f}	 t/          fd|D                       }n"# t0          $ r} t          d          | d} ~ ww xY wdt          j        |          cxk    rdk    sn t          d          |                    |dk    ot          j        |          dk               |                    |           t5          |          r0d t)          ||          D             }t          d|d|d          |}d |D             }!ntt          j                  j        j        dk    r5j        |k    rt          dj         d| d          fd|D             }!nCj        j        dv rfdD             00fd|D             }!nt          dj         d           |!D ];}"t          j        |"          dk    r!|"d         |"d         k    rt          d!          <t=          d" t)          ||!          D                       }#|#r7t?          fd#|#D                       }$
|$k     rt          d$|$ d%
 d           t)          |!|          D ])\  }%}t5          |%          r|dk    rt          d&          *|}t%          ||j                   sht          j        |t          '          }&|&j        t          |          k    r5t          d(                    t          |          |&j                            tC          j"        |          D ]E}'|'t                    k    r0t          d)                    t                    |'                    Ft%          |t*          j                  r|dk    rt          d*| d+          n9t%          |t*          j#                  r|dk    s|dk    rt          d,| d-           tI          ||.          
f	d/t)          ||          D                       }(|(d         })|d         dk    r|)j%        j        d         n|)j&        j        d         }*tO                    rJ|*dk    rD|t          d0          d|cxk    r|*k    s$n t          d1                    |                    |}i }+t)          ||!          D ][\  }}"t)          ||"          D ]E\  },}-|-s>|,|+vr:tQ          |,d2          }.tS          |.t          j*        d3d4d3          5          |+|,<   F\ | |(|||+||||!6	  	        }/|/+                    ||	|||||7          S )8a#1  Partial dependence (PD) and individual conditional expectation (ICE) plots.

        Partial dependence plots, individual conditional expectation plots or an
        overlay of both of them can be plotted by setting the ``kind``
        parameter. The ``len(features)`` plots are arranged in a grid with
        ``n_cols`` columns. Two-way partial dependence plots are plotted as
        contour plots. The deciles of the feature values will be shown with tick
        marks on the x-axes for one-way plots, and on both axes for two-way
        plots.

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

        .. note::

            :func:`PartialDependenceDisplay.from_estimator` does not support using the
            same axes with multiple calls. To plot the partial dependence for
            multiple estimators, please pass the axes created by the first call to the
            second call::

               >>> from sklearn.inspection import PartialDependenceDisplay
               >>> from sklearn.datasets import make_friedman1
               >>> from sklearn.linear_model import LinearRegression
               >>> from sklearn.ensemble import RandomForestRegressor
               >>> X, y = make_friedman1()
               >>> est1 = LinearRegression().fit(X, y)
               >>> est2 = RandomForestRegressor().fit(X, y)
               >>> disp1 = PartialDependenceDisplay.from_estimator(est1, X,
               ...                                                 [1, 2])
               >>> disp2 = PartialDependenceDisplay.from_estimator(est2, X, [1, 2],
               ...                                                 ax=disp1.axes_)

        .. warning::

            For :class:`~sklearn.ensemble.GradientBoostingClassifier` and
            :class:`~sklearn.ensemble.GradientBoostingRegressor`, the
            `'recursion'` method (used by default) will not account for the `init`
            predictor of the boosting process. In practice, this will produce
            the same values as `'brute'` up to a constant offset in the target
            response, provided that `init` is a constant estimator (which is the
            default). However, if `init` is not a constant estimator, the
            partial dependence values are incorrect for `'recursion'` because the
            offset will be sample-dependent. It is preferable to use the `'brute'`
            method. Note that this only applies to
            :class:`~sklearn.ensemble.GradientBoostingClassifier` and
            :class:`~sklearn.ensemble.GradientBoostingRegressor`, not to
            :class:`~sklearn.ensemble.HistGradientBoostingClassifier` and
            :class:`~sklearn.ensemble.HistGradientBoostingRegressor`.

        .. versionadded:: 1.0

        Parameters
        ----------
        estimator : BaseEstimator
            A fitted estimator object implementing :term:`predict`,
            :term:`predict_proba`, or :term:`decision_function`.
            Multioutput-multiclass classifiers are not supported.

        X : {array-like, dataframe} of shape (n_samples, n_features)
            ``X`` is used to generate a grid of values for the target
            ``features`` (where the partial dependence will be evaluated), and
            also to generate values for the complement features when the
            `method` is `'brute'`.

        features : list of {int, str, pair of int, pair of str}
            The target features for which to create the PDPs.
            If `features[i]` is an integer or a string, a one-way PDP is created;
            if `features[i]` is a tuple, a two-way PDP is created (only supported
            with `kind='average'`). Each tuple must be of size 2.
            If any entry is a string, then it must be in ``feature_names``.

        sample_weight : array-like of shape (n_samples,), default=None
            Sample weights are used to calculate weighted means when averaging the
            model output. If `None`, then samples are equally weighted. If
            `sample_weight` is not `None`, then `method` will be set to `'brute'`.
            Note that `sample_weight` is ignored for `kind='individual'`.

            .. versionadded:: 1.3

        categorical_features : array-like of shape (n_features,) or shape                 (n_categorical_features,), dtype={bool, int, str}, default=None
            Indicates the categorical features.

            - `None`: no feature will be considered categorical;
            - boolean array-like: boolean mask of shape `(n_features,)`
              indicating which features are categorical. Thus, this array has
              the same shape has `X.shape[1]`;
            - integer or string array-like: integer indices or strings
              indicating categorical features.

            .. versionadded:: 1.2

        feature_names : array-like of shape (n_features,), dtype=str, default=None
            Name of each feature; `feature_names[i]` holds the name of the feature
            with index `i`.
            By default, the name of the feature corresponds to their numerical
            index for NumPy array and their column name for pandas dataframe.

        target : int, default=None
            - In a multiclass setting, specifies the class for which the PDPs
              should be computed. Note that for binary classification, the
              positive class (index 1) is always used.
            - In a multioutput setting, specifies the task for which the PDPs
              should be computed.

            Ignored in binary classification or classical regression settings.

        response_method : {'auto', 'predict_proba', 'decision_function'},                 default='auto'
            Specifies whether to use :term:`predict_proba` or
            :term:`decision_function` as the target response. For regressors
            this parameter is ignored and the response is always the output of
            :term:`predict`. By default, :term:`predict_proba` is tried first
            and we revert to :term:`decision_function` if it doesn't exist. If
            ``method`` is `'recursion'`, the response is always the output of
            :term:`decision_function`.

        n_cols : int, default=3
            The maximum number of columns in the grid plot. Only active when `ax`
            is a single axis or `None`.

        grid_resolution : int, default=100
            The number of equally spaced points on the axes of the plots, for each
            target feature.

        percentiles : tuple of float, default=(0.05, 0.95)
            The lower and upper percentile used to create the extreme values
            for the PDP axes. Must be in [0, 1].

        method : str, default='auto'
            The method used to calculate the averaged predictions:

            - `'recursion'` is only supported for some tree-based estimators
              (namely
              :class:`~sklearn.ensemble.GradientBoostingClassifier`,
              :class:`~sklearn.ensemble.GradientBoostingRegressor`,
              :class:`~sklearn.ensemble.HistGradientBoostingClassifier`,
              :class:`~sklearn.ensemble.HistGradientBoostingRegressor`,
              :class:`~sklearn.tree.DecisionTreeRegressor`,
              :class:`~sklearn.ensemble.RandomForestRegressor`
              but is more efficient in terms of speed.
              With this method, the target response of a
              classifier is always the decision function, not the predicted
              probabilities. Since the `'recursion'` method implicitly computes
              the average of the ICEs by design, it is not compatible with ICE and
              thus `kind` must be `'average'`.

            - `'brute'` is supported for any estimator, but is more
              computationally intensive.

            - `'auto'`: the `'recursion'` is used for estimators that support it,
              and `'brute'` is used otherwise. If `sample_weight` is not `None`,
              then `'brute'` is used regardless of the estimator.

            Please see :ref:`this note <pdp_method_differences>` for
            differences between the `'brute'` and `'recursion'` method.

        n_jobs : int, default=None
            The number of CPUs to use to compute the partial dependences.
            Computation is parallelized over features specified by the `features`
            parameter.

            ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
            ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
            for more details.

        verbose : int, default=0
            Verbose output during PD computations.

        line_kw : dict, default=None
            Dict with keywords passed to the ``matplotlib.pyplot.plot`` call.
            For one-way partial dependence plots. It can be used to define common
            properties for both `ice_lines_kw` and `pdp_line_kw`.

        ice_lines_kw : dict, default=None
            Dictionary with keywords passed to the `matplotlib.pyplot.plot` call.
            For ICE lines in the one-way partial dependence plots.
            The key value pairs defined in `ice_lines_kw` takes priority over
            `line_kw`.

        pd_line_kw : dict, default=None
            Dictionary with keywords passed to the `matplotlib.pyplot.plot` call.
            For partial dependence in one-way partial dependence plots.
            The key value pairs defined in `pd_line_kw` takes priority over
            `line_kw`.

        contour_kw : dict, default=None
            Dict with keywords passed to the ``matplotlib.pyplot.contourf`` call.
            For two-way partial dependence plots.

        ax : Matplotlib axes or array-like of Matplotlib axes, default=None
            - If a single axis is passed in, it is treated as a bounding axes
              and a grid of partial dependence plots will be drawn within
              these bounds. The `n_cols` parameter controls the number of
              columns in the grid.
            - If an array-like of axes are passed in, the partial dependence
              plots will be drawn directly into these axes.
            - If `None`, a figure and a bounding axes is created and treated
              as the single axes case.

        kind : {'average', 'individual', 'both'}, default='average'
            Whether to plot the partial dependence averaged across all the samples
            in the dataset or one line per sample or both.

            - ``kind='average'`` results in the traditional PD plot;
            - ``kind='individual'`` results in the ICE plot.

            Note that the fast `method='recursion'` option is only available for
            `kind='average'` and `sample_weights=None`. Computing individual
            dependencies and doing weighted averages requires using the slower
            `method='brute'`.

        centered : bool, default=False
            If `True`, the ICE and PD lines will start at the origin of the
            y-axis. By default, no centering is done.

            .. versionadded:: 1.1

        subsample : float, int or None, default=1000
            Sampling for ICE curves when `kind` is 'individual' or 'both'.
            If `float`, should be between 0.0 and 1.0 and represent the proportion
            of the dataset to be used to plot ICE curves. If `int`, represents the
            absolute number samples to use.

            Note that the full dataset is still used to calculate averaged partial
            dependence when `kind='both'`.

        random_state : int, RandomState instance or None, default=None
            Controls the randomness of the selected samples when subsamples is not
            `None` and `kind` is either `'both'` or `'individual'`.
            See :term:`Glossary <random_state>` for details.

        Returns
        -------
        display : :class:`~sklearn.inspection.PartialDependenceDisplay`

        See Also
        --------
        partial_dependence : Compute Partial Dependence values.

        Examples
        --------
        >>> import matplotlib.pyplot as plt
        >>> from sklearn.datasets import make_friedman1
        >>> from sklearn.ensemble import GradientBoostingRegressor
        >>> from sklearn.inspection import PartialDependenceDisplay
        >>> X, y = make_friedman1()
        >>> clf = GradientBoostingRegressor(n_estimators=10).fit(X, y)
        >>> PartialDependenceDisplay.from_estimator(clf, X, [0, (0, 1)])
        <...>
        >>> plt.show()
        z.from_estimatorr   Nclasses_r   z(target must be specified for multi-classz"target not in est.classes_, got {}	__array__z	allow-nan)ensure_all_finitedtype   pWhen `kind` is provided as a list of strings, it should contain as many elements as `features`. `kind` contains $ element(s) and `features` contains  element(s).c              3   :   K   | ]}t          |           V  dS )r"   Nr   ).0fxr"   s     r&   	<genexpr>z:PartialDependenceDisplay.from_estimator.<locals>.<genexpr>6  sB        LN&rGGG     r(   zYEach entry in features must be either an int, a string, or an iterable of size at most 2.r   c                      g | ]\  }}|rd n|S r    )rH   forcing_average	kind_plots      r&   
<listcomp>z;PartialDependenceDisplay.from_estimator.<locals>.<listcomp>M  s5       .OY -;		)  r(   zICE plot cannot be rendered for 2-way feature interactions. 2-way feature interactions mandates PD plots using the 'average' kind: features=z" should be configured to use kind=z explicitly.c                 <    g | ]}t          |          d k    rdndS rA   )F)FFlen)rH   fxss     r&   rP   z;PartialDependenceDisplay.from_estimator.<locals>.<listcomp>[  s7       BECHHMM~  r(   bzeWhen `categorical_features` is a boolean array-like, the array should be of shape (n_features,). Got z elements while `X` contains z
 features.c                 F    g | ]}t          fd |D                       S )c              3   (   K   | ]}|         V  d S r   rM   )rH   rI   r-   s     r&   rJ   zEPartialDependenceDisplay.from_estimator.<locals>.<listcomp>.<genexpr>l  s)      AAr.r2AAAAAAr(   tuple)rH   rU   r-   s     r&   rP   z;PartialDependenceDisplay.from_estimator.<locals>.<listcomp>k  sC     " " "FIEAAAASAAAAA" " "r(   )iOUc                 2    g | ]}t          |           S )rF   rG   )rH   catr"   s     r&   rP   z;PartialDependenceDisplay.from_estimator.<locals>.<listcomp>p  s6     , , , 's-HHH, , ,r(   c                 F    g | ]}t          fd |D                       S )c                     g | ]}|v S rM   rM   )rH   idxcategorical_features_idxs     r&   rP   zFPartialDependenceDisplay.from_estimator.<locals>.<listcomp>.<listcomp>u  s    JJJs3"::JJJr(   rY   )rH   rU   rc   s     r&   rP   z;PartialDependenceDisplay.from_estimator.<locals>.<listcomp>t  sF     " " " JJJJcJJJKK" " "r(   zXExpected `categorical_features` to be an array-like of boolean, integer, or string. Got z	 instead.zdTwo-way partial dependence plots are not supported for pairs of continuous and categorical features.c                 @    g | ]\  }}|D ]}t          |          |S rM   )any)rH   rU   catsrI   s       r&   rP   z;PartialDependenceDisplay.from_estimator.<locals>.<listcomp>  sO       !T!  4yy	   r(   c                 h    g | ].}t          t          t          |d                               /S )rA   axis)rT   r   r
   )rH   rb   Xs     r&   rP   z;PartialDependenceDisplay.from_estimator.<locals>.<listcomp>  sH        GN1c$B$B$BCCDD  r(   zThe resolution of the computed grid is less than the minimum number of categories in the targeted categorical features. Expect the `grid_resolution` to be greater than z. Got zJIt is not possible to display individual effects for categorical features.r@   #Expected ax to have {} axes, got {}zLAll entries of features must be less than len(feature_names) = {0}, got {1}.zWhen an integer, subsample=z should be positive.z!When a floating-point, subsample=z should be in the (0, 1) range.)r4   r5   c              3   n   	K   | ]/\  }} t          t                    |
	|           V  0dS ))r,   r"   r-   r/   r3   r1   r2   r   N)r   r   )rH   rO   rU   rj   r-   	estimatorr"   r1   r3   r2   r/   r,   s      r&   rJ   z:PartialDependenceDisplay.from_estimator.<locals>.<genexpr>  sx       >
 >
 	3 (G&''++%9 / /'  >
 >
 >
 >
 >
 >
r(   z4target must be specified for multi-output regressorsz'target must be in [0, n_tasks], got {}.rh   g?      ?)probr   )r:   r0   r6   r7   r8   r9   r;   ),r   __name__matplotlib.pyplotpyplothasattrnpsizer=   
ValueErrorsearchsortedrT   formatr   issparser   objectshaper   
isinstancestrzipnumbersIntegralrZ   	TypeErrorappendre   asarrayr@   r   setminAxesr   from_iterableRealr   r   
individualr   r
   r   arangeplot)1clsrn   rj   r!   r,   r-   r"   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r   r;   r   r   pltr#   
n_featureskind_tmp_featuresice_for_two_way_pdrO   rU   er   rf   categorical_features_targeted
min_n_catsis_cataxesr[   r    	pd_resultn_tasksr$   rI   r_   X_coldisplayrc   s1    `` ``` ` ```                                   @r&   from_estimatorz'PartialDependenceDisplay.from_estimator   s	   n 	!CL!A!A!ABBB'''''' 9j)) 	bgi6H.I.IA.M.M~ !KLLL);VDDJ*>>>>s9+='>'>>>>>>%j1V;; !E!L!LV!T!TUUU <
 J ;'' 	L6?1+=+= 	LAFKKKAWQZ
,Q>>*4T3*?*?IX&&Tu::X&&RCFu::R R69(mmR R R   ,.r(!%22 	% 	%NIs# 0#677 f    RU         B  
 )))))))) B   %%i9&<&QPQAQRRR$$$$!"" 	 256H%2P2P  E . %. . 	. . .    ' IQ  NN $&:.B#C#C #).#55',
::$2/42 2 &2 2 2  " " " "MU" " " &+0OCC, , , ,3, , ,(" " " "'" " "
 !V0D0JV V V  
 '  74==A%%47d1g+=+=$C   -0 %(>%B%B  - -) -     #@   
 #Z//$H &H H .=H H H   &)%?%?  !	v;; 9	#9#9$1   >*R":":>:b///DyCMM)) 9@@Hty    $X.. 	 	AC&&&& 99?M@R@RTU9V9V   ' i!122 
	A~~ Q)QQQ    	7<00 	A~~a (	 ( ( (   >XVW=== >
 >
 >
 >
 >
 >
 >
 >
 >
 >
 >
 >
 #&eX"6"6>
 >
 >
 
 

, qM	 Qx9$$ #A&&%+A. 	
 	"" 	 w{{~ !WXXX))))')))) =DDVLL    JX~66 	S 	SICsD>> S SC Sr00*1bq999E",U3S9Q9Q"R"R"RGBKS
 #!'!%)

 

 

 ||%!!  
 
 	
s   (H
H#HH#c                     t          | j        t          j                  r| j        |k     r| j        S |S t          | j        t          j                  rt          || j        z            S |S )z,Compute the number of samples as an integer.)r}   r   r   r   r   r   )r%   	n_sampless     r&   _get_sample_countz*PartialDependenceDisplay._get_sample_count  se    dng&677 	4~	))~%55 	4	DN2333r(   c                 ^   t          | j                  }|                    |j        d         |d          }	||	ddf         }
t	          |
          D ]Y\  }}t          j        ||z  |z   | j        j                  } |j        ||	                                fi |d         | j        |<   ZdS )a  Plot the ICE lines.

        Parameters
        ----------
        preds : ndarray of shape                 (n_instances, n_grid_points)
            The predictions computed for all points of `feature_values` for a
            given feature for all samples in `X`.
        feature_values : ndarray of shape (n_grid_points,)
            The feature values for which the predictions have been computed.
        n_ice_to_plot : int
            The number of ICE lines to plot.
        ax : Matplotlib axes
            The axis on which to plot the ICE lines.
        pd_plot_idx : int
            The sequential index of the plot. It will be unraveled to find the
            matching 2D position in the grid layout.
        n_total_lines_by_plot : int
            The total number of lines expected to be plot on the axis.
        individual_line_kw : dict
            Dict with keywords passed when plotting the ICE lines.
        r   F)replaceN)
r   r   choicer|   	enumerateru   unravel_indexlines_r   ravel)r%   predsfeature_valuesn_ice_to_plotr:   pd_plot_idxn_total_lines_by_plotindividual_line_kwrngice_lines_idxice_lines_subsampledice_idxiceline_idxs                 r&   _plot_ice_linesz(PartialDependenceDisplay._plot_ice_lines  s    @ !!233

KN # 
 

  %]AAA%56%&:;; 	 	LGS'33g=t{?P H %,BG		% %/A% %%DK!!		 	r(   c                 ,   |rUt          j        || j        j                  } |j        ||fi |d         | j        |<   |                    dd           dS t          j        || j        j                  }	 |j        ||fi |d         | j        |	<   dS )a  Plot the average partial dependence.

        Parameters
        ----------
        avg_preds : ndarray of shape (n_grid_points,)
            The average predictions for all points of `feature_values` for a
            given feature for all samples in `X`.
        feature_values : ndarray of shape (n_grid_points,)
            The feature values for which the predictions have been computed.
        ax : Matplotlib axes
            The axis on which to plot the average PD.
        pd_line_idx : int
            The sequential index of the plot. It will be unraveled to find the
            matching 2D position in the grid layout.
        line_kw : dict
            Dict with keywords passed when plotting the PD plot.
        categorical : bool
            Whether feature is categorical.
        bar_kw: dict
            Dict with keywords passed when plotting the PD bars (categorical).
        r   xZ   )ri   rotationN)ru   r   bars_r|   bartick_paramsr   r   )
r%   	avg_predsr   r:   pd_line_idxr6   categoricalbar_kwbar_idxr   s
             r&   _plot_average_dependencez1PartialDependenceDisplay._plot_average_dependence?  s    >  
	&{DJ4DEEG"("&"M"Mf"M"Ma"PDJwNNbN11111'T[5FGGH$+BG% % % % 	%DK!!!r(   c           	      x   ddl m} |dv r&|                     || j                 ||||	|
|           |dv rI|dk    r|	}n|	|
z  |z   }|                     || j                                                 ||||||           |                    |j        |j                  }t          j
        |	| j        j                  }| j                            |d         d          3|                    | j        |d                  dd|d	          | j        |<   t!          d
 |                                D                       }t%          d |                                D                       }|                    ||g           |                                s&|                    | j        |d                             |	|	|z  dk    r*|                                s|                    d           n|                    g            |                    dd          r|dk    r|s|                                 dS dS dS dS )a;  Plot 1-way partial dependence: ICE and PDP.

        Parameters
        ----------
        kind : str
            The kind of partial plot to draw.
        preds : ndarray of shape                 (n_instances, n_grid_points) or None
            The predictions computed for all points of `feature_values` for a
            given feature for all samples in `X`.
        avg_preds : ndarray of shape (n_grid_points,)
            The average predictions for all points of `feature_values` for a
            given feature for all samples in `X`.
        feature_values : ndarray of shape (n_grid_points,)
            The feature values for which the predictions have been computed.
        feature_idx : int
            The index corresponding to the target feature.
        n_ice_lines : int
            The number of ICE lines to plot.
        ax : Matplotlib axes
            The axis on which to plot the ICE and PDP lines.
        n_cols : int or None
            The number of column in the axis.
        pd_plot_idx : int
            The sequential index of the plot. It will be unraveled to find the
            matching 2D position in the grid layout.
        n_lines : int
            The total number of lines expected to be plot on the axis.
        ice_lines_kw : dict
            Dict with keywords passed when plotting the ICE lines.
        pd_line_kw : dict
            Dict with keywords passed when plotting the PD plot.
        categorical : bool
            Whether feature is categorical.
        bar_kw: dict
            Dict with keywords passed when plotting the PD bars (categorical).
        pdp_lim : dict
            Global min and max average predictions, such that all plots will
            have the same scale and y limits. `pdp_lim[1]` is the global min
            and max for single partial dependence curves.
        r   
transformsr   bothr   r   r   Nr+   k	transformcolorc              3   &   K   | ]}|d          V  dS )r   NrM   rH   vals     r&   rJ   zLPartialDependenceDisplay._plot_one_way_partial_dependence.<locals>.<genexpr>  &      99c!f999999r(   c              3   &   K   | ]}|d          V  dS )rA   NrM   r   s     r&   rJ   zLPartialDependenceDisplay._plot_one_way_partial_dependence.<locals>.<genexpr>  r   r(   zPartial dependencelabelr   )
matplotlibr   r   r#   r   r   blended_transform_factory	transData	transAxesru   r   deciles_vlines_r|   r$   getvlinesr   valuesmaxset_ylim
get_xlabel
set_xlabelr"   
get_ylabel
set_ylabelset_yticklabelslegend)r%   r   r   r   r   feature_idxn_ice_linesr:   r0   r   n_linesr7   r8   r   r   pdp_limr   r   trans
vlines_idxmin_valmax_vals                         r&    _plot_one_way_partial_dependencez9PartialDependenceDisplay._plot_one_way_partial_dependencej  s|   v 	*))))))))  do&   &&&y  ))G3kA))$/*0022   44R\2<PP%k43G3MNN
<KND11=/1yy[^, 09 0 0D , 99(8(89999999(8(899999
Wg&''' }} 	>MM$,[^<===>[61Q66==?? 42333r""">>'4(( 	T\-A-A+-AIIKKKKK	 	-A-A-A-Ar(   c
           
         |r7ddl m}
 t          dd          }i ||	}|| j                 } |j        |fi |}d}|                    d          |                    d          }}t          j        |t                    }|	                                |
                                z   dz  }t          |j                  D ]r}t          j        ||j                  \  }}|||f         |k     r|n|}d	}t          |||f         |          }t          d
d
|          } |j        |||fi ||||f<   s|j        }|                    ||           |                    t          j        t+          |d                             t          j        t+          |d                             |d         |d         | j        |d                  | j        |d                             |
                    |                                d           t          j        || j        j                  }|| j        |<   dS ddlm} t          j        |d         |d                   \  }}|| j                 j        }|                    ||||dd          } t          j        || j        j                  }! |j         |||f||d         |d         d|| j        |!<   |!                    | dddd           |"                    |j#        |j$                  }"|%                                |&                                }$}#t          j        || j'        j                  }%|(                    | j)        |d                  dd|"d          | j'        |%<   t          j        || j*        j                  }&|+                    | j)        |d                  dd|"d          | j*        |&<   |,                    |#           |-                    |$           |.                                s&|/                    | j        |d                             |0                    | j        |d                             dS )a  Plot 2-way partial dependence.

        Parameters
        ----------
        avg_preds : ndarray of shape                 (n_instances, n_grid_points, n_grid_points)
            The average predictions for all points of `feature_values[0]` and
            `feature_values[1]` for some given features for all samples in `X`.
        feature_values : seq of 1d array
            A sequence of array of the feature values for which the predictions
            have been computed.
        feature_idx : tuple of int
            The indices of the target features
        ax : Matplotlib axes
            The axis on which to plot the ICE and PDP lines.
        pd_plot_idx : int
            The sequential index of the plot. It will be unraveled to find the
            matching 2D position in the grid layout.
        Z_level : ndarray of shape (8, 8)
            The Z-level used to encode the average predictions.
        contour_kw : dict
            Dict with keywords passed when plotting the contours.
        categorical : bool
            Whether features are categorical.
        heatmap_kw: dict
            Dict with keywords passed when plotting the PD heatmap
            (categorical).
        r   Nnearestviridis)interpolationcmapro   rk   g       @z.2fcenter)havar   )r:   rA   )xticksyticksxticklabelsyticklabelsxlabelylabelvertical)r   r         ?r   )levels
linewidthscolors)r   vmaxvminz%2.2f
   T)fmtr   fontsizeinliner+   r   )1rr   rs   dictr#   imshowr   ru   
empty_liker{   r   r   rangerv   r   r|   ry   textfigurecolorbarr   r   rT   r"   setpget_xticklabels	heatmaps_r   r   meshgridTcontour	contours_contourfclabelr   r   r   get_xlimget_ylimr   r   r$   deciles_hlines_hlinesset_xlimr   r   r   r   )'r%   r   r   r   r:   r   Z_levelr9   r   
heatmap_kwr   default_im_kwim_kwdataimr  cmap_mincmap_maxthresh
flat_indexrowcolr   values_format	text_datatext_kwargsfigheatmap_idxr   XXYYZCScontour_idxr   xlimylimr   
hlines_idxs'                                          r&    _plot_two_way_partial_dependencez9PartialDependenceDisplay._plot_two_way_partial_dependence  sv   P  V	>++++++ yyIIIM3}3
3ET_-D4))5))BD!#RWWS\\hH=V444Dhhjj488::-4F#DI.. M M
+J
CCS$(cNV$;$; %"4S>=AA	"h85III!(c9!L!L!L!LS#X)CLLL###FFy^A%6!7!788y^A%6!7!788*1-*1-)+a.9)+a.9     HHR''))JH???*;8LMMK*,DN;'''------[!2N14EFFFB$/*,ABAg#cRRB*;8LMMK*5"++ R[QZ+ + + +DN;' IIbgcBtILLL88r|TTE$D)+t7K7QRRJ/1yy[^, 09 0 0D , )+t7K7QRRJ/1yy[^, 09 0 0D , KKKK ==?? Bd0Q@AAAMM$,[^<=====r(   )
r:   r0   r6   r7   r8   r9   r   r  r   r;   c       
         X  4 t          d           ddlm} ddlm} t          | j        t                    r| j        gt          | j	                  z  }n| j        }| j
        d | j	        D             }n| j
        }t          |          t          | j	                  k    r5t          dt          |           dt          | j	                   d          h d	4t          4fd
|D                       rt          d4d| j                  |
s| j        }ng }t          || j                  D ]w\  }}d|d         i}|dv r"|j        }||| j        ddddf         z
  }||d<   |dv r|j        }||| j        ddf         z
  }||d<   |                    t'          d-i |           x|	i }	t          ||          D ]\  }}|d         }|dk    r|j        n|j        }|| j                                                 }|| j                                                 }||z
  }|d|z  z  }|d|z  z  }t          |          }|	                    |||f          \  }}t)          ||          }t+          ||          }||f|	|<   |i }|i }|i }|i }|i }||                                \  }}|i }ddi}t1          ||          }t          | j	                  }d |D             } t3          |           rd}!d}"ni|                     d          }#|                     t          ||#         j        d                             }!t          d |D                       r|!dz   }"n|!}"t          ||j                  r|j        st          d          |                                 || _        |j         | _!        t)          ||          }tE          tG          j$        |tK          |          z                      }$tG          j&        |$|ftN                    | _(        t3          |           r#tG          j&        |$|ftN                    | _)        n#tG          j&        |$||"ftN                    | _)        tG          j&        |$|ftN                    | _*        tG          j&        |$|ftN                    | _+        tG          j&        |$|ftN                    | _,        | j(        -                                }% ||$||.                                          }&t          t_          |          |&          D ]"\  }'}(| j!        0                    |(          |%|'<   #nTtG          j1        |tN                    }|j2        |k    r(t          d3                    ||j2                            |j4        dk    r|j5        d         }nd}d| _        |-                                d         j         | _!        || _(        t3          |           r!tG          j6        |tN                    | _)        n)tG          j&        |j5        |"fz   tN                    | _)        tG          j6        |tN                    | _*        tG          j6        |tN                    | _+        tG          j6        |tN                    | _,        d|	v rtG          j7        |	d         ddi})tG          j6        | j(        tN                    | _8        tG          j6        | j(        tN                    | _9        tu          t          | j(        -                                | j	        |||                    D ]c\  }*\  }+},}-}}d}d}|d         }.|dk    r|j        }n|dk    r|j        }n|j        }|j        }t          |.          dk    rd |d!k    rdndd"}/|dk    rd#d$d%}0i }1n|d!k    rd#d$d&d'}0d(d)d*}1ni }0i }1i |/|0}0i |/|1}1t1          |/|          }t1          t1          |0|          |          }|d+= t1          t1          |1|          |          }d,d i}2t1          |2|          }i }3t1          |3|          }| ;                    ||||.d         |,|!|+||*|"|||-d         ||	           8| <                    ||.|,|+|*|)||-d         o|-d         |	  	         e| S ).as  Plot partial dependence plots.

        Parameters
        ----------
        ax : Matplotlib axes or array-like of Matplotlib axes, default=None
            - If a single axis is passed in, it is treated as a bounding axes
                and a grid of partial dependence plots will be drawn within
                these bounds. The `n_cols` parameter controls the number of
                columns in the grid.
            - If an array-like of axes are passed in, the partial dependence
                plots will be drawn directly into these axes.
            - If `None`, a figure and a bounding axes is created and treated
                as the single axes case.

        n_cols : int, default=3
            The maximum number of columns in the grid plot. Only active when
            `ax` is a single axes or `None`.

        line_kw : dict, default=None
            Dict with keywords passed to the `matplotlib.pyplot.plot` call.
            For one-way partial dependence plots.

        ice_lines_kw : dict, default=None
            Dictionary with keywords passed to the `matplotlib.pyplot.plot` call.
            For ICE lines in the one-way partial dependence plots.
            The key value pairs defined in `ice_lines_kw` takes priority over
            `line_kw`.

            .. versionadded:: 1.0

        pd_line_kw : dict, default=None
            Dictionary with keywords passed to the `matplotlib.pyplot.plot` call.
            For partial dependence in one-way partial dependence plots.
            The key value pairs defined in `pd_line_kw` takes priority over
            `line_kw`.

            .. versionadded:: 1.0

        contour_kw : dict, default=None
            Dict with keywords passed to the `matplotlib.pyplot.contourf`
            call for two-way partial dependence plots.

        bar_kw : dict, default=None
            Dict with keywords passed to the `matplotlib.pyplot.bar`
            call for one-way categorical partial dependence plots.

            .. versionadded:: 1.2

        heatmap_kw : dict, default=None
            Dict with keywords passed to the `matplotlib.pyplot.imshow`
            call for two-way categorical partial dependence plots.

            .. versionadded:: 1.2

        pdp_lim : dict, default=None
            Global min and max average predictions, such that all plots will have the
            same scale and y limits. `pdp_lim[1]` is the global min and max for single
            partial dependence curves. `pdp_lim[2]` is the global min and max for
            two-way partial dependence curves. If `None` (default), the limit will be
            inferred from the global minimum and maximum of all predictions.

            .. versionadded:: 1.1

        centered : bool, default=False
            If `True`, the ICE and PD lines will start at the origin of the
            y-axis. By default, no centering is done.

            .. versionadded:: 1.1

        Returns
        -------
        display : :class:`~sklearn.inspection.PartialDependenceDisplay`
            Returns a :class:`~sklearn.inspection.PartialDependenceDisplay`
            object that contains the partial dependence plots.
        plot_partial_dependencer   N)GridSpecFromSubplotSpecc                 <    g | ]}t          |          d k    rdndS rR   rS   )rH   rI   s     r&   rP   z1PartialDependenceDisplay.plot.<locals>.<listcomp>  s7       ACCGGqLLn  r(   rB   rC   rD   >   r   r   r   c                     g | ]}|vS rM   rM   )rH   r   valid_kindss     r&   rP   z1PartialDependenceDisplay.plot.<locals>.<listcomp>  s    333$333r(   z*Values provided to `kind` must be one of: z+ or a list of such values. Currently, kind=grid_valuesr   r   r   r   r+   alphag      ?c                     g | ]}|d k    	S rL   rM   rH   rO   s     r&   rP   z1PartialDependenceDisplay.plot.<locals>.<listcomp>  s    HHHi9	1HHHr(   rA   Fc                     g | ]}|d k    	S )r   rM   r<  s     r&   rP   z1PartialDependenceDisplay.plot.<locals>.<listcomp>   s    >>>II'>>>r(   zUThe ax was already used in another plot function, please set ax=display.axes_ insteadrk   )subplot_specrl   r   num   C0r   )r   r   g333333?r   )r:  	linewidthztab:blue)r:  rB  r   z
tab:orangez--)r   	linestyler   r   rM   )=r   rr   rs   matplotlib.gridspecr5  r}   r   r~   rT   r!   r   rw   re   r    r   r   r#   r   r   r	   r   r   r   subplotsr   allindexr   r   axisonset_axis_offbounding_ax_r	  figure_intru   r   floatemptyr{   axes_r   r  r   r  r   get_subplotspecr  add_subplotr   rv   ry   ndimr|   r  linspacer   r  r   r   r2  )5r%   r:   r0   r6   r7   r8   r9   r   r  r   r;   r   r5  r   r   pd_results_rO   r   current_resultsr   r   pdpr   min_pdmax_pdspann_fx
old_min_pd
old_max_pd_default_contour_kwsr   is_average_plotr   r   ice_plot_idxn_rows
axes_ravelgsr[   specr  r   axir   r_   r   default_line_kwsdefault_ice_lines_kwsdefault_pd_lines_kwsdefault_bar_kwsdefault_heatmap_kwr8  s5                                                       @r&   r   zPartialDependenceDisplay.plot_  s/
   t 	!!:;;;''''''??????di%% 	I;T]!3!33DD9D& GK}  NN "0Nt99DM****4t994 4 t}%%4 4 4   8773333d33344 	B[ B B48IB B    	=/KKK(+D$/(B(B = =$	9#0)M2J"K 666%0E!E$/111a*E$FFE49OL1 333 ) 1I )Idoq$6N,O OI1:OI.""5#;#;?#;#;<<<<?G"%dK"8"8 1 1	3]+'0I'='=3>t/3355t/3355 $+%$+%6{{)0TFF;K)L)L&
JVZ00VZ00!' 0?GLJ>FJ:LLNNEArJ&o+,?LL
''
HH4HHH 	&KGG +0077L00K-8;<< K >>>>>?? &%/%b#(## 7	= 9     OO "D9DL,,FeFmm!;<<==F66"2&AAADJ?## P h'7vFFF h'@OOOXvv&6fEEEDN66"2&AAADJXvv&6fEEEDN))++J((R-?-?-A-A  B uZ00"55 ? ?4 $ 8 8 > >
1? Bf---Bw*$$ 9@@RWUU   w!||! $D88::a=/DLDJ?## L mBf=== hrx7*'<FKKK]2V<<<DNr888DJ]2V<<<DN <<k71:5155G!}TZvFFF!}TZvFFFJS
  "" K
 K
 ]	 ]	FKF#{CI IE&}5NL((!,i''%-		%-	!,>""a'' "*3v*=*=YY4$ $  ,,69,L,L)+-((&(( "%%(!+- -) ".%), ,((
 -/)+-((U+;(U?T(U%'S*:'S>R'S$01A7KK5*+@'JJL    !)3*+?II: 
 $+D//HH%'"34F
SS
55"1% F   $ 55"F%s1v
 
 
 
 r(   )rq   
__module____qualname____doc__r'   classmethodr   r   r   r   r   r2  r   rM   r(   r&   r   r      sF       C CZ - - - - -.  ! 3I
 I
 I
 I
 [I
V  / / /b) ) )Vs s sj~> ~> ~>F e e e e e e er(   r   )!r   	itertoolsr   mathr   numpyru   scipyr   scipy.stats.mstatsr   baser   utilsr	   r
   r   r   utils._encoder   utils._optional_dependenciesr   utils._plottingr   utils.parallelr   r    r   	_pd_utilsr   r   r   rM   r(   r&   <module>r|     sh                          ) ) ) ) ) )                        % $ $ $ $ $ D D D D D D 5 5 5 5 5 5 / / / / / / / / ! ! ! ! ! ! @ @ @ @ @ @ @ @i i i i i i i i i ir(   