
    0Ph}                       d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddlm
Z
 ddlmZ ddlZddlmZ ddlmZ d	d
lmZmZ d	dlmZmZ d	dlmZ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'm(Z( d	dl)m*Z*m+Z+m,Z,m-Z-m.Z. d	dl/m0Z0m1Z1m2Z2m3Z3 d	dl4m5Z5 d	dl6m7Z7m8Z8 d	dl9m:Z:m;Z; ddl<m=Z= g dZ>d Z?d Z@ e. e*d          gddgddgddg e- eA e                                eBeCeDeEdgdge+dgdgeEdge+eFgd gd gd g e-d!h          e
gd"d#$          	 d_ddddddd%d#d#d#ejG        d&d'            ZHd( ZId`d*ZJd+ ZK e. e*d          gddgddgddg e- eA e                                eBdgdge+dgdgeEdge+eFdg e-d!h          e
gd,d#$          	 d_ddddddd%ejG        d-d.            ZLd#d#d#d#d#ddejG        d/d0ZMdad1ZN e. e*dd2g          gddgg d3ddgdge+dgdgeEdge+eFdg e-h d4          gd5
d#$          	 d_dddddd%d2d6d7            ZOd8 ZPd9 ZQd: ZR e. e*d          gddgddgddgdg e,e+ddd;<          ge+dgd=gdg e- eA e                                eBdgeEdgeEdgd>d#$          ddd?ddddddd@	dA            ZSdB ZTdC ZU e.i dD e*dg          gdEddgdFddgdGddgdHdgdIdgdJ e- eA e                                eBdgdKd gdLe+dgdMe+eFgddgdNd gd=d=gdO e-d!h          e
gdPd gdQeEdgdReEdgd#$          d ejV        dSdTdU          ddd#ddVdd#dejG        d#dddWdX            ZWdY ZXdZ ZY e. e*dg          gddgddgeFgdgddgdg e- eA e                                eBdge+dge+eFgdg e-d!h          e
geEdgeEdgd[d#$          dddddVdejG        ddd\	d]            ZZd^ Z[dS )bzm
The :mod:`sklearn.model_selection._validation` module includes classes and
functions to validate the model.
    N)Counter)suppress)partial)Real)
format_exc)logger   )cloneis_classifier)FitFailedWarningUnsetMetadataPassedError)check_scoringget_scorer_names)_MultimetricScorer)LabelEncoder)Bunch_safe_indexingcheck_random_state	indexable)deviceget_namespace)
HasMethodsIntegralInterval
StrOptionsvalidate_params)MetadataRouterMethodMapping_routing_enabledprocess_routing)_safe_split)Paralleldelayed)_check_method_params_num_samples   )check_cv)cross_validatecross_val_scorecross_val_predictpermutation_test_scorelearning_curvevalidation_curvec                     || t          d| d          | t          j        dt                     | }|i n|}t	          |           |S )zA helper function to check deprecations on `groups` and `fit_params`.

    # TODO(SLEP6): To be removed when set_config(enable_metadata_routing=False) is not
    # possible.
    Nz`params` and `fit_params` cannot both be provided. Pass parameters via `params`. `fit_params` is deprecated and will be removed in version .zj`fit_params` is deprecated and will be removed in version {version}. Pass parameters via `params` instead.)
ValueErrorwarningswarnFutureWarning_check_groups_routing_disabled)
fit_paramsparamsgroupsversions       c/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/model_selection/_validation.py _check_params_groups_deprecationr:   :   s     j4"" " "
 
 	

 
	8 	
 	
 	
 >RRvF"6***M    c                 H    | t                      rt          d          d S d S )Nz`groups` can only be passed if metadata routing is not enabled via `sklearn.set_config(enable_metadata_routing=True)`. When routing is enabled, pass `groups` alongside other metadata via the `params` argument instead.)r   r0   )r7   s    r9   r4   r4   Y   s9    .00
 
 	
 r;   fit
array-likesparse matrix	cv_objectverbosebooleanraise)	estimatorXyr7   scoringcvn_jobsrA   r6   pre_dispatchreturn_train_scorereturn_estimatorreturn_indiceserror_scoreF)prefer_skip_nested_validationz2*n_jobs)r7   rG   rH   rI   rA   r6   rJ   rK   rL   rM   rN   c                $   
 t          |           t                    \  |i n|}t          |t                               }t	           |dk              t                      rt          d                              |t                                          dd	          
                               t                                          dd	                                        t                                          dd	                    }	 t          |dfi |n# t          $ rH}t          |j                  }t          | d j        j         d| d|j        |j                  d}~ww xY wt!                      t!          d|i          _        t!          |          _        t!          i           _         |j        fi j        j        }|rt+          |          }t-          ||	          } | 
f	d|D                       }t/          |           t1          |          rt3          |           t5          |          }i }|d         |d<   |d         |d<   r|d         |d<   |r#i |d<   t7          | \  |d         d<   |d         d<   t9          |d                   }
rt9          |d                   }|D ]"}||         |d |z  <   
rd!|z  }||         ||<   #|S )"a2!  Evaluate metric(s) by cross-validation and also record fit/score times.

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

    Parameters
    ----------
    estimator : estimator object implementing 'fit'
        The object to use to fit the data.

    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        The data to fit. Can be for example a list, or an array.

    y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None
        The target variable to try to predict in the case of
        supervised learning.

    groups : array-like of shape (n_samples,), default=None
        Group labels for the samples used while splitting the dataset into
        train/test set. Only used in conjunction with a "Group" :term:`cv`
        instance (e.g., :class:`GroupKFold`).

        .. versionchanged:: 1.4
            ``groups`` can only be passed if metadata routing is not enabled
            via ``sklearn.set_config(enable_metadata_routing=True)``. When routing
            is enabled, pass ``groups`` alongside other metadata via the ``params``
            argument instead. E.g.:
            ``cross_validate(..., params={'groups': groups})``.

    scoring : str, callable, list, tuple, or dict, default=None
        Strategy to evaluate the performance of the cross-validated model on
        the test set. If `None`, the
        :ref:`default evaluation criterion <scoring_api_overview>` of the estimator
        is used.

        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.

        See :ref:`multimetric_grid_search` for an example.

    cv : int, cross-validation generator or an iterable, default=None
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - None, to use the default 5-fold cross validation,
        - int, to specify the number of folds in a `(Stratified)KFold`,
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For int/None inputs, if the estimator is a classifier and ``y`` is
        either binary or multiclass, :class:`StratifiedKFold` is used. In all
        other cases, :class:`KFold` is used. These splitters are instantiated
        with `shuffle=False` so the splits will be the same across calls.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. versionchanged:: 0.22
            ``cv`` default value if None changed from 3-fold to 5-fold.

    n_jobs : int, default=None
        Number of jobs to run in parallel. Training the estimator and computing
        the score are parallelized over the cross-validation splits.
        ``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
        The verbosity level.

    params : dict, default=None
        Parameters to pass to the underlying estimator's ``fit``, the scorer,
        and the CV splitter.

        .. versionadded:: 1.4

    pre_dispatch : int or str, default='2*n_jobs'
        Controls the number of jobs that get dispatched during parallel
        execution. Reducing this number can be useful to avoid an
        explosion of memory consumption when more jobs get dispatched
        than CPUs can process. This parameter can be:

        - An int, giving the exact number of total jobs that are spawned
        - A str, giving an expression as a function of n_jobs, as in '2*n_jobs'

    return_train_score : bool, default=False
        Whether to include train scores.
        Computing training scores is used to get insights on how different
        parameter settings impact the overfitting/underfitting trade-off.
        However computing the scores on the training set can be computationally
        expensive and is not strictly required to select the parameters that
        yield the best generalization performance.

        .. versionadded:: 0.19

        .. versionchanged:: 0.21
            Default value was changed from ``True`` to ``False``

    return_estimator : bool, default=False
        Whether to return the estimators fitted on each split.

        .. versionadded:: 0.20

    return_indices : bool, default=False
        Whether to return the train-test indices selected for each split.

        .. versionadded:: 1.3

    error_score : 'raise' or numeric, default=np.nan
        Value to assign to the score if an error occurs in estimator fitting.
        If set to 'raise', the error is raised.
        If a numeric value is given, FitFailedWarning is raised.

        .. versionadded:: 0.20

    Returns
    -------
    scores : dict of float arrays of shape (n_splits,)
        Array of scores of the estimator for each run of the cross validation.

        A dict of arrays containing the score/time arrays for each scorer is
        returned. The possible keys for this ``dict`` are:

        ``test_score``
            The score array for test scores on each cv split.
            Suffix ``_score`` in ``test_score`` changes to a specific
            metric like ``test_r2`` or ``test_auc`` if there are
            multiple scoring metrics in the scoring parameter.
        ``train_score``
            The score array for train scores on each cv split.
            Suffix ``_score`` in ``train_score`` changes to a specific
            metric like ``train_r2`` or ``train_auc`` if there are
            multiple scoring metrics in the scoring parameter.
            This is available only if ``return_train_score`` parameter
            is ``True``.
        ``fit_time``
            The time for fitting the estimator on the train
            set for each cv split.
        ``score_time``
            The time for scoring the estimator on the test set for each
            cv split. (Note time for scoring on the train set is not
            included even if ``return_train_score`` is set to ``True``
        ``estimator``
            The estimator objects for each cv split.
            This is available only if ``return_estimator`` parameter
            is set to ``True``.
        ``indices``
            The train/test positional indices for each cv split. A dictionary
            is returned where the keys are either `"train"` or `"test"`
            and the associated values are a list of integer-dtyped NumPy
            arrays with the indices. Available only if `return_indices=True`.

    See Also
    --------
    cross_val_score : Run cross-validation for single metric evaluation.

    cross_val_predict : Get predictions from each split of cross-validation for
        diagnostic purposes.

    sklearn.metrics.make_scorer : Make a scorer from a performance metric or
        loss function.

    Examples
    --------
    >>> from sklearn import datasets, linear_model
    >>> from sklearn.model_selection import cross_validate
    >>> from sklearn.metrics import make_scorer
    >>> from sklearn.metrics import confusion_matrix
    >>> from sklearn.svm import LinearSVC
    >>> diabetes = datasets.load_diabetes()
    >>> X = diabetes.data[:150]
    >>> y = diabetes.target[:150]
    >>> lasso = linear_model.Lasso()

    Single metric evaluation using ``cross_validate``

    >>> cv_results = cross_validate(lasso, X, y, cv=3)
    >>> sorted(cv_results.keys())
    ['fit_time', 'score_time', 'test_score']
    >>> cv_results['test_score']
    array([0.3315057 , 0.08022103, 0.03531816])

    Multiple metric evaluation using ``cross_validate``
    (please refer the ``scoring`` parameter doc for more information)

    >>> scores = cross_validate(lasso, X, y, cv=3,
    ...                         scoring=('r2', 'neg_mean_squared_error'),
    ...                         return_train_score=True)
    >>> print(scores['test_neg_mean_squared_error'])
    [-3635.5... -3573.3... -6114.7...]
    >>> print(scores['train_r2'])
    [0.28009951 0.3908844  0.22784907]
    N
classifierrC   )rG   	raise_excr(   ownerr=   splitcallercalleesplittermethod_mappingrD   r\   scorescorerr\   zy are passed to cross validation but are not explicitly set as requested or not requested for cross_validate's estimator: S. Call `.set_fit_request({{metadata}}=True)` on the estimator for each metadata in  that you want to use and `metadata=False` for not using it. See the Metadata Routing User guide <https://scikit-learn.org/stable/metadata_routing.html> for more information.messageunrequested_paramsrouted_paramsr7   rV   r=   r^   rI   rA   rJ   c              3      	K   | ]S\  }} t          t                    t                    	||
d j        j        j        j        d          V  Td S )NT)r`   traintestrA   
parametersr5   score_paramsrK   return_timesrL   rN   r#   _fit_and_scorer
   rD   r=   r`   r^   ).0rl   rm   rE   rN   rD   rL   rK   rf   scorersrA   rF   s      r9   	<genexpr>z!cross_validate.<locals>.<genexpr>  s        " E4! 	 )$.2&-31-#	
 	
 	
     r;   fit_time
