
    0Ph,                        d Z ddlZddlZddlmZ ddlmZmZ ddl	m
Z
 ddlmZmZmZmZ ddlmZmZmZmZmZmZ dd	lmZmZ d
 Zd Zd Z e edg          gdgddg e e e                                eee e!dg eeddd          gedgdgddg eeddd           eeddd          gd	d          dddddddd            Z"dS )z&Permutation importance for estimators.    N   )_generate_indices)check_scoringget_scorer_names)_aggregate_score_dicts)Bunch_safe_indexingcheck_arraycheck_random_state)
HasMethodsIntegralInterval
RealNotInt
StrOptionsvalidate_params)Paralleldelayedc                 >    | | ||||          S  | |||          S )N)sample_weight )scorer	estimatorXyr   s        j/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/inspection/_permutation_importance.py_weights_scorerr      s5     viA]CCCC6)Q"""    c	           
         t          |          }||j        d         k     rWt          |d|j        d         |          }	t          ||	d          }
t          ||	d          }|t          ||	d          }n|                                }
g }t          j        |
j        d                   }t          |          D ]}|                    |           t          |
d          r,|
j
        ||f         }|
j        |_        ||
|
j        |         <   n|
||f         |
dd|f<   |                    t          || |
||                     t          |d         t                     rt#          |          }nt          j        |          }|S )z+Calculate score when `col_idx` is permuted.r   F)random_state	bootstrapn_population	n_samplesaxisNiloc)r   shaper   r	   copynparangerangeshufflehasattrr%   indexcolumnsappendr   
isinstancedictr   array)r   r   r   r   col_idxr   	n_repeatsr   max_samplesrow_indices
X_permutedscoresshuffling_idx_cols                  r   _calculate_permutation_scoresr<      s    &l33L QWQZ'%!	
 
 
 $A{;;;
1k222$*=+ANNNMVVXX
FIj.q122M9 X X]+++:v&& 	H/-"89C"(CI69Jz)'233%/w0F%GJqqq'z"ofiQVVWWWW&)T"" "'//&!!Mr   c                     | |z
  }t          t          j        |d          t          j        |d          |          S )a  Compute the importances as the decrease in score.

    Parameters
    ----------
    baseline_score : ndarray of shape (n_features,)
        The baseline score without permutation.
    permuted_score : ndarray of shape (n_features, n_repeats)
        The permuted scores for the `n` repetitions.

    Returns
    -------
    importances : :class:`~sklearn.utils.Bunch`
        Dictionary-like object, with the following attributes.
        importances_mean : ndarray, shape (n_features, )
            Mean of feature importance over `n_repeats`.
        importances_std : ndarray, shape (n_features, )
            Standard deviation over `n_repeats`.
        importances : ndarray, shape (n_features, n_repeats)
            Raw permutation importance scores.
       r#   )importances_meanimportances_stdimportances)r   r(   meanstd)baseline_scorepermuted_scorerA   s      r   _create_importances_bunchrF   U   sL    * !>1K1555{333   r   fitz
array-liker>   left)closedr   right)	r   r   r   scoringr4   n_jobsr   r   r5   T)prefer_skip_nested_validation   g      ?)rK   r4   rL   r   r   r5   c          
         	
 t          d          st          dd          t          |          }|                    t	          j        t          j                  j        dz             
t          t          j
                  st          j        d         z            n j        d         k    rt          d          t           |          t                     	 t!          |	           
fd
t#          j        d                   D                       t          	t$                    r	fd	D             S t'          	t	          j                            S )a  Permutation importance for feature evaluation [BRE]_.

    The :term:`estimator` is required to be a fitted estimator. `X` can be the
    data set used to train the estimator or a hold-out set. The permutation
    importance of a feature is calculated as follows. First, a baseline metric,
    defined by :term:`scoring`, is evaluated on a (potentially different)
    dataset defined by the `X`. Next, a feature column from the validation set
    is permuted and the metric is evaluated again. The permutation importance
    is defined to be the difference between the baseline metric and metric from
    permutating the feature column.

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

    Parameters
    ----------
    estimator : object
        An estimator that has already been :term:`fitted` and is compatible
        with :term:`scorer`.

    X : ndarray or DataFrame, shape (n_samples, n_features)
        Data on which permutation importance will be computed.

    y : array-like or None, shape (n_samples, ) or (n_samples, n_classes)
        Targets for supervised or `None` for unsupervised.

    scoring : str, callable, list, tuple, or dict, default=None
        Scorer to use.
        If `scoring` represents a single score, one can use:

        - a single string (see :ref:`scoring_parameter`);
        - a callable (see :ref:`scoring_callable`) that returns a single value.

        If `scoring` represents multiple scores, one can use:

        - a list or tuple of unique strings;
        - a callable returning a dictionary where the keys are the metric
          names and the values are the metric scores;
        - a dictionary with metric names as keys and callables a values.

        Passing multiple scores to `scoring` is more efficient than calling
        `permutation_importance` for each of the scores as it reuses
        predictions to avoid redundant computation.

        If None, the estimator's default scorer is used.

    n_repeats : int, default=5
        Number of times to permute a feature.

    n_jobs : int or None, default=None
        Number of jobs to run in parallel. The computation is done by computing
        permutation score for each columns and parallelized over the columns.
        `None` means 1 unless in a :obj:`joblib.parallel_backend` context.
        `-1` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    random_state : int, RandomState instance, default=None
        Pseudo-random number generator to control the permutations of each
        feature.
        Pass an int to get reproducible results across function calls.
        See :term:`Glossary <random_state>`.

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

        .. versionadded:: 0.24

    max_samples : int or float, default=1.0
        The number of samples to draw from X to compute feature importance
        in each repeat (without replacement).

        - If int, then draw `max_samples` samples.
        - If float, then draw `max_samples * X.shape[0]` samples.
        - If `max_samples` is equal to `1.0` or `X.shape[0]`, all samples
          will be used.

        While using this option may provide less accurate importance estimates,
        it keeps the method tractable when evaluating feature importance on
        large datasets. In combination with `n_repeats`, this allows to control
        the computational speed vs statistical accuracy trade-off of this method.

        .. versionadded:: 1.0

    Returns
    -------
    result : :class:`~sklearn.utils.Bunch` or dict of such instances
        Dictionary-like object, with the following attributes.

        importances_mean : ndarray of shape (n_features, )
            Mean of feature importance over `n_repeats`.
        importances_std : ndarray of shape (n_features, )
            Standard deviation over `n_repeats`.
        importances : ndarray of shape (n_features, n_repeats)
            Raw permutation importance scores.

        If there are multiple scoring metrics in the scoring parameter
        `result` is a dict with scorer names as keys (e.g. 'roc_auc') and
        `Bunch` objects like above as values.

    References
    ----------
    .. [BRE] :doi:`L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32,
             2001. <10.1023/A:1010933404324>`

    Examples
    --------
    >>> from sklearn.linear_model import LogisticRegression
    >>> from sklearn.inspection import permutation_importance
    >>> X = [[1, 9, 9],[1, 9, 9],[1, 9, 9],
    ...      [0, 9, 9],[0, 9, 9],[0, 9, 9]]
    >>> y = [1, 1, 1, 0, 0, 0]
    >>> clf = LogisticRegression().fit(X, y)
    >>> result = permutation_importance(clf, X, y, n_repeats=10,
    ...                                 random_state=0)
    >>> result.importances_mean
    array([0.4666..., 0.       , 0.       ])
    >>> result.importances_std
    array([0.2211..., 0.       , 0.       ])
    r%   z	allow-nanN)ensure_all_finitedtyper>   r   z max_samples must be <= n_samples)rK   )rL   c              3   b   K   | ])} t          t                    	|	  	        V  *d S )N)r   r<   )
.0r3   r   r   r5   r4   random_seedr   r   r   s
     r   	<genexpr>z)permutation_importance.<locals>.<genexpr>  si       % %  	/-..
	
 
	
% % % % % %r   c                     i | ]Pt                   t          j        fd t          j        d                   D                                 QS )c                 ,    g | ]}|                  S r   r   )rS   r3   namer8   s     r   
<listcomp>z5permutation_importance.<locals>.<dictcomp>.<listcomp>3  s"    QQQG&/$/QQQr   r>   )rF   r(   r2   r*   r&   )rS   rX   r   rD   r8   s    @r   
<dictcomp>z*permutation_importance.<locals>.<dictcomp>/  st     
 
 
  +t$QQQQQuQWQZ?P?PQQQRR 
 
 
r   )r,   r
   r   randintr(   iinfoint32maxr0   numbersr   intr&   
ValueErrorr   r   r   r*   r1   rF   r2   )r   r   r   rK   r4   rL   r   r   r5   rD   rT   r   r8   s   ``` `  ``@@@@r   permutation_importancerb   r   s   t 1f F[EEE &l33L&&rx'9'9'='ABBKk7#344 =+
233	qwqz	!	!;<<<9g666F$VY1mLLN$XV$$$ % % % % % % % % % % % QWQZ((% % %  F .$'' 
K
 
 
 
 
 
 '
 
 
 	
 )&9I9IJJJr   )#__doc__r_   numpyr(   ensemble._baggingr   metricsr   r   model_selection._validationr   utilsr   r	   r
   r   utils._param_validationr   r   r   r   r   r   utils.parallelr   r   r   r<   rF   setcallablelisttupler1   rb   r   r   r   <module>ro      sD   , ,
      1 1 1 1 1 1 5 5 5 5 5 5 5 5 @ @ @ @ @ @ J J J J J J J J J J J J                / . . . . . . .# # #3 3 3l  :  j%))*^D!Jss++--..//
 hxD@@@AT"'(&-HXq$v666HZAg666
! * #'-  : nK nK nK nK1 0nK nK nKr   