
    -i                         S SK r S SKJr  S SKJr  S SKrS SKJr  S SK	J
r
  SSKJr  SSKJrJrJrJr  SS	KJr  SS
KJr  SSKJr  SSKJrJr  SSKJr  SSKJrJr   " S S5      r g)    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                       \ rS rSrSrSSSSS.S jr\SSSSSS	S
SSSSSSSSSSSSSSS.S j5       rS rS r	S r
S rS rSS	SSSSSSSSS.
S jrSrg)PartialDependenceDisplay   aC  Partial Dependence Plot (PDP) and Individual Conditional 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.

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

For an example on how to use this class, see the following example:
:ref:`sphx_glr_auto_examples_miscellaneous_plot_partial_dependence_visualization_api.py`.

.. 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                p    Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        Xl        g N	
pd_resultsfeaturesfeature_names
target_idxdecilesr   r   r   r   )
selfr!   r"   r#   r$   r%   r   r   r   r   s
             ^/var/www/html/venv/lib/python3.13/site-packages/sklearn/inspection/_plot/partial_dependence.py__init__!PartialDependenceDisplay.__init__   s4     % *$	"(,    autor   d   )皙?gffffff?r   F)sample_weightcategorical_featuresr#   targetresponse_methodn_colsgrid_resolutionpercentilescustom_valuesmethodn_jobsverboseline_kwice_lines_kw