score_timerD   indicesrl   rm   test_scorestrain_scoresztest_%sztrain_%s)r4   r   r'   r   r   r   r   addr   r    r   sortedre   	__class____name__rf   r   r[   rD   r`   rV   listr"   !_warn_or_raise_about_fit_failurescallable_insert_error_scores_aggregate_score_dictszip_normalize_score_results)rD   rE   rF   r7   rG   rH   rI   rA   r6   rJ   rK   rL   rM   rN   routerere   rx   parallelresultsrettest_scores_dicttrain_scores_dictnamekeyrf   rt   s   ```    `  `` `           @@r9   r(   r(   c   s   h #6***Q??DAq>RRvF	"aM)$<$<	=	=	=B7{g/E  G  0/
 !1222S,22%2PP    S#  -22%2NN	    S,22%2PP    	"	+FEDDVDDMM' 	 	 	
 "((<!=!=*) $ $#,#6#?$ $ *<	$ $ $ $%#7o   	, !&h-?!@!@!@"'F"3"3"3$2bhq!<<}5;<<G  w-- vw\RRRHh            " ##    G( &g{;;;
  3Wk222$W--G
Cj)C
O-C 0";/K HI:=w-7IwY!7/0FGG N4W^5LMM  / / 0 6I 	/t#C(.CHJs   )D8 8
F
AFF
c                 f   d}g }t          |           D ]-\  }}|d         |                    |           #||d         }.t          |t                    rWfd|D             }|D ]H}|                                | |         d<   d| |         v r|                                | |         d<   GdS dS )zInsert error in `results` by replacing them inplace with `error_score`.

    This only applies to multimetric scores because `_fit_and_score` will
    handle the single metric case.
    N	fit_errorry   c                     i | ]}|S  r   rs   r   rN   s     r9   
<dictcomp>z(_insert_error_scores.<locals>.<dictcomp>  s    JJJ4JJJr;   rz   )	enumerateappend
isinstancedictcopy)r   rN   successful_scorefailed_indicesiresultformatted_errors    `     r9   r   r     s     Nw'' 5 5	6+*!!!$$$$%%m4"D)) DJJJJ9IJJJ 	D 	DA(7(<(<(>(>GAJ}%++-<-A-A-C-C
>*D D	D 	Dr;   r^   c                 ^    t          | d         t                    rt          |           S || iS )z:Creates a scoring dictionary based on the type of `scores`r   )r   r   r   )scoresscaler_score_keys     r9   r   r     s1    &)T"" .%f---f%%r;   c                 v  	 d | D             }|rt          |          }t          |           }t          |          }d	d                    	fd|                                D                       }||k    rd| d| }t	          |          d| d| d| d	| }t          j        |t                     d S d S )
Nc                 .    g | ]}|d          
|d          S )r   r   )rs   r   s     r9   
<listcomp>z5_warn_or_raise_about_fit_failures.<locals>.<listcomp>  s.        &VK5H5T{5T5T5Tr;   zQ--------------------------------------------------------------------------------

c              3   0   K   | ]\  }} | d | V  dS )z' fits failed with the following error:
Nr   )rs   errorn	delimiters      r9   ru   z4_warn_or_raise_about_fit_failures.<locals>.<genexpr>  sN       '
 '
q L!LLULL'
 '
 '
 '
 '
 '
r;   z	
All the z fits failed.
It is very likely that your model is misconfigured.
You can try to debug the error by setting error_score='raise'.

Below are more details about the failures:
z fits failed out of a total of zO.
The score on these train-test partitions for these parameters will be set to z.
If these failures are not expected, you can try to debug them by setting error_score='raise'.

Below are more details about the failures:
)lenr   joinitemsr0   r1   r2   r   )
r   rN   
fit_errorsnum_failed_fitsnum_fitsfit_errors_counterfit_errors_summaryall_fits_failed_messagesome_fits_failed_messager   s
            @r9   r   r     sV    *1  J  Fj//w<<$Z00#	!YY '
 '
 '
 '
.4466'
 '
 '
 
 

 h&&TX T T @RT T $ 4555T_ T TX T T#.T T
 @RT T % M24DEEEEE9F Fr;   rD   rE   rF   r7   rG   rH   rI   rA   r6   rJ   rN   )r7   rG   rH   rI   rA   r6   rJ   rN   c                l    t          | |          }t          | |||d|i|||||	|
          }|d         S )ad  Evaluate a score by cross-validation.

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

    Parameters
    ----------
    estimator : estimator object implementing 'fit'
        The object to use to fit the data.

    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        The data to fit. Can be for example a list, or an array.

    y : array-like of shape (n_samples,) or (n_samples, n_outputs),             default=None
        The target variable to try to predict in the case of
        supervised learning.

    groups : array-like of shape (n_samples,), default=None
        Group labels for the samples used while splitting the dataset into
        train/test set. Only used in conjunction with a "Group" :term:`cv`
        instance (e.g., :class:`GroupKFold`).

        .. versionchanged:: 1.4
            ``groups`` can only be passed if metadata routing is not enabled
            via ``sklearn.set_config(enable_metadata_routing=True)``. When routing
            is enabled, pass ``groups`` alongside other metadata via the ``params``
            argument instead. E.g.:
            ``cross_val_score(..., params={'groups': groups})``.

    scoring : str or callable, default=None
        A str (see :ref:`scoring_parameter`) or a scorer callable object / function with
        signature ``scorer(estimator, X, y)`` which should return only a single value.

        Similar to :func:`cross_validate`
        but only a single metric is permitted.

        If `None`, the estimator's default scorer (if available) is used.

    cv : int, cross-validation generator or an iterable, default=None
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - `None`, to use the default 5-fold cross validation,
        - int, to specify the number of folds in a `(Stratified)KFold`,
        - :term:`CV splitter`,
        - An iterable that generates (train, test) splits as arrays of indices.

        For `int`/`None` inputs, if the estimator is a classifier and `y` is
        either binary or multiclass, :class:`StratifiedKFold` is used. In all
        other cases, :class:`KFold` is used. These splitters are instantiated
        with `shuffle=False` so the splits will be the same across calls.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. versionchanged:: 0.22
            `cv` default value if `None` changed from 3-fold to 5-fold.

    n_jobs : int, default=None
        Number of jobs to run in parallel. Training the estimator and computing
        the score are parallelized over the cross-validation splits.
        ``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
        The verbosity level.

    params : dict, default=None
        Parameters to pass to the underlying estimator's ``fit``, the scorer,
        and the CV splitter.

        .. versionadded:: 1.4

    pre_dispatch : int or str, default='2*n_jobs'
        Controls the number of jobs that get dispatched during parallel
        execution. Reducing this number can be useful to avoid an
        explosion of memory consumption when more jobs get dispatched
        than CPUs can process. This parameter can be:

        - ``None``, in which case all the jobs are immediately created and spawned. Use
          this for lightweight and fast-running jobs, to avoid delays due to on-demand
          spawning of the jobs
        - An int, giving the exact number of total jobs that are spawned
        - A str, giving an expression as a function of n_jobs, as in '2*n_jobs'

    error_score : 'raise' or numeric, default=np.nan
        Value to assign to the score if an error occurs in estimator fitting.
        If set to 'raise', the error is raised.
        If a numeric value is given, FitFailedWarning is raised.

        .. versionadded:: 0.20

    Returns
    -------
    scores : ndarray of float of shape=(len(list(cv)),)
        Array of scores of the estimator for each run of the cross validation.

    See Also
    --------
    cross_validate : To run cross-validation on multiple metrics and also to
        return train scores, fit times and score times.

    cross_val_predict : Get predictions from each split of cross-validation for
        diagnostic purposes.

    sklearn.metrics.make_scorer : Make a scorer from a performance metric or
        loss function.

    Examples
    --------
    >>> from sklearn import datasets, linear_model
    >>> from sklearn.model_selection import cross_val_score
    >>> diabetes = datasets.load_diabetes()
    >>> X = diabetes.data[:150]
    >>> y = diabetes.target[:150]
    >>> lasso = linear_model.Lasso()
    >>> print(cross_val_score(lasso, X, y, cv=3))
    [0.3315057  0.08022103 0.03531816]
    rG   r^   r   
test_score)r   r(   )rD   rE   rF   r7   rG   rH   rI   rA   r6   rJ   rN   r`   
cv_resultss                r9   r)   r)     s^    n 9g666F

&!!  J l##r;   )rK   return_parametersreturn_n_test_samplesrp   rL   split_progresscandidate_progressrN   c                ,   t          |          \  }}t          |          }|                    ||          |                    ||          }}t          t          j                  sdk    rt          d          d}|dk    r;|d|d         d	z    d
|d	          }|r |dk    r|d|d         d	z    d
|d	          z  }|d	k    r5d}n0t                    }d                    fd|D                       }|dk    r.d| d| }t          | dt          |          z
  dz              ||ni }t          |||          }|	|	ni }	t          ||	|          }t          ||	|          } | j        d+i t          d          } t          j                    }t          | |||          \  }}t          | ||||          \  }}i } 	 | | j        |fi | n | j        ||fi | d| d<   t          j                    |z
  }!t#          | ||||          }"t          j                    |z
  |!z
  }#|
rt#          | ||||          }$n# t$          $ r t          j                    |z
  }!d}#dk    r t          t          j                  rEt          |t&                    r*fd|j        D             }"|
r|"                                }$n}"|
r}$t-                      | d<   Y nw xY w|d	k    r|#|!z   }%d| d}&||rdndz   }'|dk    rrt          |"t.                    r@t          |"          D ]/}(|'d|( dz  }'|
r|$|(         })|'d|)ddz  }'|'d|"|(         ddz  }'0n|'d z  }'|
r|'d!|$dd"|"ddz  }'n|'|"dz  }'|'d#t1          j        |%           z  }'|&ddt          |&          z
  t          |'          z
  z  z  }&|&|'z  }&t          |&           |"| d$<   |
r|$| d%<   |rt5          |          | d&<   |r
|!| d'<   |#| d(<   |r| d)<   |r| | d*<   | S ),aW  Fit estimator and compute scores for a given dataset split.

    Parameters
    ----------
    estimator : estimator object implementing 'fit'
        The object to use to fit the data.

    X : array-like of shape (n_samples, n_features)
        The data to fit.

    y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
        The target variable to try to predict in the case of
        supervised learning.

    scorer : A single callable or dict mapping scorer name to the callable
        If it is a single callable, the return value for ``train_scores`` and
        ``test_scores`` is a single float.

        For a dict, it should be one mapping the scorer name to the scorer
        callable object / function.

        The callable object / fn should have signature
        ``scorer(estimator, X, y)``.

    train : array-like of shape (n_train_samples,)
        Indices of training samples.

    test : array-like of shape (n_test_samples,)
        Indices of test samples.

    verbose : int
        The verbosity level.

    error_score : 'raise' or numeric, default=np.nan
        Value to assign to the score if an error occurs in estimator fitting.
        If set to 'raise', the error is raised.
        If a numeric value is given, FitFailedWarning is raised.

    parameters : dict or None
        Parameters to be set on the estimator.

    fit_params : dict or None
        Parameters that will be passed to ``estimator.fit``.

    score_params : dict or None
        Parameters that will be passed to the scorer.

    return_train_score : bool, default=False
        Compute and return score on training set.

    return_parameters : bool, default=False
        Return parameters that has been used for the estimator.

    split_progress : {list, tuple} of int, default=None
        A list or tuple of format (<current_split_id>, <total_num_of_splits>).

    candidate_progress : {list, tuple} of int, default=None
        A list or tuple of format
        (<current_candidate_id>, <total_number_of_candidates>).

    return_n_test_samples : bool, default=False
        Whether to return the ``n_test_samples``.

    return_times : bool, default=False
        Whether to return the fit/score times.

    return_estimator : bool, default=False
        Whether to return the fitted estimator.

    Returns
    -------
    result : dict with the following attributes
        train_scores : dict of scorer name -> float
            Score on training set (for all the scorers),
            returned only if `return_train_score` is `True`.
        test_scores : dict of scorer name -> float
            Score on testing set (for all the scorers).
        n_test_samples : int
            Number of test samples.
        fit_time : float
            Time spent for fitting in seconds.
        score_time : float
            Time spent for scoring in seconds.
        parameters : dict or None
            The parameters that have been evaluated.
        estimator : estimator object
            The fitted estimator.
        fit_error : str or None
            Traceback str if the fit failed, None if the fit succeeded.
    )r   rC   zerror_score must be the string 'raise' or a numeric value. (Hint: if using 'raise', please make sure that it has been spelled correctly.) r	   N r   r&   /	   z; z, c              3   2   K   | ]}| d |          V  dS )=Nr   )rs   krn   s     r9   ru   z!_fit_and_score.<locals>.<genexpr>E  s5      "O"Oaa#9#9*Q-#9#9"O"O"O"O"O"Or;   z[CVz] START P   r/   r6   rx   F)safer           c                     i | ]}|S r   r   r   s     r9   r   z"_fit_and_score.<locals>.<dictcomp>l  s    MMMTt[MMMr;   z] END ;z: (ztrain=z.3fztest=)z, score=z(train=z, test=z total time=ry   rz   n_test_samplesrv   rw   rn   rD   r   )r   r   asarrayr   numbersNumberr0   r|   r   printr   r$   
set_paramsr
   timer!   r=   _score	Exceptionr   _scorersr   r   r   r   short_format_timer%   )*rD   rE   rF   r`   rl   rm   rA   rn   r5   ro   rK   r   r   rp   rL   r   r   rN   xp_X_deviceprogress_msg
params_msgsorted_keys	start_msgscore_params_trainscore_params_test
start_timeX_trainy_trainX_testy_testr   rv   ry   rw   rz   
total_timeend_msg
result_msgscorer_namescorer_scoress*          `         `                        r9   rr   rr     s   ^ !EBayyH **U8*44bjjhj6W6W4Ek7>22 
{g7M7M"
 
 	
 L{{%H~a02HH^A5FHHL 	S'A++R!3A!6q!8RR;Ma;PRRRL{{JJ ,,K"O"O"O"O;"O"O"OOOJ{{<,<<
<<	9R#i..0C799:::  *52J%a
EJJJJ#/#;<<L-aeTTT,Q|TRRR
 )I(II5%+H+H+HII	J"9aE::GW Aq$>>NFFF!?IM'00Z0000IM'799j999& #{9;;+vvv/@+
 
 Y[[:-8
 	!7GV5G L3  + + +9;;+
'!!W^44 	/&"455 /MMMMV_MMM% 6#.#3#3#5#5L)% /#.L(ll{+: {{(*
,,,,*#<33"=
Q;;+t,, 7#)+#6#6 J JK"6k"6"6"66J) E(4[(A"&D}&D&D&D&DD
"I+k*B"I"I"I"IIJJJ j(
% 7"WL"W"W"W["W"W"W"WWJJ["6"66JKV%=j%I%IKKK
 	3"s7||+c*oo=>>:g'F= .!-~ 8#/#7#7  *%z)| *)| ('{Ms    I BK/.K/c                 ^   |i n|}	 | || |fi |}n || ||fi |}n[# t           $ rN t          |t                    r |dk    r |}t          j        d| dt                       t                     Y nw xY wt          |t                    rMd |                                D             }|r-|D ]*\  }}	|||<   t          j        d| d|	 t                     +d}
t          |t                    r|                                D ]\  }}t          |d          r@t          t                    5  |                                }ddd           n# 1 swxY w Y   t          |t          j                  s"t          |
|t          |          |fz            |||<   nt          |d          r@t          t                    5  |                                }ddd           n# 1 swxY w Y   t          |t          j                  s"t          |
|t          |          |fz            |S )zCompute the score(s) of an estimator on a given test set.

    Will return a dict of floats if `scorer` is a _MultiMetricScorer, otherwise a single
    float is returned.
    NrC   z[Scoring failed. The score on this train-test partition for these parameters will be set to z. Details: 
c                 F    g | ]\  }}t          |t                    ||fS r   )r   str)rs   r   str_es      r9   r   z_score.<locals>.<listcomp>  s@     
 
 
)dEz%QT?U?U
5M
 
 
r;   z>scoring must return a number, got %s (%s) instead. (scorer=%s)item)r   r   r   r1   r2   r   UserWarningr   r   hasattrr   r0   r   r   r   type)rD   r   r   r`   ro   rN   r   exception_messagesr   r   	error_msgr^   s               r9   r   r     s=    &-22<L>VIv>>>>FFVIvvFFFFF   f011 	 g%%$*;F* *%<<* *      ( &,-- 
 
-3\\^^
 
 
  	1 	 	e*t#;F# # # #      QI&$ I!<<>> 	! 	!KD%uf%% )j)) ) )!JJLLE) ) ) ) ) ) ) ) ) ) ) ) ) ) ) eW^44 I eT%[[$-G!GHHH F4LL	! 66"" 	'*%% ' '' ' ' ' ' ' ' ' ' ' ' ' ' ' ' &'.11 	IY&$v,,)GGHHHMs4   ! AA98A92EE	E	G&&G*-G*predict)r>   r?   N>   r   predict_probadecision_functionpredict_log_proba)
rD   rE   rF   r7   rH   rI   rA   r6   rJ   method)r7   rH   rI   rA   r6   rJ   r   c          	      ,   	 t          |           t                    \  |i n|}t                      rt          d                              |t                                          dd                                         t                                          dd                    }
	 t          |