pd_line_kw
contour_kwaxr   centeredr   r   c                  ^^^^^^^
^^^ [        U R                   S35        SSKJn  [	        TS5      (       a  [
        R                  " TR                  5      S:  a  Uc  [        S5      e[
        R                  " TR                  U5      nSUs=::  a  [        TR                  5      :  a  O  OTR                  U   U:w  a  [        SR                  U5      5      eOSn[	        TS5      (       d*  [        R                  " T5      (       d  [        TS	[        S
9mTR                   S   n[#        TT5      m[%        U[&        5      (       a  U/[        U5      -  OUn[        U5      [        U5      :w  a$  [        S[        U5       S[        U5       S35      e/ / nn[)        UU5       H  u  nn [%        U [*        R,                  [&        45      (       a  U 4n  [/        U4S jU  5       5      n S[
        R                  " U 5      s=::  a  S::  d  O  [        S5      eUR3                  US:g  =(       a    [
        R                  " U 5      S:  5        UR3                  U 5        M     [5        U5      (       a>  [)        UU5       V"Vs/ s H  u  n"nU"(       a  SOUPM     nn"n[        SU< SU< S35      eUnTc%  U V s/ s H  n [        U 5      S:X  a  SOSPM     n#n GO[
        R6                  " T5      mTR8                  R:                  S:X  aR  TR                  U:w  a  [        STR                   SU S35      eU V s/ s H  n [/        U4S jU  5       5      PM     n#n OTR8                  R:                  S;   aL  T V$s/ s H  n$[=        U$TS9PM     n%n$U V V&s/ s H"  n [/        U  V&s/ s H  n&U&U%;   PM
     sn&5      PM$     n#n n&O[        STR8                   S35      eU# H6  n'[
        R                  " U'5      S:X  d  M  U'S   U'S   :w  d  M-  [        S 5      e   [?        [)        UU#5       V V'V(s/ s H$  u  n n'U   H  n([5        U'5      (       d  M  U(PM     M&     sn(n'n 5      n)U)(       aO  [A        U) V&s/ s H   n&[        [C        [E        TU&SS!95      5      PM"     sn&5      n*T
U*:  a  [        S"U* S#T
 S35      e[)        U#U5       H)  u  n+n[5        U+5      (       d  M  US:w  d  M   [        S$5      e   Ub{  [%        UURF                  5      (       d`  [
        R6                  " U[        S%9n,U,R                  [        U5      :w  a.  [        S&R                  [        U5      U,R                  5      5      e[H        RJ                  " U5       H6  n-U-[        T5      :  d  M  [        S'R                  [        T5      U-5      5      e   [%        U[*        R,                  5      (       a  US::  a  [        S(U S)35      eO:[%        U[*        RL                  5      (       a  US::  d  US:  a  [        S*U S+35      e[O        XS,9" UUUUUU
UUUU4
S- j[)        UU5       5       5      n.U.S   n/US   S:X  a  U/RP                  R                   S   OU/RR                  R                   S   n0[U        T5      (       a?  U0S:  a9  Uc  [        S.5      eSUs=::  a  U0::  d  O  [        S/R                  U5      5      eUn0 n1[)        UU#5       H[  u  n n'[)        U U'5       HE  u  n(n$U$(       a  M  U(U1;  d  M  [E        TU(SS!9n2[W        U2[
        RX                  " S0S1S05      S29U1U('   MG     M]     U " U.UTUU1UUUU#S39	n3U3R[                  UU	UUUUUS49$ ! [0         a  n![        S5      U!eSn!A!ff = fs  snn"f s  sn f s  sn f s  sn$f s  sn&f s  sn&n f s  sn(n'n f s  sn&f )5a-  Partial dependence (PD) and individual conditional expectation (ICE) plots.

Partial dependence plots, individual conditional expectation plots, or an
overlay of both can be plotted by setting the `kind` parameter.
This method generates one plot for each entry in `features`. The plots
are arranged in a grid with `n_cols` columns. For one-way partial
dependence plots, the deciles of the feature values are shown on the
x-axis. For two-way plots, the deciles are shown on both axes and PDPs
are contour plots.

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

For an example on how to use this class method, see
:ref:`sphx_glr_auto_examples_inspection_plot_partial_dependence.py`.

.. 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.
    This parameter is overridden by `custom_values` if that parameter is set.

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].
    This parameter is overridden by `custom_values` if that parameter is set.

custom_values : dict
    A dictionary mapping the index of an element of `features` to an
    array of values where the partial dependence should be calculated
    for that feature. Setting a range of values for a feature overrides
    `grid_resolution` and `percentiles`.

    .. versionadded:: 1.7

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   8   >#    U  H  n[        UTS 9v   M     g7f)r#   N)r   ).0fxr#   s     r'   	<genexpr>:PartialDependenceDisplay.from_estimator.<locals>.<genexpr>H  s      RUB&rGRUs   zYEach entry in features must be either an int, a string, or an iterable of size at most 2.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.FFF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              3   .   >#    U  H
  nTU   v   M     g 7fr    )rJ   rK   r/   s     r'   rL   rM   ~  s     ASr.r2Ss   )iOUrI   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.)axiszThe 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.rC   #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.)r7   r8   c              3   d   >
#    U  H%  u  p[        [        5      " TTUTTTTT	TT
UTS 9v   M'     g7f))	r.   r#   r/   r1   r6   r3   r4   r   r5   N)r   r   )rJ   	kind_plotfxsXr/   r5   	estimatorr#   r3   r6   r4   r1   r.   s      r'   rL   rM     sM      >
 #7	 &'++%9 / /'+ #7s   -0z4target must be specified for multi-output regressorsz'target must be in [0, n_tasks], got {}.g?      ?)probr    )r=   r2   r9   r:   r;   r<   r>   ).r   __name__matplotlib.pyplotpyplothasattrnpsizer@   
ValueErrorsearchsortedlenformatr   issparser   objectshaper   
isinstancestrzipnumbersIntegraltuple	TypeErrorappendanyasarrayrC   r   r   setminr   r
   Axesr   from_iterableRealr   r   
individualr   r   arangeplot)4clsr]   r\   r"   r.   r/   r#   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r   r>   r   r   pltr$   
n_featureskind_tmp_featuresice_for_two_way_pdrZ   r[   eforcing_averager   catcategorical_features_idxidxcatsrK   categorical_features_targeted
min_n_catsis_cataxesrS   r!   	pd_resultn_tasksr%   X_coldisplays4    `` ``` ` ````                                      r'   from_estimator'PartialDependenceDisplay.from_estimator   s   P	 	!CLL>!AB' 9j))bggi6H6H.IA.M~ !KLL););VDJ*>s9+=+='>>%%j1V; !E!L!LV!TUU <
 J ;''6??1+=+=AFKAWWQZ
,Q>*4T3*?*?X&Tu:X&CCFu:, O669(m_LR  ,.r(!%2NIs# 0 0#677f RU  )) B  %%i9&<&QPQAQR$- 30 !""
 366H%2P2P.OY -	);2P    %< (y	.   'IQIQ#CHM~=  N $&::.B#C #))..#5',,
:$K/4455R%,j2  NV"MUcEASAAX  " &++00OC  4,3 's-H3 ) ,  ("' cJcs3"::cJK'  "
 !00D0J0J/K9V 
 '774=A%47d1g+=$C  ' -0 &)>%B%B	T!4y ! %B-) -  $A#@C GN1c$BCD#@
 #Z/$U &,f_,=YH  &)%?!	v;;9	#9$1  &@ >*R":":::b/DyyCM) 9@@Htyy  $$X.AC&& 99?M@RTU9V  / i!1!122A~ 1)<PQ   	7<<00A~a 7	{ C( (  V= >
 >
 #&eX"6>
 

. qM	 Qx9$ ##A&%%++A. 	
 	""w{~ !WXX)') =DDVL   JX~6ICsD>Csr0*1bq9E",U3S9Q"RGBK * 7 !'!%)

 ||%!!  
 	
E   B ( "
,
 K"(sZ   ]8^:^;^!;^&^0%^+4^0-^6
^61'^=8
^^^+^0c                    [        U R                  [        R                  5      (       a  U R                  U:  a  U R                  $ U$ [        U R                  [        R                  5      (       a  [        XR                  -  5      $ U$ )z,Compute the number of samples as an integer.)rm   r   rp   rq   r{   r   )r&   	n_sampless     r'   _get_sample_count*PartialDependenceDisplay._get_sample_count  sb    dnng&6&677~~	)~~%55	NN233r*   c                 d   [        U R                  5      nUR                  UR                  S   USS9n	XSS24   n
[	        U
5       Hf  u  p[
        R                  " XV-  U-   U R                  R                  5      nUR                  " X,R                  5       40 UD6S   U R                  U'   Mh     g)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   choicerl   	enumeraterd   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_lines(PartialDependenceDisplay._plot_ice_lines!  s    @ !!2!23

KKN # 

  %A%56%&:;LG''3g=t{{?P?PH %'GG		%/A%%DKK!	 <r*   c                 j   U(       a^  [         R                  " X@R                  R                  5      nUR                  " X!40 UD6S   U R                  U'   UR                  SSS9  g[         R                  " X@R                  R                  5      n	UR                  " UU40 UD6S   U R                  U	'   g)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   )rV   rotationN)rd   r   bars_rl   bartick_paramsr   r~   )
r&   	avg_predsr   r=   pd_line_idxr9   categoricalbar_kwbar_idxr   s
             r'   _plot_average_dependence1PartialDependenceDisplay._plot_average_dependenceR  s    > &&{JJ4D4DEG"$&&"Mf"Ma"PDJJwNNbN1''[[5F5FGH$&GG% % 	%DKK!r*   c           	      6   SSK Jn  US;   a#  U R                  X R                     UUUU	U
U5        US;   aA  US:X  a  U	nOX-  U-   nU R	                  X0R                     R                  5       UUUUUU5        UR                  UR                  UR                  5      n[        R                  " XR                  R                  5      nU R                  R                  US   S5      b0  UR                  U R                  US      SSUSS	9U R                  U'   [!        S
 UR#                  5        5       5      n[%        S UR#                  5        5       5      nUR'                  UU/5        UR)                  5       (       d!  UR+                  U R,                  US      5        Ub  X-  S:X  a'  UR/                  5       (       d  UR1                  S5        OUR3                  / 5        UR                  SS5      (       a   US:w  a  U(       d  UR5                  5         gggg)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   *   #    U  H	  oS    v   M     g7f)r   NrR   rJ   vals     r'   rL   LPartialDependenceDisplay._plot_one_way_partial_dependence.<locals>.<genexpr>       9(8!f(8   c              3   *   #    U  H	  oS    v   M     g7f)rD   NrR   r   s     r'   rL   r     r   r   zPartial dependencelabelr|   )
matplotlibr   r   r$   r   r   blended_transform_factory	transData	transAxesrd   r   deciles_vlines_rl   r%   getvlinesrx   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=   r2   r   n_linesr:   r;   r   r   pdp_limr   r   trans
vlines_idxmin_valmax_vals                         r'    _plot_one_way_partial_dependence9PartialDependenceDisplay._plot_one_way_partial_dependence}  s   v 	*))  oo& &&y ))3kA))//*002 44R\\2<<P%%k3G3G3M3MN
<<KND1=/1yy[^, 09 0D  , 9(8999(899
Wg&' }}MM$,,[^<=>[1Q6==??23r">>'4((T\-A+IIK KV-A(r*   c
           
         U(       Ga  SSK Jn
  [        SSS9n0 UEU	EnXR                     nUR                  " U40 UD6nSnUR                  S5      UR                  S5      nn[        R                  " U[        S9nUR                  5       UR                  5       -   S-  n[        UR                  5       Hn  n[        R                  " UUR                  5      u  nnUUU4   U:  a  UOUnS	n[        UUU4   U5      n[        S
S
US9nUR                   " UUU40 UD6UUU4'   Mp     UR"                  nUR%                  XS9  UR'                  [        R(                  " [+        US   5      5      [        R(                  " [+        US   5      5      US   US   U R,                  US      U R,                  US      S9  U
R/                  UR1                  5       SS9  [        R                  " XPR2                  R                  5      nXR2                  U'   gSSKJn  [        R8                  " US   US   5      u  nnXR                     R:                  nUR=                  UUUUSSS9n [        R                  " XPR>                  R                  5      n!UR@                  " UUU4UUS   US   S.UD6U R>                  U!'   URC                  U SSSSS9  URE                  URF                  URH                  5      n"URK                  5       URM                  5       n$n#[        R                  " XPRN                  R                  5      n%URQ                  U RR                  US      SSU"SS9U RN                  U%'   [        R                  " XPRT                  R                  5      n&URW                  U RR                  US      SSU"SS9U RT                  U&'   URY                  U#5        UR[                  U$5        UR]                  5       (       d!  UR_                  U R,                  US      5        URa                  U R,                  US      5        g)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cmapr^   rW   g       @z.2fcenter)havar   )r=   rD   )xticksyticksxticklabelsyticklabelsxlabelylabelvertical)r   r         ?r   )levels
linewidthscolors)r   vmaxvminz%2.2f
   T)fmtr   fontsizeinliner-   r   )1ra   rb   dictr$   imshowr   rd   
empty_likerk   r   rx   rangere   r   rl   ri   textfigurecolorbarrw   r}   rh   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_levelr<   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_dependence9PartialDependenceDisplay._plot_two_way_partial_dependence  s   P + yyIM3}3
3E__-D4)5)BD!#RWWS\hH==V4Dhhj488:-4F#DII.
++J

CS$(cNV$; %"4S>=A	"h85I!#c9!L!LS#X / ))CLLL#FFyy^A%6!78yy^A%6!78*1-*1-))+a.9))+a.9   HHR'')JH?**;8L8LMK*,NN;'-[[!2N14EFFB//*,,ABAg#cRB**;8L8LMK*,+++ R[QZ+ +DNN;' IIbgcBtIL88r||TE$D))+7K7K7Q7QRJ/1yy[^, 09 0D  , ))+7K7K7Q7QRJ/1yy[^, 09 0D  , KKKK ==??d00Q@AMM$,,[^<=r*   )
r=   r2   r9   r:   r;   r<   r   r  r   r>   c       
            [        S5        SSKJn  SSKJn  [        U R                  [        5      (       a$  U R                  /[        U R                  5      -  nOU R                  nU R                  c.  U R                   Vs/ s H  n[        U5      S:X  a  SOSPM     nnOU R                  n[        U5      [        U R                  5      :w  a.  [        S[        U5       S	[        U R                  5       S
35      e1 Skn[        U Vs/ s H  nUU;  PM
     sn5      (       a  [        SU< SU R                  < 35      eU
(       d  U R                  nO/ n[        XR                  5       H  u  nnSUS   0nUS;   a)  UR                  nUUU R                   SS2SS4   -
  nUUS'   US;   a&  UR"                  nUUU R                   SS4   -
  nUUS'   UR%                  ['        S+0 UD65        M     U	c  0 n	[        UU5       H  u  nnUS   nUS:X  a  UR"                  OUR                  nUU R                      R)                  5       nUU R                      R+                  5       nUU-
  nUSU-  -  nUSU-  -  n[        U5      nU	R-                  UUU45      u  nn[)        UU5      n[+        UU5      nUU4U	U'   M     Uc  0 nUc  0 nUc  0 nUc  0 nUc  0 nUc  UR/                  5       u  n nUc  0 nSS0n![1        U!U5      n[        U R                  5      n"U Vs/ s H  nUS:H  PM
     n#n[3        U#5      (       a  Sn$Sn%OgU#R5                  S5      n&U R7                  [        UU&   R                  S   5      5      n$[        U Vs/ s H  nUS:H  PM
     sn5      (       a  U$S-   n%OU$n%[        XR8                  5      (       Ga  UR:                  (       d  [        S5      eUR=                  5         Xl        UR@                  U l!        [)        UU"5      n[E        [F        RH                  " U"[K        U5      -  5      5      n'[F        RL                  " U'U4[N        S9U l(        [3        U#5      (       a!  [F        RL                  " U'U4[N        S9U l)        O![F        RL                  " U'UU%4[N        S9U l)        [F        RL                  " U'U4[N        S9U l*        [F        RL                  " U'U4[N        S9U l+        [F        RL                  " U'U4[N        S9U l,        U RP                  R[                  5       n(U" U'X!R]                  5       S9n)[        [_        U"5      U)5       H$  u  n*n+U RB                  Ra                  U+5      U(U*'   M&     GOT[F        Rb                  " U[N        S9nURd                  U":w  a%  [        SRg                  U"URd                  5      5      eURh                  S:X  a  URj                  S   nOSnSU l        UR[                  5       S   R@                  U l!        Xl(        [3        U#5      (       a  [F        Rl                  " U[N        S9U l)        O,[F        RL                  " URj                  U%4-   [N        S9U l)        [F        Rl                  " U[N        S9U l*        [F        Rl                  " U[N        S9U l+        [F        Rl                  " U[N        S9U l,        SU	;   a  [F        Rn                  " U	S   SS06n,[F        Rl                  " U RP                  [N        S9U l8        [F        Rl                  " U RP                  [N        S9U l9        [u        [        U RP                  R[                  5       U R                  UUU5      5       GHI  u  n-u  n.n/n0nnSnSnUS   n1US:X  a  UR                  nO+US:X  a  UR"                  nOUR"                  nUR                  n[        U15      S:X  a  SUS:X  a  SOSS .n2US:X  a  S!S"S#.n30 n4OUS:X  a  S!S"S$S%.n3S&S'S(.n4O0 n30 n40 U2EU3En30 U2EU4En4[1        U2U5      n[1        [1        U3U5      U5      nUS)	 [1        [1        U4U5      U5      nS*S0n5[1        U5U5      n0 n6[1        U6U5      nU Rw                  UUUU1S   U/U$U.UU-U%UUU0S   UU	5        GM!  U Ry                  UU1U/U.U-W,UU0S   =(       a    U0S   U5	        GML     U $ s  snf s  snf s  snf s  snf ),a
  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)GridSpecFromSubplotSpecrD   rN   rO   rE   rF   rG   >   r   r   r|   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      ?Fr   zUThe ax was already used in another plot function, please set ax=display.axes_ insteadrW   )subplot_specrX   r   num   C0)r   r   g333333?r   )r6  	linewidthztab:blue)r6  r;  r   z
tab:orangez--)r   	linestyler   r   rR   )=r   ra   rb   matplotlib.gridspecr4  rm   r   rn   rh   r"   r   rf   ru   r!   ro   r|   r$   r   rt   r	   rx   r   r   subplotsr   allindexr   ry   axisonset_axis_offbounding_ax_r  figure_intrd   r   floatemptyrk   axes_r   r  r   r  r   get_subplotspecr  add_subplotrv   re   ri   ndimrl   r  linspacer   r  r   r   r0  )7r&   r=   r2   r9   r:   r;   r<   r   r  r   r>   r   r4  r   rK   r   valid_kindsr   pd_results_rZ   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gsrS   specr  r   axir   r   r   default_line_kwsdefault_ice_lines_kwsdefault_pd_lines_kwsdefault_bar_kwsdefault_heatmap_kws7                                                          r'   r~   PartialDependenceDisplay.plotr  s   t 	!!:;'?dii%%II;T]]!33D99D&GK}}GTCGqLn<}  N "00Nt9DMM**Kt9+At}}%&l4  8d3d$d344<[O L448II=B  //KK(+D//(B$	9#0)M2J"K 66%00E!E$//1a*E$FFE49OL1 33 ) 1 1I )Idooq$6N,O OI1:OI.""5#;?#;< )C ?G"%dK"8	3]+'0I'=3>>t/335t/335 $+%$+%6{)0TFF;K)L&
JVZ0VZ0!' 0! #9$ ?GLJ>FJ:LLNEArJ&o+,?L
'
CGH4i9	14HKG +007L00K-88;<K >II'>??%/%b((## 99   OO "99DL,FeFm!;<=F66"2&ADJ?## hh'7vF hh'@OXXvv&6fEDN66"2&ADJXXvv&6fEDN))+J(-?-?-AB uZ0"54 $ 8 8 >
1 6 Bf-Bww*$ 9@@RWWU  ww!|! $D88:a=//DLJ?## mmBf= hhrxx7*'<FK]]2V<DNr8DJ]]2V<DN <kk71:515G!}}TZZvF!}}TZZvFJS

  "K
FKF#{CI IE&}5NL(!,,i'%--	%--	!,,>"a' "*3v*=Y4$  ,69,L)+-(&( "%%(!+-) ".%),(
 -/)+-((U+;(U?T(U%'S*:'S>R'S$01A7K5*+@'JL  !)3*+?I:
 $+D//H%'"34F
S
55"1% F$ 55"F%s1v
gK
~ C 4F I ?s   ccc	c)rH  r   rC  r  r%   r  r   r#   r"   rD  r  r   r   r   r!   r   r   r$   )r`   
__module____qualname____firstlineno____doc__r(   classmethodr   r   r   r   r   r0  r~   __static_attributes__rR   r*   r'   r   r      s    D\ -.  ! 5[
 [
z/b)Vsj~>F e er*   r   )!rp   	itertoolsr   mathr   numpyrd   scipyr   scipy.stats.mstatsr   baser   utilsr	   r
   r   r   utils._encoder   utils._optional_dependenciesr   utils._plottingr   utils.parallelr   r    r   	_pd_utilsr   r   r   rR   r*   r'   <module>ry     sF         )    % D 5 / ! @| |r*   