dfi |n# t          $ rH}t          |j	                  }t          | d	 j
        j         d
| d|j	        |j                  d}~ww xY wt                      t          d|i          _        t          |          _        t!          |t#                               }t%           |j        fi j        j                  }t)          j        d |D                       }t-          |t/                              st1          d          	dv odu}|rt)          j                  j        dk    r$t7                      }|                              nwj        dk    rlt)          j        t<                    }t?          j         d                   D ]4t7                                          ddf                   |ddf<   5|tC          |||          } | 	fd|D                       }t)          j"        tG          |          t<                    t)          j$        tG          |                    |<   tK          j&        |d                   r"tK          j'        ||d         j(                  }n|rttS          |d         t$                    rYj         d         }g }t?          |          D ]7t)          j        fd|D                       }|*                    |           8|}nt)          j        |          }tS          |t$                    rfd|D             S |         S )a*  Generate cross-validated estimates for each input data point.

    The data is split according to the cv parameter. Each sample belongs
    to exactly one test set, and its prediction is computed with an
    estimator fitted on the corresponding training set.

    Passing these predictions into an evaluation metric may not be a valid
    way to measure generalization performance. Results can differ from
    :func:`cross_validate` and :func:`cross_val_score` unless all tests sets
    have equal size and the metric decomposes over samples.

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

    Parameters
    ----------
    estimator : estimator
        The estimator instance to use to fit the data. It must implement a `fit`
        method and the method given by the `method` parameter.

    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        The data to fit. Can be, for example a list, or an array at least 2d.

    y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs),             default=None
        The target variable to try to predict in the case of
        supervised learning.

    groups : array-like of shape (n_samples,), default=None
        Group labels for the samples used while splitting the dataset into
        train/test set. Only used in conjunction with a "Group" :term:`cv`
        instance (e.g., :class:`GroupKFold`).

        .. versionchanged:: 1.4
            ``groups`` can only be passed if metadata routing is not enabled
            via ``sklearn.set_config(enable_metadata_routing=True)``. When routing
            is enabled, pass ``groups`` alongside other metadata via the ``params``
            argument instead. E.g.:
            ``cross_val_predict(..., params={'groups': groups})``.

    cv : int, cross-validation generator or an iterable, default=None
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - None, to use the default 5-fold cross validation,
        - int, to specify the number of folds in a `(Stratified)KFold`,
        - :term:`CV splitter`,
        - An iterable that generates (train, test) splits as arrays of indices.

        For int/None inputs, if the estimator is a classifier and ``y`` is
        either binary or multiclass, :class:`StratifiedKFold` is used. In all
        other cases, :class:`KFold` is used. These splitters are instantiated
        with `shuffle=False` so the splits will be the same across calls.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. versionchanged:: 0.22
            ``cv`` default value if None changed from 3-fold to 5-fold.

    n_jobs : int, default=None
        Number of jobs to run in parallel. Training the estimator and
        predicting are parallelized over the cross-validation splits.
        ``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
        The verbosity level.

    params : dict, default=None
        Parameters to pass to the underlying estimator's ``fit`` and the CV
        splitter.

        .. versionadded:: 1.4

    pre_dispatch : int or str, default='2*n_jobs'
        Controls the number of jobs that get dispatched during parallel
        execution. Reducing this number can be useful to avoid an
        explosion of memory consumption when more jobs get dispatched
        than CPUs can process. This parameter can be:

        - None, in which case all the jobs are immediately created and spawned. Use
          this for lightweight and fast-running jobs, to avoid delays due to on-demand
          spawning of the jobs
        - An int, giving the exact number of total jobs that are spawned
        - A str, giving an expression as a function of n_jobs, as in '2*n_jobs'

    method : {'predict', 'predict_proba', 'predict_log_proba',               'decision_function'}, default='predict'
        The method to be invoked by `estimator`.

    Returns
    -------
    predictions : ndarray
        This is the result of calling `method`. Shape:

        - When `method` is 'predict' and in special case where `method` is
          'decision_function' and the target is binary: (n_samples,)
        - When `method` is one of {'predict_proba', 'predict_log_proba',
          'decision_function'} (unless special case above):
          (n_samples, n_classes)
        - If `estimator` is :term:`multioutput`, an extra dimension
          'n_outputs' is added to the end of each shape above.

    See Also
    --------
    cross_val_score : Calculate score for each CV split.
    cross_validate : Calculate one or more scores and timings for each CV
        split.

    Notes
    -----
    In the case that one or more classes are absent in a training portion, a
    default score needs to be assigned to all instances for that class if
    ``method`` produces columns per class, as in {'decision_function',
    'predict_proba', 'predict_log_proba'}.  For ``predict_proba`` this value is
    0.  In order to ensure finite output, we approximate negative infinity by
    the minimum finite float value for the dtype in other cases.

    Examples
    --------
    >>> from sklearn import datasets, linear_model
    >>> from sklearn.model_selection import cross_val_predict
    >>> diabetes = datasets.load_diabetes()
    >>> X = diabetes.data[:150]
    >>> y = diabetes.target[:150]
    >>> lasso = linear_model.Lasso()
    >>> y_pred = cross_val_predict(lasso, X, y, cv=3)
    Nr(   rT   r=   rV   rW   rZ   r]   z| are passed to `cross_val_predict` but are not explicitly set as requested or not requested for cross_validate's estimator: zR Call `.set_fit_request({{metadata}}=True)` on the estimator for each metadata in rb   rc   r7   rg   rh   rQ   c                     g | ]\  }}|S r   r   )rs   r   rm   s      r9   r   z%cross_val_predict.<locals>.<listcomp>  s    ">">">GAt4">">">r;   z+cross_val_predict only works for partitionsr   r   r   r&   r	   dtyperj   c           
   3      K   | ]A\  }} t          t                    t                    ||j        j                  V  Bd S N)r#   _fit_and_predictr
   rD   r=   )rs   rl   rm   rE   rD   r   rf   rF   s      r9   ru   z$cross_val_predict.<locals>.<genexpr>  su         E4 	" !!)#'	
 	
     r;   r   )formatc                      g | ]
}|         S r   r   )rs   pi_labels     r9   r   z%cross_val_predict.<locals>.<listcomp>  s    )J)J)J!G*)J)J)Jr;   c                      g | ]
}|         S r   r   )rs   r  inv_test_indicess     r9   r   z%cross_val_predict.<locals>.<listcomp>   s    999"#999r;   )+r4   r   r   r   r{   r   r    r   r|   re   r}   r~   rf   r   r[   rD   r'   r   r   rV   npconcatenate_check_is_permutationr%   r0   r   ndimr   fit_transform
zeros_likeintrangeshaper"   emptyr   arangespissparsevstackr  r   r   )rD   rE   rF   r7   rH   rI   rA   r6   rJ   r   r   r   re   splitstest_indicesencodeley_encr   predictionsn_labelsconcat_predlabel_predsr  r  rf   s   ```      `             @@@r9   r*   r*     s   L #6***Q??DAq>RRvF )4
 !1222S,22%2PP    S#,22%2NN    		+FEDDVDDMM' 	 	 	
 "((<!=!=*) - -4=4G4P- - *<	- - - $%#7o   	* !&h-?!@!@!@"'F"3"3"3	"aM)$<$<	=	=	=B("(1a@@=#9#?@@AAF>">">v">">">??L |A?? HFGGG
 	MM 	TM   	JqMM6Q;;B  ##AAVq[[M!3///E ,, P P$0NN$@$@111g:$O$Oaaaj!!A vw\RRRH(         "    K xL 1 1===%'Ys</@/@%A%A\"	{;q>"" 2iKN4IJJJ	 2J{1~t44 2
 71:X 	, 	,G.)J)J)J)Jk)J)J)JKKK{++++!n[11+t$$ -9999[9999+,,s   ;C
 

DADDc                 6    ||ni }t          |||          }t           ||          \  }}t           |||          \  }	}
|  j        |fi | n  j        ||fi | t                     } ||	          dv odu}|rt	          t
                    r, fdt          t                              D             nKj        dk    rt          t                              nj
        d         }t           j        |          S )a(  Fit estimator and predict values for a given dataset split.

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

    Parameters
    ----------
    estimator : estimator object implementing 'fit' and 'predict'
        The object to use to fit the data.

    X : array-like of shape (n_samples, n_features)
        The data to fit.

        .. versionchanged:: 0.20
            X is only required to be an object with finite length or shape now

    y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
        The target variable to try to predict in the case of
        supervised learning.

    train : array-like of shape (n_train_samples,)
        Indices of training samples.

    test : array-like of shape (n_test_samples,)
        Indices of test samples.

    fit_params : dict or None
        Parameters that will be passed to ``estimator.fit``.

    method : str
        Invokes the passed method name of the passed estimator.

    Returns
    -------
    predictions : sequence
        Result of calling 'estimator.method'
    Nr   r   c                     g | ]J}t          j        |         |         t          t          d d |f                                       KS )N)	n_classesr   )_enforce_prediction_orderclasses_r   set)rs   r  rD   r   r  rF   s     r9   r   z$_fit_and_predict.<locals>.<listcomp>?  so         *&w/(!#a7
m"4"455!	    r;   r&   )r$   r!   r=   getattrr   r   r  r   r
  r#  r  r!  r"  )rD   rE   rF   rl   rm   r5   r   r   r   r   r   funcr  r   r  s   ` `   `       @r9   r   r     s   L  *52J%a
EJJJJ"9aE::GWIq!T599IFA	g,,,,,,	gw55*5559f%%D$v,,K 	MM 	TM 
  k4(( 	        %S%5%566  KK ()v{{CFF
I3"KF K r;   c           	         |t          |           k    rGd}t          j        d                    t          |           ||          t                     |dk    r|j        dk    rT|j        d         t          |           k    r6t          d                    |j        |t          |                               t          |           dk    r1t          d                    t          |           ||                    t          j	        |j
                  j        }||dd	}t          j        t          |          |f||         |j
        
          }||dd| f<   |}|S )a   Ensure that prediction arrays have correct column order

    When doing cross-validation, if one or more classes are
    not present in the subset of data used for training,
    then the output prediction array might not have the same
    columns as other folds. Use the list of class names
    (assumed to be ints) to enforce the correct column order.

    Note that `classes` is the list of classes in this fold
    (a subset of the classes in the full training set)
    and `n_classes` is the number of classes in the full training set.
    zTTo fix this, use a cross-validation technique resulting in properly stratified foldszNumber of classes in training fold ({}) does not match total number of classes ({}). Results may not be appropriate for your use case. {}r   r	   r&   zOutput shape {} of {} does not match number of classes ({}) in fold. Irregular decision_function outputs are not currently supported by cross_val_predictzOnly {} class/es in training fold, but {} in overall dataset. This is not supported for decision_function with imbalanced folds. {}r   )r   r   r   r   N)r   r1   r2   r  RuntimeWarningr
  r  r0   r  finfor   minfullr%   )classesr  r   r   recommendation	float_mindefault_valuespredictions_for_all_classess           r9   r!  r!  Q  s    CLL   	
 	 Gi@@	
 	
 	
 (((1$$):1)=W)M)M
 !( )/{/@&#g,,(W(W   7||q   0 17Gi1 1	   H[.//3	!*!*
 

 ')g+&&	26"#'
 '
 '
#
 3>#AAAwJ/1r;   c                     t          |           |k    rdS t          j        |t                    }d|| <   t          j        |          sdS dS )a5  Check whether indices is a reordering of the array np.arange(n_samples)

    Parameters
    ----------
    indices : ndarray
        int array to test
    n_samples : int
        number of expected elements

    Returns
    -------
    is_partition : bool
        True iff sorted(indices) is np.arange(n)
    Fr   T)r   r  zerosboolall)rx   	n_sampleshits      r9   r	  r	    sQ     7||y  u
(9D
)
)
)CCL6#;; u4r;   left)closedrandom_state)rD   rE   rF   r7   rH   n_permutationsrI   r8  rA   rG   r5   r6   d   )	r7   rH   r9  rI   r8  rA   rG   r5   r6   c       	   
      4    t          |
|d          }t                    \  t          t                               t	           |	          t                    t                      rt          d                               t                                          dd                                        t                                          dd	          
                              t                                          dd                    }	 t          |dfi |n# t          $ rH}t          |j                  }t          | d j        j         d| d|j        |j                  d}~ww xY wt#                      t#          |          _        t#          di          _        t#          i           _        t+          t-                     j        j        j        j        j        j                  } t5          ||           fdt7          |          D                       }t9          j        |          }t9          j        ||k              dz   |dz   z  }|||fS )a  Evaluate the significance of a cross-validated score with permutations.

    Permutes targets to generate 'randomized data' and compute the empirical
    p-value against the null hypothesis that features and targets are
    independent.

    The p-value represents the fraction of randomized data sets where the
    estimator performed as well or better than in the original data. A small
    p-value suggests that there is a real dependency between features and
    targets which has been used by the estimator to give good predictions.
    A large p-value may be due to lack of real dependency between features
    and targets or the estimator was not able to use the dependency to
    give good predictions.

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

    Parameters
    ----------
    estimator : estimator object implementing 'fit'
        The object to use to fit the data.

    X : array-like of shape at least 2D
        The data to fit.

    y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
        The target variable to try to predict in the case of
        supervised learning.

    groups : array-like of shape (n_samples,), default=None
        Labels to constrain permutation within groups, i.e. ``y`` values
        are permuted among samples with the same group identifier.
        When not specified, ``y`` values are permuted among all samples.

        When a grouped cross-validator is used, the group labels are
        also passed on to the ``split`` method of the cross-validator. The
        cross-validator uses them for grouping the samples  while splitting
        the dataset into train/test set.

        .. versionchanged:: 1.6
            ``groups`` can only be passed if metadata routing is not enabled
            via ``sklearn.set_config(enable_metadata_routing=True)``. When routing
            is enabled, pass ``groups`` alongside other metadata via the ``params``
            argument instead. E.g.:
            ``permutation_test_score(..., params={'groups': groups})``.

    cv : int, cross-validation generator or an iterable, default=None
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - `None`, to use the default 5-fold cross validation,
        - int, to specify the number of folds in a `(Stratified)KFold`,
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For `int`/`None` inputs, if the estimator is a classifier and `y` is
        either binary or multiclass, :class:`StratifiedKFold` is used. In all
        other cases, :class:`KFold` is used. These splitters are instantiated
        with `shuffle=False` so the splits will be the same across calls.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. versionchanged:: 0.22
            `cv` default value if `None` changed from 3-fold to 5-fold.

    n_permutations : int, default=100
        Number of times to permute ``y``.

    n_jobs : int, default=None
        Number of jobs to run in parallel. Training the estimator and computing
        the cross-validated score are parallelized over the permutations.
        ``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 or None, default=0
        Pass an int for reproducible output for permutation of
        ``y`` values among samples. See :term:`Glossary <random_state>`.

    verbose : int, default=0
        The verbosity level.

    scoring : str or callable, default=None
        A single str (see :ref:`scoring_parameter`) or a callable
        (see :ref:`scoring_callable`) to evaluate the predictions on the test set.

        If `None` the estimator's score method is used.

    fit_params : dict, default=None
        Parameters to pass to the fit method of the estimator.

        .. deprecated:: 1.6
            This parameter is deprecated and will be removed in version 1.6. Use
            ``params`` instead.

    params : dict, default=None
        Parameters to pass to the `fit` method of the estimator, the scorer
        and the cv splitter.

        - If `enable_metadata_routing=False` (default): Parameters directly passed to
          the `fit` method of the estimator.

        - If `enable_metadata_routing=True`: Parameters safely routed to the `fit`
          method of the estimator, `cv` object and `scorer`. See :ref:`Metadata Routing
          User Guide <metadata_routing>` for more details.

        .. versionadded:: 1.6

    Returns
    -------
    score : float
        The true score without permuting targets.

    permutation_scores : array of shape (n_permutations,)
        The scores obtained for each permutations.

    pvalue : float
        The p-value, which approximates the probability that the score would
        be obtained by chance. This is calculated as:

        `(C + 1) / (n_permutations + 1)`

        Where C is the number of permutations whose score >= the true score.

        The best possible p-value is 1/(n_permutations + 1), the worst is 1.0.

    Notes
    -----
    This function implements Test 1 in:

    Ojala and Garriga. `Permutation Tests for Studying Classifier Performance
    <http://www.jmlr.org/papers/volume11/ojala10a/ojala10a.pdf>`_. The
    Journal of Machine Learning Research (2010) vol. 11

    Examples
    --------
    >>> from sklearn.datasets import make_classification
    >>> from sklearn.linear_model import LogisticRegression
    >>> from sklearn.model_selection import permutation_test_score
    >>> X, y = make_classification(random_state=0)
    >>> estimator = LogisticRegression()
    >>> score, permutation_scores, pvalue = permutation_test_score(
    ...     estimator, X, y, random_state=0
    ... )
    >>> print(f"Original Score: {score:.3f}")
    Original Score: 0.810
    >>> print(
    ...     f"Permutation Scores: {permutation_scores.mean():.3f} +/- "
    ...     f"{permutation_scores.std():.3f}"
    ... )
    Permutation Scores: 0.505 +/- 0.057
    >>> print(f"P-value: {pvalue:.3f}")
    P-value: 0.010
    1.8rQ   r   r+   rT   r=   rW   r]   rV   rZ   r^   r_   z are passed to `permutation_test_score` but are not explicitly set as requested or not requested for permutation_test_score's estimator: ra   rb   rc   Nrh   r7   rg   ri   split_paramsr5   ro   )rI   rA   c              3      K   | ]c} t          t                    t                    t          	          j        j        j        j        j        j	                   V  ddS )r=  N)
r#   _permutation_test_scorer
   _shuffler[   rV   rD   r=   r`   r^   )
rs   r   rE   rH   rD   r7   r8  rf   r`   rF   s
     r9   ru   z)permutation_test_score.<locals>.<genexpr>  s       B B  	)'(()Q--&/5$.2&-3		
 		
 		
B B B B B Br;         ?r&   )r:   r   r'   r   r   r   r   r   r{   r   r    r   r|   re   r}   r~   rf   r   rD   r[   r`   r@  r
   rV   r=   r^   r"   r  r  arraysum)rD   rE   rF   r7   rH   r9  rI   r8  rA   rG   r5   r6   r   r   re   r^   permutation_scorespvaluerf   r`   s   `````  `          @@r9   r+   r+     s-   t .j&&%PPFQ6**LAq&	"aM)$<$<	=	=	=B9g666F%l33L 0/!9:::S#  -22%2NN	    S,22%2PP    S,22%2PP    	$	+FEDDVDDMM' 	 	 	
 "((<!=!=*) 	$ 	$ $-#6#?	$ 	$
 *<	$ 	$ 	$ $%#7o   	0 "'F"3"3"3!&h-?!@!@!@$2 $i		
"+1 *.")/	 	 	E BAAA B B B B B B B B B B B ~&&B B B   "455f'5011C7NQ<NOF$f,,s   1E   
F
AFFc                 h   ||ni }||ni }g } |j         ||fi |D ]\  }	}
t          | |||	          \  }}t          | |||
|	          \  }}t          |||	          }t          |||
          } | j        ||fi | |                     || ||fi |           t          j        |          S )z-Auxiliary function for permutation_test_scoreNr   )rV   r!   r$   r=   r   r  mean)rD   rE   rF   rH   r`   r>  r5   ro   	avg_scorerl   rm   r   r   r   r   fit_params_trainr   s                    r9   r@  r@    s   
  *52J#/#;<<LIrx15555 Q Qt&y!Q>>$Y1dEBB/*eTTT0<QUVVV	gw;;*:;;;	66OO=NOOPPPP79r;   c                 $   |#|                     t          |                     }n\t          j        t          |                    }t          j        |          D ]&}||k    }|                     ||                   ||<   't          | |          S )zAReturn a shuffled copy of y eventually shuffle among same groups.)permutationr   r  r  uniquer   )rF   r7   r8  rx   group	this_masks         r9   rA  rA    s    ~**3q6622)CKK((Yv&& 	N 	NE%I!-!9!9'):L!M!MGI!W%%%r;   rD   rE   rF   r7   train_sizesrH   rG   exploit_incremental_learningrI   rJ   shufflerN   rp   r5   r6   g?rB     r3  )r7   rP  rH   rG   rQ  rI   rJ   rA   rR  r8  rN   rp   r5   r6   c                   
#$%&' |rt           d          st          d          t          |||d          }t          |          \  }t	          |t                               }t           |          &t                      r,t          d          	                     t                      	                    dd	          	                    dd	          
          	                    |t                      	                    dd	                    	                    &t                      	                    dd	                    }	 t          |dfi |%n# t          $ rH}t          |j                  }t          | d j        j         d| d|j        |j                  d}~ww xY wt%                      %t%          ||          %_        t%          d|i          %_        t%          i           %_        t-           |j        fi %j        j                  }t1          |d         d                   }t3          ||          ''j        d         }
dk    rt7          dt9          '          z              t;          ||	
          }|rt=          |          $$fd|D             }|rmt                     rt?          j                   nd# |# %&'f	d|D                       }t?          j!        |          "                    d          }ng }|D ])\  }}'D ]!}|#                    |d|         |f           "* | %&
fd|D                       }tI          |           tK          |          }|d         &                    d |          j'        }|d!         &                    d |          j'        }||g}rY|d"         &                    d |          j'        } |d#         &                    d |          j'        }!|(                    | |!g           '|d         |d$         f}"r|"|d%         |d&         fz   }"|"S )'a  Learning curve.

    Determines cross-validated training and test scores for different training
    set sizes.

    A cross-validation generator splits the whole dataset k times in training
    and test data. Subsets of the training set with varying sizes will be used
    to train the estimator and a score for each training subset size and the
    test set will be computed. Afterwards, the scores will be averaged over
    all k runs for each training subset size.

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

    Parameters
    ----------
    estimator : object type that implements the "fit" method
        An object of that type which is cloned for each validation. It must
        also implement "predict" unless `scoring` is a callable that doesn't
        rely on "predict" to compute a score.

    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        Training vector, where `n_samples` is the number of samples and
        `n_features` is the number of features.

    y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
        Target relative to X for classification or regression;
        None for unsupervised learning.

    groups : array-like of shape (n_samples,), default=None
        Group labels for the samples used while splitting the dataset into
        train/test set. Only used in conjunction with a "Group" :term:`cv`
        instance (e.g., :class:`GroupKFold`).

        .. versionchanged:: 1.6
            ``groups`` can only be passed if metadata routing is not enabled
            via ``sklearn.set_config(enable_metadata_routing=True)``. When routing
            is enabled, pass ``groups`` alongside other metadata via the ``params``
            argument instead. E.g.:
            ``learning_curve(..., params={'groups': groups})``.

    train_sizes : array-like of shape (n_ticks,),             default=np.linspace(0.1, 1.0, 5)
        Relative or absolute numbers of training examples that will be used to
        generate the learning curve. If the dtype is float, it is regarded as a
        fraction of the maximum size of the training set (that is determined
        by the selected validation method), i.e. it has to be within (0, 1].
        Otherwise it is interpreted as absolute sizes of the training sets.
        Note that for classification the number of samples usually has to
        be big enough to contain at least one sample from each class.

    cv : int, cross-validation generator or an iterable, default=None
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - None, to use the default 5-fold cross validation,
        - int, to specify the number of folds in a `(Stratified)KFold`,
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For int/None inputs, if the estimator is a classifier and ``y`` is
        either binary or multiclass, :class:`StratifiedKFold` is used. In all
        other cases, :class:`KFold` is used. These splitters are instantiated
        with `shuffle=False` so the splits will be the same across calls.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. versionchanged:: 0.22
            ``cv`` default value if None changed from 3-fold to 5-fold.

    scoring : str or callable, default=None
        A str (see :ref:`scoring_parameter`) or a scorer callable object / function with
        signature ``scorer(estimator, X, y)``.

    exploit_incremental_learning : bool, default=False
        If the estimator supports incremental learning, this will be
        used to speed up fitting for different training set sizes.

    n_jobs : int, default=None
        Number of jobs to run in parallel. Training the estimator and computing
        the score are parallelized over the different training and test sets.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    pre_dispatch : int or str, default='all'
        Number of predispatched jobs for parallel execution (default is
        all). The option can reduce the allocated memory. The str can
        be an expression like '2*n_jobs'.

    verbose : int, default=0
        Controls the verbosity: the higher, the more messages.

    shuffle : bool, default=False
        Whether to shuffle training data before taking prefixes of it
        based on``train_sizes``.

    random_state : int, RandomState instance or None, default=None
        Used when ``shuffle`` is True. Pass an int for reproducible
        output across multiple function calls.
        See :term:`Glossary <random_state>`.

    error_score : 'raise' or numeric, default=np.nan
        Value to assign to the score if an error occurs in estimator fitting.
        If set to 'raise', the error is raised.
        If a numeric value is given, FitFailedWarning is raised.

        .. versionadded:: 0.20

    return_times : bool, default=False
        Whether to return the fit and score times.

    fit_params : dict, default=None
        Parameters to pass to the fit method of the estimator.

        .. deprecated:: 1.6
            This parameter is deprecated and will be removed in version 1.8. Use
            ``params`` instead.

    params : dict, default=None
        Parameters to pass to the `fit` method of the estimator and to the scorer.

        - If `enable_metadata_routing=False` (default): Parameters directly passed to
          the `fit` method of the estimator.

        - If `enable_metadata_routing=True`: Parameters safely routed to the `fit`
          method of the estimator. See :ref:`Metadata Routing User Guide
          <metadata_routing>` for more details.

        .. versionadded:: 1.6

    Returns
    -------
    train_sizes_abs : array of shape (n_unique_ticks,)
        Numbers of training examples that has been used to generate the
        learning curve. Note that the number of ticks might be less
        than n_ticks because duplicate entries will be removed.

    train_scores : array of shape (n_ticks, n_cv_folds)
        Scores on training sets.

    test_scores : array of shape (n_ticks, n_cv_folds)
        Scores on test set.

    fit_times : array of shape (n_ticks, n_cv_folds)
        Times spent for fitting in seconds. Only present if ``return_times``
        is True.

    score_times : array of shape (n_ticks, n_cv_folds)
        Times spent for scoring in seconds. Only present if ``return_times``
        is True.

    Examples
    --------
    >>> from sklearn.datasets import make_classification
    >>> from sklearn.tree import DecisionTreeClassifier
    >>> from sklearn.model_selection import learning_curve
    >>> X, y = make_classification(n_samples=100, n_features=10, random_state=42)
    >>> tree = DecisionTreeClassifier(max_depth=4, random_state=42)
    >>> train_size_abs, train_scores, test_scores = learning_curve(
    ...     tree, X, y, train_sizes=[0.3, 0.6, 0.9]
    ... )
    >>> for train_size, cv_train_scores, cv_test_scores in zip(
    ...     train_size_abs, train_scores, test_scores
    ... ):
    ...     print(f"{train_size} samples were used to train the model")
    ...     print(f"The average train accuracy is {cv_train_scores.mean():.2f}")
    ...     print(f"The average test accuracy is {cv_test_scores.mean():.2f}")
    24 samples were used to train the model
    The average train accuracy is 1.00
    The average test accuracy is 0.85
    48 samples were used to train the model
    The average train accuracy is 1.00
    The average test accuracy is 0.90
    72 samples were used to train the model
    The average train accuracy is 1.00
    The average test accuracy is 0.93
    partial_fitzSAn estimator must support the partial_fit interface to exploit incremental learningr<  rQ   r   r,   rT   r=   rW   r]   rV   rZ   r^   r_   zy are passed to `learning_curve` but are not explicitly set as requested or not requested for learning_curve's estimator: ra   rb   rc   N)r=   rU  r7   rg   ri   r   z%[learning_curve] Training set sizes: rI   rJ   rA   c              3   L   K   | ]\  }}                     |          |fV  d S r   )rL  )rs   rl   rm   rngs      r9   ru   z!learning_curve.<locals>.<genexpr>	  s8      MMkeTCOOE**D1MMMMMMr;   c              3      	K   | ]Q\  }} t          t                    t                    ||
	j        j        j        j                   V  RdS ))rN   r5   ro   N)r#   _incremental_fit_estimatorr
   rD   rU  r`   r^   )rs   rl   rm   rE   r+  rN   rD   rp   rf   r`   train_sizes_absrF   s      r9   ru   z!learning_curve.<locals>.<genexpr>  s       
 
 t 0G.//i  '(2>*17  
 
 
 
 
 
r;   )r	   r&   r   c              3      K   | ]R\  }} t          t                    t                    
||	d j        j        j        j        d          V  Sd S )NT)
r`   rl   rm   rA   rn   r5   ro   rK   rN   rp   rq   )rs   rl   rm   rE   rN   rD   rp   rf   r`   rA   rF   s      r9   ru   z!learning_curve.<locals>.<genexpr>%  s       
 
  t $GN##i  (26*17#'')  
 
 
 
 
 
r;   rz   ry   rv   rw   r&   r	      ))r   r0   r:   r   r'   r   r   r   r   r{   r   r    r   r|   re   r}   r~   rf   r   rD   r[   r`   r   rV   r   _translate_train_sizesr  r   r   r"   r   r  rM  r   	transposer   r   r   reshapeTextend)(rD   rE   rF   r7   rP  rH   rG   rQ  rI   rJ   rA   rR  r8  rN   rp   r5   r6   r   r   re   cv_itern_max_training_samplesn_unique_ticksr   outtrain_test_proportionsrl   rm   n_train_samplesr   rz   ry   	fit_timesscore_timesr   r+  rX  rf   r`   r[  s(   ```       `  ``                    @@@@@r9   r,   r,     sm   x $ 
GI},M,M 
.
 
 	

 .j&&%PPFQ6**LAq&	"aM)$<$<	=	=	=B9g666F 1/!1222S#  -E%00E-88    S,22%2PP    S,22%2PP    	(	+FEDDVDDMM' 	 	 	
 "((<!=!=*) $ $#,#6#?$ $ *<	$ $ $ $%#7o   	. "'F"G"G"G!&h-?!@!@!@$2 828AqAAM$:$@AABBG A// -[:PQQO$*1-N{{5O8L8LLMMMvL'RRRH N ..MMMMWMMM# 51"/	":":D")A,,,h 
 
 
 
 
 
 
 
 
 
 
 
  '
 
 
 
 
" joo''	22!#" 	O 	OKE4#2 O O&--u5Eo5E/F.MNNNNO ( 
 
 
 
 
 
 
 
 
 
 
   6!
 
 
 
 
$ 	*';???(11~.66r>JJLm,44RHHJ[) 	1
+33BGGII!,/77NKKMKJJ	;/000
3q63q6
)C %SVSV$$Js   E* *
F<4AF77F<c                 l   t          j        |           }|j        d         }t          j        |          }t          j        |          }t          j        |j        t           j                  rV|dk    s|dk    rt          d||fz            ||z  	                    t          d          }t          j        |d|          }n!|dk    s||k    rt          d|||fz            t          j        |          }||j        d         k    r*t          j        d	|j        d         |fz  t                     |S )
a~  Determine absolute sizes of training subsets and validate 'train_sizes'.

    Examples:
        _translate_train_sizes([0.5, 1.0], 10) -> [5, 10]
        _translate_train_sizes([5, 10], 10) -> [5, 10]

    Parameters
    ----------
    train_sizes : array-like of shape (n_ticks,)
        Numbers of training examples that will be used to generate the
        learning curve. If the dtype is float, it is regarded as a
        fraction of 'n_max_training_samples', i.e. it has to be within (0, 1].

    n_max_training_samples : int
        Maximum number of training samples (upper bound of 'train_sizes').

    Returns
    -------
    train_sizes_abs : array of shape (n_unique_ticks,)
        Numbers of training examples that will be used to generate the
        learning curve. Note that the number of ticks might be less
        than n_ticks because duplicate entries will be removed.
    r   r   rB  ztrain_sizes has been interpreted as fractions of the maximum number of training samples and must be within (0, 1], but is within [%f, %f].F)r   r   r&   z|train_sizes has been interpreted as absolute numbers of training samples and must be within (0, %d], but is within [%d, %d].z|Removed duplicate entries from 'train_sizes'. Number of ticks will be less than the size of 'train_sizes': %d instead of %d.)r  r   r  r)  max
issubdtyper   floatingr0   astyper  cliprM  r1   r2   r'  )rP  re  r[  n_ticksn_min_required_samplesn_max_required_sampless         r9   r_  r_  J  s}   0 j--O#A&GVO44VO44	}_*BK88 !S((,BS,H,HA *+ABC   +-CCKKE L 
 
 '/16LMM #a''%(>>>3 +**	 	 	 i00O&q)))/2A2G2JG1TU 		
 	
 	
 r;   c                    g g g g f\  }}}}t          |t          j        ||          dd                   }|
i }
|t          | j        fi |
}nt          | j        fd|i|
}||ni }t          |||          }t          |||          }|D ]6\  }}|d|         }t          | |||          \  }}t          | |||          \  }}t          | ||||          \  }}t          j                    }| ||           n |||           t          j                    |z
  }|                    |           t          j                    }|                    t          | |||||	                     |                    t          | |||||	                     t          j                    |z
  } |                    |            8|r||||fn||f}!t          j
        |!          j        S )zETrain estimator on training subsets incrementally and compute scores.Nr]  r+  r   )ro   rN   )r   r  rV   r   rU  r$   r!   r   r   r   rC  rb  )"rD   rE   rF   r+  rl   rm   rP  r`   rp   rN   r5   ro   rz   ry   rj  rk  
partitionspartial_fit_funcr   r   ri  partial_traintrain_subsetr   r   X_partial_trainy_partial_trainr   r   	start_fitrv   start_scorerw   r   s"                                     r9   rZ  rZ    sn    9;BB5L+y+["(5+">">ss"CDDJ
"9#8GGJGG"9#8XX'XZXX#/#;<<L-aeTTT,Q|TRRR*4 $' $'&-o-.&y!QEE+6y!Q+V+V($Y1dLIIIKK	"_----_o>>>9;;*"""ikk.'  		
 		
 		
 	/'  		
 		
 		
 Y[[;.
:&&&& 	){I{;;K(  8C==?r;   )rD   rE   rF   
param_nameparam_ranger7   rH   rG   rI   rJ   rA   rN   r5   r6   )	r7   rH   rG   rI   rJ   rA   rN   r5   r6   c                   
 t          |||d          }t          |          \  }t          |t                               }t	           |          t                      rt          d                               t                                          dd                                        |t                                          dd	          
                              t                                          dd                    }	 t          |dfi |n# t          $ rH}t          |j                  }t          | d j        j         d| d|j        |j                  d}~ww xY wt!                      t!          |          _        t!          d|i          _        t!          i           _        t)          ||	
          } | 
f	d |j        fi j        j        D                       }t-                    }t/          |          }|d                             d|          j        }|d                             d|          j        }||fS )a  Validation curve.

    Determine training and test scores for varying parameter values.

    Compute scores for an estimator with different values of a specified
    parameter. This is similar to grid search with one parameter. However, this
    will also compute training scores and is merely a utility for plotting the
    results.

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

    Parameters
    ----------
    estimator : object type that implements the "fit" method
        An object of that type which is cloned for each validation. It must
        also implement "predict" unless `scoring` is a callable that doesn't
        rely on "predict" to compute a score.

    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        Training vector, where `n_samples` is the number of samples and
        `n_features` is the number of features.

    y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
        Target relative to X for classification or regression;
        None for unsupervised learning.

    param_name : str
        Name of the parameter that will be varied.

    param_range : array-like of shape (n_values,)
        The values of the parameter that will be evaluated.

    groups : array-like of shape (n_samples,), default=None
        Group labels for the samples used while splitting the dataset into
        train/test set. Only used in conjunction with a "Group" :term:`cv`
        instance (e.g., :class:`GroupKFold`).

        .. versionchanged:: 1.6
            ``groups`` can only be passed if metadata routing is not enabled
            via ``sklearn.set_config(enable_metadata_routing=True)``. When routing
            is enabled, pass ``groups`` alongside other metadata via the ``params``
            argument instead. E.g.:
            ``validation_curve(..., params={'groups': groups})``.

    cv : int, cross-validation generator or an iterable, default=None
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - None, to use the default 5-fold cross validation,
        - int, to specify the number of folds in a `(Stratified)KFold`,
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For int/None inputs, if the estimator is a classifier and ``y`` is
        either binary or multiclass, :class:`StratifiedKFold` is used. In all
        other cases, :class:`KFold` is used. These splitters are instantiated
        with `shuffle=False` so the splits will be the same across calls.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. versionchanged:: 0.22
            ``cv`` default value if None changed from 3-fold to 5-fold.

    scoring : str or callable, default=None
        A str (see :ref:`scoring_parameter`) or a scorer callable object / function with
        signature ``scorer(estimator, X, y)``.

    n_jobs : int, default=None
        Number of jobs to run in parallel. Training the estimator and computing
        the score are parallelized over the combinations of each parameter
        value and each cross-validation split.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    pre_dispatch : int or str, default='all'
        Number of predispatched jobs for parallel execution (default is
        all). The option can reduce the allocated memory. The str can
        be an expression like '2*n_jobs'.

    verbose : int, default=0
        Controls the verbosity: the higher, the more messages.

    error_score : 'raise' or numeric, default=np.nan
        Value to assign to the score if an error occurs in estimator fitting.
        If set to 'raise', the error is raised.
        If a numeric value is given, FitFailedWarning is raised.

        .. versionadded:: 0.20

    fit_params : dict, default=None
        Parameters to pass to the fit method of the estimator.

        .. deprecated:: 1.6
            This parameter is deprecated and will be removed in version 1.8. Use
            ``params`` instead.

    params : dict, default=None
        Parameters to pass to the estimator, scorer and cross-validation object.

        - If `enable_metadata_routing=False` (default): Parameters directly passed to
          the `fit` method of the estimator.

        - If `enable_metadata_routing=True`: Parameters safely routed to the `fit`
          method of the estimator, to the scorer and to the cross-validation object.
          See :ref:`Metadata Routing User Guide <metadata_routing>` for more details.

        .. versionadded:: 1.6

    Returns
    -------
    train_scores : array of shape (n_ticks, n_cv_folds)
        Scores on training sets.

    test_scores : array of shape (n_ticks, n_cv_folds)
        Scores on test set.

    Notes
    -----
    See :ref:`sphx_glr_auto_examples_model_selection_plot_train_error_vs_test_error.py`

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.datasets import make_classification
    >>> from sklearn.model_selection import validation_curve
    >>> from sklearn.linear_model import LogisticRegression
    >>> X, y = make_classification(n_samples=1_000, random_state=0)
    >>> logistic_regression = LogisticRegression()
    >>> param_name, param_range = "C", np.logspace(-8, 3, 10)
    >>> train_scores, test_scores = validation_curve(
    ...     logistic_regression, X, y, param_name=param_name, param_range=param_range
    ... )
    >>> print(f"The average train accuracy is {train_scores.mean():.2f}")
    The average train accuracy is 0.81
    >>> print(f"The average test accuracy is {test_scores.mean():.2f}")
    The average test accuracy is 0.81
    r<  rQ   r   r-   rT   r=   rW   r]   rV   rZ   r^   r_   z} are passed to `validation_curve` but are not explicitly set as requested or not requested for validation_curve's estimator: ra   rb   rc   Nrh   r7   rg   ri   rV  c              3      	K   | ]X\  }}D ]P} t          t                    t                    
|||i	j        j        	j        j        d           V  QYdS )T)	r`   rl   rm   rA   rn   r5   ro   rK   rN   Nrq   )rs   rl   rm   vrE   rN   rD   r~  r  rf   r`   rA   rF   s       r9   ru   z#validation_curve.<locals>.<genexpr>	  s          E4# " ! 	 )"A$.2&-3##	
 	
 	
      r;   rz   r]  ry   )r:   r   r'   r   r   r   r   r{   r   r    r   r|   re   r}   r~   rf   r   rD   r[   r`   r"   rV   r   r   ra  rb  )rD   rE   rF   r~  r  r7   rH   rG   rI   rJ   rA   rN   r5   r6   r   r   re   r   r   n_paramsrz   ry   rf   r`   s   `````     ``          @@r9   r-   r-     s   ^ .j&&%PPFQ6**LAq&	"aM)$<$<	=	=	=B9g666F -/!3444S#,22%2NN    S,22%2PP    S,22%2PP    	 	+FEDDVDDMM' 	 	 	
 "((<!=!=*) $ $6?6I6R$ $ *<	$ $ $ $%#7o   	. "'F"3"3"3!&h-?!@!@!@$2vL'RRRHh              $28AqIIM,B,HII!    G& ;H$W--G>*222x@@BL-(00X>>@K$$s   #D2 2
F<AE??Fc                 ,      fd d         D             S )a  Aggregate the list of dict to dict of np ndarray

    The aggregated output of _aggregate_score_dicts will be a list of dict
    of form [{'prec': 0.1, 'acc':1.0}, {'prec': 0.1, 'acc':1.0}, ...]
    Convert it to a dict of array {'prec': np.array([0.1 ...]), ...}

    Parameters
    ----------

    scores : list of dict
        List of dicts of the scores for all scorers. This is a flat list,
        assumed originally to be of row major order.

    Example
    -------

    >>> scores = [{'a': 1, 'b':10}, {'a': 2, 'b':2}, {'a': 3, 'b':3},
    ...           {'a': 10, 'b': 10}]                         # doctest: +SKIP
    >>> _aggregate_score_dicts(scores)                        # doctest: +SKIP
    {'a': array([1, 2, 3, 10]),
     'b': array([10, 2, 3, 10])}
    c                     i | ]Wt          d                   t          j                  r t          j        fdD                       nfdD             XS )r   c                      g | ]
}|         S r   r   rs   r^   r   s     r9   r   z5_aggregate_score_dicts.<locals>.<dictcomp>.<listcomp>	  s    777uc
777r;   c                      g | ]
}|         S r   r   r  s     r9   r   z5_aggregate_score_dicts.<locals>.<dictcomp>.<listcomp>	  s    111%*111r;   )r   r   r   r  r   )rs   r   r   s    @r9   r   z*_aggregate_score_dicts.<locals>.<dictcomp>	  s         	&)C.'.992BJ77777778881111&111	  r;   r   r   )r   s   `r9   r   r   	  s4    .    !9   r;   r   ri   )rC   )\__doc__r   r   r1   collectionsr   
contextlibr   	functoolsr   r   	tracebackr   numpyr  scipy.sparsesparser  joblibr   baser
   r   
exceptionsr   r   metricsr   r   metrics._scorerr   preprocessingr   utilsr   r   r   r   utils._array_apir   r   utils._param_validationr   r   r   r   r   utils.metadata_routingr   r   r   r    utils.metaestimatorsr!   utils.parallelr"   r#   utils.validationr$   r%   _splitr'   __all__r:   r4   r#  r   r   tupler   r   nanr(   r   r   r   r)   rr   r   r*   r   r!  r	  r+   r@  rA  linspacer,   r_  rZ  r-   r   r   r;   r9   <module>r     sB
                                                           ' ' ' ' ' ' ' ' C C C C C C C C 5 5 5 5 5 5 5 5 0 0 0 0 0 0 ( ( ( ( ( ( H H H H H H H H H H H H 4 4 4 4 4 4 4 4                         / . . . . . . . . . . . . . A A A A A A A A          >
 
 
  j''(O,D!&Jss++--..//
 mT";,!3(k&K$+"
G9--t4+ . #(1  : Q
 Q Q Q Q5 4Qh
D D D,& & & & F  F  FF  j''(O,D!&Jss#3#3#5#566774HmT";,!3-"
G9--t4  #(  & V$
 V$ V$ V$ V$!  V$J 'j j j j jZC C C CL  j%!3445O,222&mT";,!3-J   	
 * #(-  6 {-
 {- {- {- {-1 0{-|I I IX? ? ?D  0  j''(O,D!&m#8HafEEEFT"'(;Jss#3#3#5#566774HTl,  #(  , ~- ~- ~- ~-# "~-B  &	& 	& 	& jj%))*lO, 	lD! 	<&	
 	~ 	{m 	JJss#3#3#5#566774H 	' 	8T" 	3 	I; 	I; 	( 	

G9--t4 	  	tTl!" 	4,#& #()  6 Ca((!&%U U U U- ,Up
A A AHG G GT  j%))*O,D!e$~&mJss#3#3#5#566774HT"!3;"
G9--t4Tl,   #(#  4 k% k% k% k%' &k%\    r;   