
    0Ph/                    Z   d Z ddlZddlZddlZddlZddlmZmZ ddlm	Z	 ddl
mZmZmZ ddlmZ ddlmZ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mZmZm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<m=Z= ddl>m?Z?m@Z@ ddlAmBZB ddlCmDZDmEZEmFZF ddlGmHZH ddlImJZJmKZKmLZLmMZMmNZN g dZO G d d          ZP G d  d!          ZQd" ZRd# ZSd$ ZT G d% d&eee'          ZU G d( d)eU          ZV G d* d+eU          ZWdS ),zl
The :mod:`sklearn.model_selection._search` includes utilities to fine-tune the
parameters of an estimator.
    N)ABCMetaabstractmethod)defaultdict)IterableMappingSequence)deepcopy)partialreduce)product)MaskedArray)rankdata   )BaseEstimatorMetaEstimatorMixin_fit_contextcloneis_classifier)NotFittedError)check_scoring)_check_multimetric_scoring_MultimetricScorerget_scorer_names)Bunchcheck_random_state)_VisualBlock)
HasMethodsInterval
StrOptions)get_tags)"_deprecate_Xt_in_inverse_transform)MetadataRouterMethodMapping_raise_for_params_routing_enabledprocess_routing)available_if)Paralleldelayed)sample_without_replacement)_check_method_paramscheck_is_fitted	indexable   )check_cv)_aggregate_score_dicts_fit_and_score_insert_error_scores_normalize_score_results!_warn_or_raise_about_fit_failures)GridSearchCVParameterGridParameterSamplerRandomizedSearchCVc                   *    e Zd ZdZd Zd Zd Zd ZdS )r6   a"  Grid of parameters with a discrete number of values for each.

    Can be used to iterate over parameter value combinations with the
    Python built-in function iter.
    The order of the generated parameter combinations is deterministic.

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

    Parameters
    ----------
    param_grid : dict of str to sequence, or sequence of such
        The parameter grid to explore, as a dictionary mapping estimator
        parameters to sequences of allowed values.

        An empty dict signifies default parameters.

        A sequence of dicts signifies a sequence of grids to search, and is
        useful to avoid exploring parameter combinations that make no sense
        or have no effect. See the examples below.

    Examples
    --------
    >>> from sklearn.model_selection import ParameterGrid
    >>> param_grid = {'a': [1, 2], 'b': [True, False]}
    >>> list(ParameterGrid(param_grid)) == (
    ...    [{'a': 1, 'b': True}, {'a': 1, 'b': False},
    ...     {'a': 2, 'b': True}, {'a': 2, 'b': False}])
    True

    >>> grid = [{'kernel': ['linear']}, {'kernel': ['rbf'], 'gamma': [1, 10]}]
    >>> list(ParameterGrid(grid)) == [{'kernel': 'linear'},
    ...                               {'kernel': 'rbf', 'gamma': 1},
    ...                               {'kernel': 'rbf', 'gamma': 10}]
    True
    >>> ParameterGrid(grid)[1] == {'kernel': 'rbf', 'gamma': 1}
    True

    See Also
    --------
    GridSearchCV : Uses :class:`ParameterGrid` to perform a full parallelized
        parameter search.
    c                    t          |t          t          f          s't          d|dt	          |          j                   t          |t                    r|g}|D ]}t          |t                    st          d|d          |                                D ]\  }}t          |t          j	                  r(|j
        dk    rt          d|d|d|j                   t          |t                    s!t          |t          j	        t          f          s+t          d	|d
|dt	          |          j         d          t          |          dk    rt          d	|d|          ѐ|| _        d S )Nz0Parameter grid should be a dict or a list, got: 	 of type zParameter grid is not a dict ()r.   zParameter array for z! should be one-dimensional, got: z with shape Parameter grid for parameter z. needs to be a list or a numpy array, but got z
 (of type zG) instead. Single values need to be wrapped in a list with one element.r   z' need to be a non-empty sequence, got: )
isinstancer   r   	TypeErrortype__name__dictitemsnpndarrayndim
ValueErrorshapestrr   len
param_grid)selfrK   gridkeyvalues        _/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/model_selection/_search.py__init__zParameterGrid.__init__h   s
   *w&9:: 	5: 5 5j))25 5  
 j'** 	& %J  	 	DdD)) L J J J JKKK"jjll  
UeRZ00 UZ!^^$?s ? ?!? ?16? ?   eS)) BJ12 2  $I I I16I I;;/I I I   u::??$F F F<AF F   #* %    c              #      K   | j         D ]c}t          |                                          }|si V  *t          | \  }}t	          | D ]#}t          t          ||                    }|V  $ddS )zIterate over the points in the grid.

        Returns
        -------
        params : iterator over dict of str to any
            Yields dictionaries mapping each estimator parameter to one of its
            allowed values.
        N)rK   sortedrC   zipr   rB   )rL   prC   keysvaluesvparamss          rP   __iter__zParameterGrid.__iter__   s        		! 		!A17799%%E !"E{f &) ! !A!#dA,,//F LLLL!		! 		!rR   c                     t          t          t          j                  t	          fd| j        D                       S )zNumber of points on the grid.c              3   n   K   | ]/}|r' d  |                                 D                       ndV  0dS )c              3   4   K   | ]}t          |          V  d S NrJ   .0rY   s     rP   	<genexpr>z2ParameterGrid.__len__.<locals>.<genexpr>.<genexpr>   s(      //qCFF//////rR   r.   N)rX   )rb   rV   r   s     rP   rc   z(ParameterGrid.__len__.<locals>.<genexpr>   s_       
 
@A1;GG//AHHJJ//////!
 
 
 
 
 
rR   )r
   r   operatormulsumrK   )rL   r   s    @rP   __len__zParameterGrid.__len__   sP     &(,// 
 
 
 
EI_
 
 
 
 
 	
rR   c                    | j         D ]}|s|dk    ri c S |dz  }t          t          |                                          ddd          \  }}d |D             }t	          j        |          }||k    r||z  }ti }t          |||          D ]$\  }}	}
t          ||
          \  }}|	|         ||<   %|c S t          d          )a  Get the parameters that would be ``ind``th in iteration

        Parameters
        ----------
        ind : int
            The iteration index

        Returns
        -------
        params : dict of str to any
            Equal to list(self)[ind]
        r   r.   Nc                 ,    g | ]}t          |          S  r`   )rb   v_lists     rP   
<listcomp>z-ParameterGrid.__getitem__.<locals>.<listcomp>   s    <<<VS[[<<<rR   z ParameterGrid index out of range)rK   rU   rT   rC   rD   proddivmod
IndexError)rL   indsub_gridrW   values_listssizestotaloutrN   rl   noffsets               rP   __getitem__zParameterGrid.__getitem__   s      	 	H !88III1HC "%fX^^-=-=&>&>ttt&D!ED,<<|<<<EGENNEe||u&)$e&D&D . .NC"(a..KC%f~CHH


;<<<rR   N)rA   
__module____qualname____doc__rQ   r[   rg   ry   rk   rR   rP   r6   r6   <   s\        ) )V%% %% %%N! ! !(
 
 
'= '= '= '= '=rR   r6   c                   0    e Zd ZdZdddZd Zd Zd ZdS )r7   a  Generator on parameters sampled from given distributions.

    Non-deterministic iterable over random candidate combinations for hyper-
    parameter search. If all parameters are presented as a list,
    sampling without replacement is performed. If at least one parameter
    is given as a distribution, sampling with replacement is used.
    It is highly recommended to use continuous distributions for continuous
    parameters.

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

    Parameters
    ----------
    param_distributions : dict
        Dictionary with parameters names (`str`) as keys and distributions
        or lists of parameters to try. Distributions must provide a ``rvs``
        method for sampling (such as those from scipy.stats.distributions).
        If a list is given, it is sampled uniformly.
        If a list of dicts is given, first a dict is sampled uniformly, and
        then a parameter is sampled using that dict as above.

    n_iter : int
        Number of parameter settings that are produced.

    random_state : int, RandomState instance or None, default=None
        Pseudo random number generator state used for random uniform sampling
        from lists of possible values instead of scipy.stats distributions.
        Pass an int for reproducible output across multiple
        function calls.
        See :term:`Glossary <random_state>`.

    Returns
    -------
    params : dict of str to any
        **Yields** dictionaries mapping each estimator parameter to
        as sampled value.

    Examples
    --------
    >>> from sklearn.model_selection import ParameterSampler
    >>> from scipy.stats.distributions import expon
    >>> import numpy as np
    >>> rng = np.random.RandomState(0)
    >>> param_grid = {'a':[1, 2], 'b': expon()}
    >>> param_list = list(ParameterSampler(param_grid, n_iter=4,
    ...                                    random_state=rng))
    >>> rounded_list = [dict((k, round(v, 6)) for (k, v) in d.items())
    ...                 for d in param_list]
    >>> rounded_list == [{'b': 0.89856, 'a': 1},
    ...                  {'b': 0.923223, 'a': 1},
    ...                  {'b': 1.878964, 'a': 2},
    ...                  {'b': 1.038159, 'a': 2}]
    True
    Nrandom_statec          	         t          |t          t          f          s't          d|dt	          |          j                   t          |t                    r|g}|D ]}t          |t                    s"t          d                    |                    |D ]O}t          ||         t                    s2t          ||         d          st          d|d||          d          P|| _	        || _
        || _        d S )Nz5Parameter distribution is not a dict or a list, got: r;   z+Parameter distribution is not a dict ({!r})rvsr=   z* is not iterable or a distribution (value=r<   )r>   r   r   r?   r@   rA   rB   formathasattrn_iterr   param_distributions)rL   r   r   r   distrN   s         rP   rQ   zParameterSampler.__init__  sd   -/BCC 	8,8 8+,,58 8   )733 	8 $7"7' 	 	DdD)) AHHNN     !$s)X66 wIu@ @  $A A A48IA A A  	 (#6   rR   c                 >    t          d | j        D                       S )Nc              3   l   K   | ]/}t          d  |                                D                       V  0dS )c              3   8   K   | ]}t          |d            V  dS )r   N)r   ra   s     rP   rc   z;ParameterSampler._is_all_lists.<locals>.<genexpr>.<genexpr>-  s/      ==!GAu%%%======rR   N)allrX   )rb   r   s     rP   rc   z1ParameterSampler._is_all_lists.<locals>.<genexpr>,  sU       
 
 ==t{{}}=====
 
 
 
 
 
rR   )r   r   rL   s    rP   _is_all_listszParameterSampler._is_all_lists+  s3     
 
0
 
 
 
 
 	
rR   c              #     K   t          | j                  }|                                 rxt          | j                  }t          |          }| j        }||k     r't          j        d|| j        |fz  t                     |}t          |||          D ]}||         V  d S t          | j                  D ]}|                    | j                  }t          |                                          }t                      }	|D ]Z\  }
}t!          |d          r|                    |          |	|
<   /||                    t          |                             |	|
<   [|	V  d S )Nz}The total space of parameters %d is smaller than n_iter=%d. Running %d iterations. For exhaustive searches, use GridSearchCV.r~   r   )r   r   r   r6   r   rJ   r   warningswarnUserWarningr*   rangechoicerT   rC   rB   r   r   randint)rL   rngrK   	grid_sizer   i_r   rC   rZ   krY   s               rP   r[   zParameterSampler.__iter__1  s      !233  	&t'?@@JJI[F6!!25>Y4WX  	   #/	6PSTTT $ $ m####$ $ 4;'' 
 
zz$":;;tzz||,,! ; ;DAqq%(( ;$%EEsE$;$;q		$%ckk#a&&&9&9$:q		
 
rR   c                     |                                  r6t          t          | j                            }t	          | j        |          S | j        S )z&Number of points that will be sampled.)r   rJ   r6   r   minr   )rL   r   s     rP   rg   zParameterSampler.__len__T  sH     	M$*BCCDDIt{I...;rR   )rA   rz   r{   r|   rQ   r   r[   rg   rk   rR   rP   r7   r7      sm        5 5n EI 7 7 7 7 7<
 
 
! ! !F    rR   r7   c                 d    | j         s(t          dt          |           j         d| d          d S )NzThis z. instance was initialized with `refit=False`. z is available only after refitting on the best parameters. You can refit an estimator manually using the `best_params_` attribute)refitAttributeErrorr@   rA   )	search_cvattrs     rP   _check_refitr   ]  sT    ? 
'DOO, ' '"' ' '
 
 	

 
rR   c                       fd}|S )ay  Check if we can delegate a method to the underlying estimator.

    Calling a prediction method will only be available if `refit=True`. In
    such case, we check first the fitted best estimator. If it is not
    fitted, we check the unfitted estimator.

    Checking the unfitted estimator allows to use `hasattr` on the `SearchCV`
    instance even before calling `fit`.
    c                     t          |            t          | d          rt          | j                   dS t          | j                   dS )Nbest_estimator_T)r   r   getattrr   	estimator)rL   r   s    rP   checkz$_search_estimator_has.<locals>.checkr  sU    T4   4*++ 	D($///4%%%trR   rk   )r   r   s   ` rP   _search_estimator_hasr   g  s#         LrR   c              #     K   t          |           }t          t                    }t          |           D ]-\  }}|                                D ]\  }}||d|z           |<   .|                                D ]\  }}t          |                                          }		 t          j        |	          }
|
j	        j
        dk    r|
j        dk    r|
j	        nt          }n)# t          $ r t          j	        t                    }Y nw xY wt          t          j        ||          d          }|                                D ]
\  }}|||<   ||fV  dS )aB  
    Yield a masked array for each candidate param.

    `candidate_params` is a sequence of params which were used in
    a `GridSearchCV`. We use masked arrays for the results, as not
    all params are necessarily present in each element of
    `candidate_params`. For example, if using `GridSearchCV` with
    a `SVC` model, then one might search over params like:

        - kernel=["rbf"], gamma=[0.1, 1]
        - kernel=["poly"], degree=[1, 2]

    and then param `'gamma'` would not be present in entries of
    `candidate_params` corresponding to `kernel='poly'`.
    zparam_%sUr.   dtypeT)maskN)rJ   r   rB   	enumeraterC   listrX   rD   arrayr   kindrF   objectrG   r   empty)candidate_paramsn_candidatesparam_resultscand_idxrZ   namerO   rN   param_result
param_listarr	arr_dtypemaindexs                 rP   "_yield_masked_array_for_each_paramr     s       '((L%%M%&677 ? ?&!<<>> 	? 	?KD%9>M*t+,X66	? +0022  \,--//00
	Y(:&&C &)Y^s%:%:sx1}}		RXII  	) 	) 	) ((III		)  ,i@@@tLLL(..00 	 	LE5BuIIBi1 s   C#DDc            
       j    e Zd ZU dZ edg          g e e e                                ee	e
edgej        dgdeegdgdgej        eg edh          ej        gdgd	Zeed	<   eddd
dddej        d
dd            Zed             Z fdZd-dZ e ed                    d             Z e ed                    d             Z e ed                    d             Z e ed                    d             Z e ed                    d             Z  e ed                    d             Z! e ed                    d.d            Z"ed              Z#ed!             Z$d" Z%d# Z&e'd$             Z(d% Z)d& Z* e+d'(          d-d)            Z,d-d*Z-d+ Z.d, Z/ xZ0S )/BaseSearchCVzEAbstract base class for hyper parameter search with cross-validation.fitNboolean	cv_objectverboseraise	r   scoringn_jobsr   cvr   pre_dispatcherror_scorereturn_train_score_parameter_constraintsTr   2*n_jobsr   r   r   r   r   r   r   r   c                    || _         || _        || _        || _        || _        || _        || _        || _        |	| _        d S r_   )	r   r   r   r   r   r   r   r   r   )
rL   r   r   r   r   r   r   r   r   r   s
             rP   rQ   zBaseSearchCV.__init__  sL     "
(&"4rR   c                     | j         j        S r_   )r   _estimator_typer   s    rP   r   zBaseSearchCV._estimator_type  s     ~--rR   c                 \   t                                                      }t          | j                  }|j        |_        t          |j                  |_        t          |j                  |_        |j        j	        |j        _	        |j        j
        |j        _
        |j        |_        |S r_   )super__sklearn_tags__r    r   estimator_typer	   classifier_tagsregressor_tags
input_tagspairwisesparsearray_api_support)rL   tagssub_estimator_tags	__class__s      rP   r   zBaseSearchCV.__sklearn_tags__  s    ww''))%dn550?'(:(JKK&'9'HII#5#@#I !3!>!E!3!ErR   c                    t          | d           t          |            t          || d           t                      rt	          | dfi |j        d         }nt                      }| j        t          d| j	        z            t          | j        t                    r1| j        r| j        | j                 }n| j        } || j	        ||fi |S  | j        | j	        ||fi |}| j        r|| j                 }|S )aS  Return the score on the given data, if the estimator has been refit.

        This uses the score defined by ``scoring`` where provided, and the
        ``best_estimator_.score`` method otherwise.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Input data, where `n_samples` is the number of samples and
            `n_features` is the number of features.

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

        **params : dict
            Parameters to be passed to the underlying scorer(s).

            .. versionadded:: 1.4
                Only available if `enable_metadata_routing=True`. See
                :ref:`Metadata Routing User Guide <metadata_routing>` for more
                details.

        Returns
        -------
        score : float
            The score defined by ``scoring`` if provided, and the
            ``best_estimator_.score`` method otherwise.
        scoreNzNNo score function explicitly defined, and the estimator doesn't provide one %s)r   r,   r$   r%   r&   scorerrB   scorer_rG   r   r>   multimetric_r   )rL   XyrZ   score_paramsr   r   s          rP   r   zBaseSearchCV.score  s-   > 	T7###&$000 	"*4CCFCCJ7SLL66L<;=A=QR   dlD)) 	F  &dj16$.1EEEEE T11aHH<HH 	&$*%ErR   score_samplesc                 T    t          |            | j                            |          S )a  Call score_samples on the estimator with the best found parameters.

        Only available if ``refit=True`` and the underlying estimator supports
        ``score_samples``.

        .. versionadded:: 0.24

        Parameters
        ----------
        X : iterable
            Data to predict on. Must fulfill input requirements
            of the underlying estimator.

        Returns
        -------
        y_score : ndarray of shape (n_samples,)
            The ``best_estimator_.score_samples`` method.
        )r,   r   r   rL   r   s     rP   r   zBaseSearchCV.score_samples+  )    ( 	#11!444rR   predictc                 T    t          |            | j                            |          S )a  Call predict on the estimator with the best found parameters.

        Only available if ``refit=True`` and the underlying estimator supports
        ``predict``.

        Parameters
        ----------
        X : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        Returns
        -------
        y_pred : ndarray of shape (n_samples,)
            The predicted labels or values for `X` based on the estimator with
            the best found parameters.
        )r,   r   r   r   s     rP   r   zBaseSearchCV.predictB  s)    & 	#++A...rR   predict_probac                 T    t          |            | j                            |          S )a  Call predict_proba on the estimator with the best found parameters.

        Only available if ``refit=True`` and the underlying estimator supports
        ``predict_proba``.

        Parameters
        ----------
        X : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        Returns
        -------
        y_pred : ndarray of shape (n_samples,) or (n_samples, n_classes)
            Predicted class probabilities for `X` based on the estimator with
            the best found parameters. The order of the classes corresponds
            to that in the fitted attribute :term:`classes_`.
        )r,   r   r   r   s     rP   r   zBaseSearchCV.predict_probaX  r   rR   predict_log_probac                 T    t          |            | j                            |          S )a  Call predict_log_proba on the estimator with the best found parameters.

        Only available if ``refit=True`` and the underlying estimator supports
        ``predict_log_proba``.

        Parameters
        ----------
        X : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        Returns
        -------
        y_pred : ndarray of shape (n_samples,) or (n_samples, n_classes)
            Predicted class log-probabilities for `X` based on the estimator
            with the best found parameters. The order of the classes
            corresponds to that in the fitted attribute :term:`classes_`.
        )r,   r   r   r   s     rP   r   zBaseSearchCV.predict_log_probao  )    ( 	#55a888rR   decision_functionc                 T    t          |            | j                            |          S )a  Call decision_function on the estimator with the best found parameters.

        Only available if ``refit=True`` and the underlying estimator supports
        ``decision_function``.

        Parameters
        ----------
        X : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        Returns
        -------
        y_score : ndarray of shape (n_samples,) or (n_samples, n_classes)                 or (n_samples, n_classes * (n_classes-1) / 2)
            Result of the decision function for `X` based on the estimator with
            the best found parameters.
        )r,   r   r   r   s     rP   r   zBaseSearchCV.decision_function  r   rR   	transformc                 T    t          |            | j                            |          S )a.  Call transform on the estimator with the best found parameters.

        Only available if the underlying estimator supports ``transform`` and
        ``refit=True``.

        Parameters
        ----------
        X : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        Returns
        -------
        Xt : {ndarray, sparse matrix} of shape (n_samples, n_features)
            `X` transformed in the new space based on the estimator with
            the best found parameters.
        )r,   r   r   r   s     rP   r   zBaseSearchCV.transform  s)    & 	#--a000rR   inverse_transformc                 t    t          ||          }t          |            | j                            |          S )aI  Call inverse_transform on the estimator with the best found params.

        Only available if the underlying estimator implements
        ``inverse_transform`` and ``refit=True``.

        Parameters
        ----------
        X : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        Xt : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

            .. deprecated:: 1.5
                `Xt` was deprecated in 1.5 and will be removed in 1.7. Use `X` instead.

        Returns
        -------
        X : {ndarray, sparse matrix} of shape (n_samples, n_features)
            Result of the `inverse_transform` function for `Xt` based on the
            estimator with the best found parameters.
        )r!   r,   r   r   )rL   r   Xts      rP   r   zBaseSearchCV.inverse_transform  s8    4 /q"55#55a888rR   c                     	 t          |            n?# t          $ r2}t          d                    | j        j                            |d}~ww xY w| j        j        S )z_Number of features seen during :term:`fit`.

        Only available when `refit=True`.
        z*{} object has no n_features_in_ attribute.N)r,   r   r   r   r   rA   r   n_features_in_)rL   nfes     rP   r   zBaseSearchCV.n_features_in_  sw    	D!!!! 	 	 	 <CCN+   		 #22s    
A-A		Ac                 J     t          d          |            | j        j        S )zcClass labels.

        Only available when `refit=True` and the estimator is a classifier.
        classes_)r   r   r   r   s    rP   r   zBaseSearchCV.classes_  s)     	*j))$///#,,rR   c                      t          d          )a  Repeatedly calls `evaluate_candidates` to conduct a search.

        This method, implemented in sub-classes, makes it possible to
        customize the scheduling of evaluations: GridSearchCV and
        RandomizedSearchCV schedule evaluations for their whole parameter
        search space at once but other more sequential approaches are also
        possible: for instance is possible to iteratively schedule evaluations
        for new regions of the parameter search space based on previously
        collected evaluation results. This makes it possible to implement
        Bayesian optimization or more generally sequential model-based
        optimization by deriving from the BaseSearchCV abstract base class.
        For example, Successive Halving is implemented by calling
        `evaluate_candidates` multiples times (once per iteration of the SH
        process), each time passing a different set of candidates with `X`
        and `y` of increasing sizes.

        Parameters
        ----------
        evaluate_candidates : callable
            This callback accepts:
                - a list of candidates, where each candidate is a dict of
                  parameter settings.
                - an optional `cv` parameter which can be used to e.g.
                  evaluate candidates on different dataset splits, or
                  evaluate candidates on subsampled data (as done in the
                  SucessiveHaling estimators). By default, the original `cv`
                  parameter is used, and it is available as a private
                  `_checked_cv_orig` attribute.
                - an optional `more_results` dict. Each key will be added to
                  the `cv_results_` attribute. Values should be lists of
                  length `n_candidates`

            It returns a dict of all results so far, formatted like
            ``cv_results_``.

            Important note (relevant whether the default cv is used or not):
            in randomized splitters, and unless the random_state parameter of
            cv was set to an int, calling cv.split() multiple times will
            yield different splits. Since cv.split() is called in
            evaluate_candidates, this means that candidates will be evaluated
            on different splits each time evaluate_candidates is called. This
            might be a methodological issue depending on the search strategy
            that you're implementing. To prevent randomized splitters from
            being used, you may use _split._yields_constant_splits()

        Examples
        --------

        ::

            def _run_search(self, evaluate_candidates):
                'Try C=0.1 only if C=1 is better than C=10'
                all_results = evaluate_candidates([{'C': 1}, {'C': 10}])
                score = all_results['mean_test_score']
                if score[0] < score[1]:
                    evaluate_candidates([{'C': 0.1}])
        z_run_search not implemented.)NotImplementedErrorrL   evaluate_candidatess     rP   _run_searchzBaseSearchCV._run_search  s    t ""@AAArR   c                     d| j         d}t          | j         t                    o| j         |v }| j         dur%|s%t          | j                   st	          |          dS dS dS )z2Check `refit` is compatible with `scores` is valida  For multi-metric scoring, the parameter refit must be set to a scorer key or a callable to refit an estimator with the best parameter setting on the whole data and make the best_* attributes available for that metric. If this is not needed, refit should be set to False explicitly. z was passed.FN)r   r>   rI   callablerG   )rL   scoresmultimetric_refit_msgvalid_refit_dicts       rP   _check_refit_for_multimetricz)BaseSearchCV._check_refit_for_multimetric)  s     9=
	   	 &dj#66O4:;O Je##$ $TZ(( $ 2333	 $#####rR   c                 $   t          |           rc | |          }t          |t          j                  st	          d          |dk     s|t          |d                   k    rt          d          n|d|                                          }|S )z8Select index of the best combination of hyperparemeters.z&best_index_ returned is not an integerr   rZ   zbest_index_ index out of range
rank_test_)r  r>   numbersIntegralr?   rJ   rp   argmin)r   refit_metricresults
best_indexs       rP   _select_best_indexzBaseSearchCV._select_best_index=  s     E?? 		G wJj'*:;; J HIIIA~~s783D/E/E!E!E !ABBB "F !!<l!<!<=DDFFJrR   c                 ^   d}t          | j                  r| j        }n| j        t          | j        t                    rt	          | j        | j                  }nPt          | j        | j                  }|                     |           | j        }t          || j
        dk              }||fS )zGet the scorer(s) to be used.

        This is used in ``fit`` and ``get_metadata_routing``.

        Returns
        -------
        scorers, refit_metric
        r   Nr   )scorers	raise_exc)r  r   r>   rI   r   r   r   r	  r   r   r   )rL   r  r  s      rP   _get_scorerszBaseSearchCV._get_scorersL  s     DL!! 
	lGG\!Zc%B%B!#DNDLAAGG0NNG--g666:L(D,<,G  G $$rR   c                    t                      rt          | dfi |}nh|                                }|                    dd          }t	          t	          |          t	          d|i          t	          i                     }|S )zGet the parameters to be used for routing.

        This is a method instead of a snippet in ``fit`` since it's used twice,
        here in ``fit``, and in ``HalvingRandomSearchCV.fit``.
        r   groupsN)r   )split)r   )r   splitterr   )r%   r&   copypopr   )rL   rZ   routed_paramsr  s       rP   _get_routed_params_for_fitz'BaseSearchCV._get_routed_params_for_fite  s      		+D%BB6BBMM[[]]FZZ$//F!F+++h%78882  M
 rR   F)prefer_skip_nested_validationc                      j         }                                 \  }}t                    \  t          |          }                     |          t           j        t          |                     j        fi j	        j
        t           j                   t           j         j                  t          |j         j        j        j         j        ddd j         j        	  	        i 5  g g t-          t.                    d fd	}                     |           d	         d
         }t3          |t                     _        t7           j                  r# j        r                     |            j        }ddd           n# 1 swxY w Y    j        s j        sh                      j        |           _         t7           j                  sd|           j                   _!        d          j                   _"         j        r t                    j#        di t           j"        d           _$        tK          j%                    }	  j$        j        fi j         j         n  j$        j        fi j         j         tK          j%                    }
|
|	z
   _&        tO           j$        d          r j$        j(         _(        t3          |tR                    r|j*         _+        n| _+         _,         _-         S )a  Run fit with all sets of parameters.

        Parameters
        ----------

        X : array-like of shape (n_samples, n_features) or (n_samples, n_samples)
            Training vectors, where `n_samples` is the number of samples and
            `n_features` is the number of features. For precomputed kernel or
            distance matrix, the expected shape of X is (n_samples, n_samples).

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

        **params : dict of str -> object
            Parameters passed to the ``fit`` method of the estimator, the scorer,
            and the CV splitter.

            If a fit parameter is an array-like whose length is equal to
            `num_samples` then it will be split by cross-validation along with
            `X` and `y`. For example, the :term:`sample_weight` parameter is
            split because `len(sample_weights) = len(X)`. However, this behavior
            does not apply to `groups` which is passed to the splitter configured
            via the `cv` parameter of the constructor. Thus, `groups` is used
            *to perform the split* and determines which samples are
            assigned to the each side of the a split.

        Returns
        -------
        self : object
            Instance of fitted estimator.
        )rZ   )
classifier)r   r   TF)	r   
fit_paramsr   r   return_n_test_samplesreturn_timesreturn_parametersr   r   Nc                    |p}t          |           } t          |           j        dk    r't          d                    z                        fdt          t          |           t           |j        fi j        j                            D                       }t          |          dk     rt          d          t          |          z  k    r3t          d                    t          |          z                      t          |j                   t          j                  rt          |j                                       |            
                    |           |5|                                D ] \  }}	|                             |           !                    
	          S )Nr   z@Fitting {0} folds for each of {1} candidates, totalling {2} fitsc           
   3      K   | ]D\  \  }}\  }\  }} t          t                    t                    f||||
f|	fd V  EdS ))traintest
parameterssplit_progresscandidate_progressN)r)   r1   r   )rb   r   r*  	split_idxr(  r)  r   base_estimatorfit_and_score_kwargsr   n_splitsr   s         rP   rc   z@BaseSearchCV.fit.<locals>.evaluate_candidates.<locals>.<genexpr>  s         K.:0JMUD ,GN++n--
 $!#-(18'<,4l+C
 
 /
 
     rR   r.   zLNo fits were performed. Was the CV iterator empty? Were there no candidates?zVcv.split and cv.get_n_splits returned inconsistent results. Expected {} splits, got {})r   rJ   r   printr   r   r   r  r  rG   r4   r   r  r   r2   extendrC   _format_results)r   r   more_resultsrv   rN   rO   r   r   all_candidate_paramsall_more_resultsall_outr.  cv_origr/  r0  parallelr  r  rL   r   s         @rP   r  z-BaseSearchCV.fit.<locals>.evaluate_candidates  s<   ]7#'(8#9#9 "#344<!##..4f$lL84K/ /   h          OV!"233!("(1a"P"P=3I3O"P"PQQO O    $ s88a<<$4  
 XX!888$))/#c((l:R)S)S   2#t7GHHH DL)) @(d.>???$++,<===s###+&2&8&8&:&: < <
U(-44U;;;; ..((G=M  rR   r   test_scores
mean_test_rZ   )safefeature_names_in_NNrk   ).r   r  r-   r+   r  r/   r   r   get_n_splitsr  r  r   r(   r   r   rB   r   r   r   r   r   r   r   r   r  r>   r   r  r   r	  r   r  best_index_best_score_best_params_
set_paramsr   timerefit_time_r   r=  r   _scorersr   cv_results_	n_splits_)rL   r   r   rZ   r   r  r  r  first_test_scorerefit_start_timerefit_end_timer5  r6  r7  r.  r8  r/  r0  r9  r  r  s   ```        @@@@@@@@@@rP   r   zBaseSearchCV.fitw  s*   L N	 $ 1 1 3 3A1%a77777??47A-	2J2JKKK'7'1MM0F0LMMt~..4;T=NOOO#$.2&-3#6"&#(L
 
 
 
 
 
  R	* R	*#% G*400A A A A A A A A A A A A A A A A A AF 0111  'qz-8 *+;T B BD %% *$*; *112BCCC#zeR	* R	* R	* R	* R	* R	* R	* R	* R	* R	* R	* R	* R	* R	* R	*n : 
	DT. 
	D#66
L'   D DJ''  $++F+F+F#G$$  !( 1$2B CD: 	P
 $D5#8#8#C $ $)666$ $D   $y{{}($(AMM1H1LMMMM($(JJm.E.IJJJ!Y[[N-0@@Dt+-@AA P)-)=)O& g122 	#"+DLL"DL"!s   BF;;F?F?c                 <   t          |          t          |          }t          |pi                                           D ]\  }}t	          j        |          |<   dfd	} |d|d                     |d|d                    t          |          D ]
\  }}	|	|<   |d<   t          |d                   }
| j        rt          |d                   }|
D ]9} |d|z  |
|         d	d	d 
           | j        r |d|z  ||         d	           :S )NFc                    t          j        |t           j                                      
          }|r&t	                    D ]}|dd|f         d|| fz  <   t          j        |d|          }|d| z  <   |                     d          rat          j        t          j        |                     r:t          j
        d|                     d	          d
          d| t                     t          j        t          j        ||ddt           j        f         z
  dz  d|                    }|d| z  <   |rt          j        |                                          r!t          j        |t           j                  }n^t          j        |          dz
  }	t          j        ||	          }t+          | d                              t           j        d          }|d| z  <   dS dS )z;A small helper to store the scores/times to the cv_results_r   Nz
split%d_%sr.   )axisweightszmean_%s)train_test_zOne or more of the r   r   z scores are non-finite: )categoryr   zstd_%s)nanr   )methodF)r  zrank_%s)rD   r   float64reshaper   average
startswithanyisfiniter   r   r  r   sqrtnewaxisisnanr   	ones_likeint32nanmin
nan_to_numr   astype)key_namer   rO  splitsrankr-  array_means
array_stdsrank_resultmin_array_meansr   r0  r  s             rP   _storez,BaseSearchCV._format_results.<locals>._storeD  s/    HU"*555==lHUUE X!&x X XIDI!!!Y,DWGLIx+@@AA*UGDDDK,7GI()""#677 	BF[)))= = 	 9hnnS.A.A!.D 9 9+69 9 )    
[BJ77A=Aw   J
 ,6GHx'( < 8K((,,.. "$,{"("K"K"KKK&(i&<&<q&@O"$-"Q"Q"QK"*K<"F"F"F"M"Mu #N # #K 1<	H,---< <rR   fit_time
score_timerZ   r:  train_scoresztest_%sT)rd  re  rO  ztrain_%s)rd  )NFF)	rJ   r0   rB   rC   rD   asarrayr   r3   r   )rL   r   r0  rv   r4  rN   valrj  paramr   test_scores_dicttrain_scores_dictscorer_namer   r  s     `          @@rP   r3  zBaseSearchCV._format_results:  s   +,,$S))|)r** 	+ 	+HC :c??GCLL-	< -	< -	< -	< -	< -	< -	< -	<^ 	z3z?+++|S.///;<LMM 	  	 IE2GENN,3C4FGG" 	N 8^9L M M+ 	 	KFK' -    & ,%k2    rR   c                    t          | j        j                  }|                    | j        t                                          dd                     |                                 \  }}|                    |t                                          dd                              dd                     |                    | j        t                                          dd                     |S )	aj  Get metadata routing of this object.

        Please check :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        .. versionadded:: 1.4

        Returns
        -------
        routing : MetadataRouter
            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
            routing information.
        )ownerr   )callercallee)r   method_mappingr   )r   rx  r  )r  rx  )r"   r   rA   addr   r#   r  r   )rL   routerr   r   s       rP   get_metadata_routingz!BaseSearchCV.get_metadata_routing  s      dn&=>>>

n(??..eE.JJ 	 	
 	
 	

 %%''	

(??SS00SgS..	 	 	
 	
 	
 	

W(??..eG.LL 	 	
 	
 	
 rR   c                     t          | d          r
d| j        }}n	d| j        }}t          d|g| d|j        j         gt          |          g          S )Nr   r   r9  z: )namesname_details)r   r   r   r   r   rA   rI   )rL   rN   r   s      rP   _sk_visual_block_zBaseSearchCV._sk_visual_block_  ss    4*++ 	9.0DCC($.CK;;Y09;;<i..)	
 
 
 	
rR   r_   r>  )1rA   rz   r{   r|   r   r   setr   r  r   tuplerB   r  r  rI   Realr   __annotations__r   rD   rS  rQ   propertyr   r   r   r'   r   r   r   r   r   r   r   r   r   r   r  r	  staticmethodr  r  r  r   r   r3  r{  r  __classcell__r   s   @rP   r   r     s        OO !j%))*Jss++--..//
 #T*S(+m; )3/"
G9--w|<(k!$ $D   & 
 F5 5 5 5 ^5. . . X.
 
 
 
 
9 9 9 9v \''88995 5 :95, \''	2233/ / 43/* \''88995 5 :95, \''(;<<==9 9 >=9, \''(;<<==9 9 >=9, \''44551 1 651* \''(;<<==9 9 9 >=9: 3 3 X3$ - - X-:B :B :Bx4 4 4(   \% % %2  $ \&+  } } }	 }~T T T Tl  B
 
 
 
 
 
 
rR   r   )	metaclassc            	       p     e Zd ZU dZi ej        deegiZeed<   dddddde	j
        dd	 fd

Zd Z xZS )r5   aB7  Exhaustive search over specified parameter values for an estimator.

    Important members are fit, predict.

    GridSearchCV implements a "fit" and a "score" method.
    It also implements "score_samples", "predict", "predict_proba",
    "decision_function", "transform" and "inverse_transform" if they are
    implemented in the estimator used.

    The parameters of the estimator used to apply these methods are optimized
    by cross-validated grid-search over a parameter grid.

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

    Parameters
    ----------
    estimator : estimator object
        This is assumed to implement the scikit-learn estimator interface.
        Either estimator needs to provide a ``score`` function,
        or ``scoring`` must be passed.

    param_grid : dict or list of dictionaries
        Dictionary with parameters names (`str`) as keys and lists of
        parameter settings to try as values, or a list of such
        dictionaries, in which case the grids spanned by each dictionary
        in the list are explored. This enables searching over any sequence
        of parameter settings.

    scoring : str, callable, list, tuple or dict, default=None
        Strategy to evaluate the performance of the cross-validated model on
        the test set.

        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 as values.

        See :ref:`multimetric_grid_search` for an example.

    n_jobs : int, default=None
        Number of jobs to run in parallel.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

        .. versionchanged:: v0.20
           `n_jobs` default changed from 1 to None

    refit : bool, str, or callable, default=True
        Refit an estimator using the best found parameters on the whole
        dataset.

        For multiple metric evaluation, this needs to be a `str` denoting the
        scorer that would be used to find the best parameters for refitting
        the estimator at the end.

        Where there are considerations other than maximum score in
        choosing a best estimator, ``refit`` can be set to a function which
        returns the selected ``best_index_`` given ``cv_results_``. In that
        case, the ``best_estimator_`` and ``best_params_`` will be set
        according to the returned ``best_index_`` while the ``best_score_``
        attribute will not be available.

        The refitted estimator is made available at the ``best_estimator_``
        attribute and permits using ``predict`` directly on this
        ``GridSearchCV`` instance.

        Also for multiple metric evaluation, the attributes ``best_index_``,
        ``best_score_`` and ``best_params_`` will only be available if
        ``refit`` is set and all of them will be determined w.r.t this specific
        scorer.

        See ``scoring`` parameter to know more about multiple metric
        evaluation.

        See :ref:`sphx_glr_auto_examples_model_selection_plot_grid_search_digits.py`
        to see how to design a custom selection strategy using a callable
        via `refit`.

        .. versionchanged:: 0.20
            Support for callable added.

    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,
        - integer, to specify the number of folds in a `(Stratified)KFold`,
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For integer/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.

    verbose : int
        Controls the verbosity: the higher, the more messages.

        - >1 : the computation time for each fold and parameter candidate is
          displayed;
        - >2 : the score is also displayed;
        - >3 : the fold and candidate parameter indexes are also displayed
          together with the starting time of the computation.

    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. This parameter does not affect the refit
        step, which will always raise the error.

    return_train_score : bool, default=False
        If ``False``, the ``cv_results_`` attribute will not include training
        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``

    Attributes
    ----------
    cv_results_ : dict of numpy (masked) ndarrays
        A dict with keys as column headers and values as columns, that can be
        imported into a pandas ``DataFrame``.

        For instance the below given table

        +------------+-----------+------------+-----------------+---+---------+
        |param_kernel|param_gamma|param_degree|split0_test_score|...|rank_t...|
        +============+===========+============+=================+===+=========+
        |  'poly'    |     --    |      2     |       0.80      |...|    2    |
        +------------+-----------+------------+-----------------+---+---------+
        |  'poly'    |     --    |      3     |       0.70      |...|    4    |
        +------------+-----------+------------+-----------------+---+---------+
        |  'rbf'     |     0.1   |     --     |       0.80      |...|    3    |
        +------------+-----------+------------+-----------------+---+---------+
        |  'rbf'     |     0.2   |     --     |       0.93      |...|    1    |
        +------------+-----------+------------+-----------------+---+---------+

        will be represented by a ``cv_results_`` dict of::

            {
            'param_kernel': masked_array(data = ['poly', 'poly', 'rbf', 'rbf'],
                                         mask = [False False False False]...)
            'param_gamma': masked_array(data = [-- -- 0.1 0.2],
                                        mask = [ True  True False False]...),
            'param_degree': masked_array(data = [2.0 3.0 -- --],
                                         mask = [False False  True  True]...),
            'split0_test_score'  : [0.80, 0.70, 0.80, 0.93],
            'split1_test_score'  : [0.82, 0.50, 0.70, 0.78],
            'mean_test_score'    : [0.81, 0.60, 0.75, 0.85],
            'std_test_score'     : [0.01, 0.10, 0.05, 0.08],
            'rank_test_score'    : [2, 4, 3, 1],
            'split0_train_score' : [0.80, 0.92, 0.70, 0.93],
            'split1_train_score' : [0.82, 0.55, 0.70, 0.87],
            'mean_train_score'   : [0.81, 0.74, 0.70, 0.90],
            'std_train_score'    : [0.01, 0.19, 0.00, 0.03],
            'mean_fit_time'      : [0.73, 0.63, 0.43, 0.49],
            'std_fit_time'       : [0.01, 0.02, 0.01, 0.01],
            'mean_score_time'    : [0.01, 0.06, 0.04, 0.04],
            'std_score_time'     : [0.00, 0.00, 0.00, 0.01],
            'params'             : [{'kernel': 'poly', 'degree': 2}, ...],
            }

        NOTE

        The key ``'params'`` is used to store a list of parameter
        settings dicts for all the parameter candidates.

        The ``mean_fit_time``, ``std_fit_time``, ``mean_score_time`` and
        ``std_score_time`` are all in seconds.

        For multi-metric evaluation, the scores for all the scorers are
        available in the ``cv_results_`` dict at the keys ending with that
        scorer's name (``'_<scorer_name>'``) instead of ``'_score'`` shown
        above. ('split0_test_precision', 'mean_train_precision' etc.)

    best_estimator_ : estimator
        Estimator that was chosen by the search, i.e. estimator
        which gave highest score (or smallest loss if specified)
        on the left out data. Not available if ``refit=False``.

        See ``refit`` parameter for more information on allowed values.

    best_score_ : float
        Mean cross-validated score of the best_estimator

        For multi-metric evaluation, this is present only if ``refit`` is
        specified.

        This attribute is not available if ``refit`` is a function.

    best_params_ : dict
        Parameter setting that gave the best results on the hold out data.

        For multi-metric evaluation, this is present only if ``refit`` is
        specified.

    best_index_ : int
        The index (of the ``cv_results_`` arrays) which corresponds to the best
        candidate parameter setting.

        The dict at ``search.cv_results_['params'][search.best_index_]`` gives
        the parameter setting for the best model, that gives the highest
        mean score (``search.best_score_``).

        For multi-metric evaluation, this is present only if ``refit`` is
        specified.

    scorer_ : function or a dict
        Scorer function used on the held out data to choose the best
        parameters for the model.

        For multi-metric evaluation, this attribute holds the validated
        ``scoring`` dict which maps the scorer key to the scorer callable.

    n_splits_ : int
        The number of cross-validation splits (folds/iterations).

    refit_time_ : float
        Seconds used for refitting the best model on the whole dataset.

        This is present only if ``refit`` is not False.

        .. versionadded:: 0.20

    multimetric_ : bool
        Whether or not the scorers compute several metrics.

    classes_ : ndarray of shape (n_classes,)
        The classes labels. This is present only if ``refit`` is specified and
        the underlying estimator is a classifier.

    n_features_in_ : int
        Number of features seen during :term:`fit`. Only defined if
        `best_estimator_` is defined (see the documentation for the `refit`
        parameter for more details) and that `best_estimator_` exposes
        `n_features_in_` when fit.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Only defined if
        `best_estimator_` is defined (see the documentation for the `refit`
        parameter for more details) and that `best_estimator_` exposes
        `feature_names_in_` when fit.

        .. versionadded:: 1.0

    See Also
    --------
    ParameterGrid : Generates all the combinations of a hyperparameter grid.
    train_test_split : Utility function to split the data into a development
        set usable for fitting a GridSearchCV instance and an evaluation set
        for its final evaluation.
    sklearn.metrics.make_scorer : Make a scorer from a performance metric or
        loss function.

    Notes
    -----
    The parameters selected are those that maximize the score of the left out
    data, unless an explicit score is passed in which case it is used instead.

    If `n_jobs` was set to a value higher than one, the data is copied for each
    point in the grid (and not `n_jobs` times). This is done for efficiency
    reasons if individual jobs take very little time, but may raise errors if
    the dataset is large and not enough memory is available.  A workaround in
    this case is to set `pre_dispatch`. Then, the memory is copied only
    `pre_dispatch` many times. A reasonable value for `pre_dispatch` is `2 *
    n_jobs`.

    Examples
    --------
    >>> from sklearn import svm, datasets
    >>> from sklearn.model_selection import GridSearchCV
    >>> iris = datasets.load_iris()
    >>> parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
    >>> svc = svm.SVC()
    >>> clf = GridSearchCV(svc, parameters)
    >>> clf.fit(iris.data, iris.target)
    GridSearchCV(estimator=SVC(),
                 param_grid={'C': [1, 10], 'kernel': ('linear', 'rbf')})
    >>> sorted(clf.cv_results_.keys())
    ['mean_fit_time', 'mean_score_time', 'mean_test_score',...
     'param_C', 'param_kernel', 'params',...
     'rank_test_score', 'split0_test_score',...
     'split2_test_score', ...
     'std_fit_time', 'std_score_time', 'std_test_score']
    rK   r   NTr   r   Fr   c                j    t                                          ||||||||	|
	  	         || _        d S Nr   )r   rQ   rK   )rL   r   rK   r   r   r   r   r   r   r   r   r   s              rP   rQ   zGridSearchCV.__init__  sN     	%#1 	 
	
 
	
 
	
 %rR   c                 @     |t          | j                             dS )z#Search all candidates in param_gridN)r6   rK   r  s     rP   r  zGridSearchCV._run_search!  s#    M$/::;;;;;rR   )rA   rz   r{   r|   r   r   rB   r   r  rD   rS  rQ   r  r  r  s   @rP   r5   r5     s          B
$

-$tTl$ $D    F % % % % % % %6< < < < < < <rR   r5   c                        e Zd ZU dZi ej        eeg ee	j
        ddd          gdgdZeed<   d	ddd
ddddej        dd
 fd
Zd Z xZS )r8   a9  Randomized search on hyper parameters.

    RandomizedSearchCV implements a "fit" and a "score" method.
    It also implements "score_samples", "predict", "predict_proba",
    "decision_function", "transform" and "inverse_transform" if they are
    implemented in the estimator used.

    The parameters of the estimator used to apply these methods are optimized
    by cross-validated search over parameter settings.

    In contrast to GridSearchCV, not all parameter values are tried out, but
    rather a fixed number of parameter settings is sampled from the specified
    distributions. The number of parameter settings that are tried is
    given by n_iter.

    If all parameters are presented as a list,
    sampling without replacement is performed. If at least one parameter
    is given as a distribution, sampling with replacement is used.
    It is highly recommended to use continuous distributions for continuous
    parameters.

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

    .. versionadded:: 0.14

    Parameters
    ----------
    estimator : estimator object
        An object of that type is instantiated for each grid point.
        This is assumed to implement the scikit-learn estimator interface.
        Either estimator needs to provide a ``score`` function,
        or ``scoring`` must be passed.

    param_distributions : dict or list of dicts
        Dictionary with parameters names (`str`) as keys and distributions
        or lists of parameters to try. Distributions must provide a ``rvs``
        method for sampling (such as those from scipy.stats.distributions).
        If a list is given, it is sampled uniformly.
        If a list of dicts is given, first a dict is sampled uniformly, and
        then a parameter is sampled using that dict as above.

    n_iter : int, default=10
        Number of parameter settings that are sampled. n_iter trades
        off runtime vs quality of the solution.

    scoring : str, callable, list, tuple or dict, default=None
        Strategy to evaluate the performance of the cross-validated model on
        the test set.

        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 as values.

        See :ref:`multimetric_grid_search` for an example.

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

    n_jobs : int, default=None
        Number of jobs to run in parallel.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

        .. versionchanged:: v0.20
           `n_jobs` default changed from 1 to None

    refit : bool, str, or callable, default=True
        Refit an estimator using the best found parameters on the whole
        dataset.

        For multiple metric evaluation, this needs to be a `str` denoting the
        scorer that would be used to find the best parameters for refitting
        the estimator at the end.

        Where there are considerations other than maximum score in
        choosing a best estimator, ``refit`` can be set to a function which
        returns the selected ``best_index_`` given the ``cv_results_``. In that
        case, the ``best_estimator_`` and ``best_params_`` will be set
        according to the returned ``best_index_`` while the ``best_score_``
        attribute will not be available.

        The refitted estimator is made available at the ``best_estimator_``
        attribute and permits using ``predict`` directly on this
        ``RandomizedSearchCV`` instance.

        Also for multiple metric evaluation, the attributes ``best_index_``,
        ``best_score_`` and ``best_params_`` will only be available if
        ``refit`` is set and all of them will be determined w.r.t this specific
        scorer.

        See ``scoring`` parameter to know more about multiple metric
        evaluation.

        .. versionchanged:: 0.20
            Support for callable added.

    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,
        - integer, to specify the number of folds in a `(Stratified)KFold`,
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For integer/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.

    verbose : int
        Controls the verbosity: the higher, the more messages.

        - >1 : the computation time for each fold and parameter candidate is
          displayed;
        - >2 : the score is also displayed;
        - >3 : the fold and candidate parameter indexes are also displayed
          together with the starting time of the computation.

    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'

    random_state : int, RandomState instance or None, default=None
        Pseudo random number generator state used for random uniform sampling
        from lists of possible values instead of scipy.stats distributions.
        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. This parameter does not affect the refit
        step, which will always raise the error.

    return_train_score : bool, default=False
        If ``False``, the ``cv_results_`` attribute will not include training
        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``

    Attributes
    ----------
    cv_results_ : dict of numpy (masked) ndarrays
        A dict with keys as column headers and values as columns, that can be
        imported into a pandas ``DataFrame``.

        For instance the below given table

        +--------------+-------------+-------------------+---+---------------+
        | param_kernel | param_gamma | split0_test_score |...|rank_test_score|
        +==============+=============+===================+===+===============+
        |    'rbf'     |     0.1     |       0.80        |...|       1       |
        +--------------+-------------+-------------------+---+---------------+
        |    'rbf'     |     0.2     |       0.84        |...|       3       |
        +--------------+-------------+-------------------+---+---------------+
        |    'rbf'     |     0.3     |       0.70        |...|       2       |
        +--------------+-------------+-------------------+---+---------------+

        will be represented by a ``cv_results_`` dict of::

            {
            'param_kernel' : masked_array(data = ['rbf', 'rbf', 'rbf'],
                                          mask = False),
            'param_gamma'  : masked_array(data = [0.1 0.2 0.3], mask = False),
            'split0_test_score'  : [0.80, 0.84, 0.70],
            'split1_test_score'  : [0.82, 0.50, 0.70],
            'mean_test_score'    : [0.81, 0.67, 0.70],
            'std_test_score'     : [0.01, 0.24, 0.00],
            'rank_test_score'    : [1, 3, 2],
            'split0_train_score' : [0.80, 0.92, 0.70],
            'split1_train_score' : [0.82, 0.55, 0.70],
            'mean_train_score'   : [0.81, 0.74, 0.70],
            'std_train_score'    : [0.01, 0.19, 0.00],
            'mean_fit_time'      : [0.73, 0.63, 0.43],
            'std_fit_time'       : [0.01, 0.02, 0.01],
            'mean_score_time'    : [0.01, 0.06, 0.04],
            'std_score_time'     : [0.00, 0.00, 0.00],
            'params'             : [{'kernel' : 'rbf', 'gamma' : 0.1}, ...],
            }

        NOTE

        The key ``'params'`` is used to store a list of parameter
        settings dicts for all the parameter candidates.

        The ``mean_fit_time``, ``std_fit_time``, ``mean_score_time`` and
        ``std_score_time`` are all in seconds.

        For multi-metric evaluation, the scores for all the scorers are
        available in the ``cv_results_`` dict at the keys ending with that
        scorer's name (``'_<scorer_name>'``) instead of ``'_score'`` shown
        above. ('split0_test_precision', 'mean_train_precision' etc.)

    best_estimator_ : estimator
        Estimator that was chosen by the search, i.e. estimator
        which gave highest score (or smallest loss if specified)
        on the left out data. Not available if ``refit=False``.

        For multi-metric evaluation, this attribute is present only if
        ``refit`` is specified.

        See ``refit`` parameter for more information on allowed values.

    best_score_ : float
        Mean cross-validated score of the best_estimator.

        For multi-metric evaluation, this is not available if ``refit`` is
        ``False``. See ``refit`` parameter for more information.

        This attribute is not available if ``refit`` is a function.

    best_params_ : dict
        Parameter setting that gave the best results on the hold out data.

        For multi-metric evaluation, this is not available if ``refit`` is
        ``False``. See ``refit`` parameter for more information.

    best_index_ : int
        The index (of the ``cv_results_`` arrays) which corresponds to the best
        candidate parameter setting.

        The dict at ``search.cv_results_['params'][search.best_index_]`` gives
        the parameter setting for the best model, that gives the highest
        mean score (``search.best_score_``).

        For multi-metric evaluation, this is not available if ``refit`` is
        ``False``. See ``refit`` parameter for more information.

    scorer_ : function or a dict
        Scorer function used on the held out data to choose the best
        parameters for the model.

        For multi-metric evaluation, this attribute holds the validated
        ``scoring`` dict which maps the scorer key to the scorer callable.

    n_splits_ : int
        The number of cross-validation splits (folds/iterations).

    refit_time_ : float
        Seconds used for refitting the best model on the whole dataset.

        This is present only if ``refit`` is not False.

        .. versionadded:: 0.20

    multimetric_ : bool
        Whether or not the scorers compute several metrics.

    classes_ : ndarray of shape (n_classes,)
        The classes labels. This is present only if ``refit`` is specified and
        the underlying estimator is a classifier.

    n_features_in_ : int
        Number of features seen during :term:`fit`. Only defined if
        `best_estimator_` is defined (see the documentation for the `refit`
        parameter for more details) and that `best_estimator_` exposes
        `n_features_in_` when fit.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Only defined if
        `best_estimator_` is defined (see the documentation for the `refit`
        parameter for more details) and that `best_estimator_` exposes
        `feature_names_in_` when fit.

        .. versionadded:: 1.0

    See Also
    --------
    GridSearchCV : Does exhaustive search over a grid of parameters.
    ParameterSampler : A generator over parameter settings, constructed from
        param_distributions.

    Notes
    -----
    The parameters selected are those that maximize the score of the held-out
    data, according to the scoring parameter.

    If `n_jobs` was set to a value higher than one, the data is copied for each
    parameter setting(and not `n_jobs` times). This is done for efficiency
    reasons if individual jobs take very little time, but may raise errors if
    the dataset is large and not enough memory is available.  A workaround in
    this case is to set `pre_dispatch`. Then, the memory is copied only
    `pre_dispatch` many times. A reasonable value for `pre_dispatch` is `2 *
    n_jobs`.

    Examples
    --------
    >>> from sklearn.datasets import load_iris
    >>> from sklearn.linear_model import LogisticRegression
    >>> from sklearn.model_selection import RandomizedSearchCV
    >>> from scipy.stats import uniform
    >>> iris = load_iris()
    >>> logistic = LogisticRegression(solver='saga', tol=1e-2, max_iter=200,
    ...                               random_state=0)
    >>> distributions = dict(C=uniform(loc=0, scale=4),
    ...                      penalty=['l2', 'l1'])
    >>> clf = RandomizedSearchCV(logistic, distributions, random_state=0)
    >>> search = clf.fit(iris.data, iris.target)
    >>> search.best_params_
    {'C': np.float64(2...), 'penalty': 'l1'}
    r.   Nleft)closedr   )r   r   r   r   
   Tr   r   F)
r   r   r   r   r   r   r   r   r   r   c       
             || _         || _        |
| _        t                                          |||||||	||	  	         d S r  )r   r   r   r   rQ   )rL   r   r   r   r   r   r   r   r   r   r   r   r   r   s                rP   rQ   zRandomizedSearchCV.__init__~  sb      $7 (%#1 	 
	
 
	
 
	
 
	
 
	
rR   c                 Z     |t          | j        | j        | j                             dS )z1Search n_iter candidates from param_distributionsr~   N)r7   r   r   r   r  s     rP   r  zRandomizedSearchCV._run_search  sB    ($+DDU  	
 	
 	
 	
 	
rR   )rA   rz   r{   r|   r   r   rB   r   r   r  r  r  rD   rS  rQ   r  r  r  s   @rP   r8   r8   &  s         N N`
$

-$ $d|8G,afEEEF'(	$ $ $D    F 
 
 
 
 
 
 
>
 
 
 
 
 
 
rR   r8   )Xr|   r  rd   rD  r   abcr   r   collectionsr   collections.abcr   r   r   r  r	   	functoolsr
   r   	itertoolsr   numpyrD   numpy.mar   scipy.statsr   baser   r   r   r   r   
exceptionsr   metricsr   metrics._scorerr   r   r   utilsr   r   utils._estimator_html_reprr   utils._param_validationr   r   r   utils._tagsr    utils.deprecationr!   utils.metadata_routingr"   r#   r$   r%   r&   utils.metaestimatorsr'   utils.parallelr(   r)   utils.randomr*   utils.validationr+   r,   r-   _splitr/   _validationr0   r1   r2   r3   r4   __all__r6   r7   r   r   r   r   r5   r8   rk   rR   rP   <module>r     s        ' ' ' ' ' ' ' ' # # # # # # 7 7 7 7 7 7 7 7 7 7       % % % % % % % %                                   X X X X X X X X X X X X X X ' ' ' ' ' ' # # # # # #         
 . - - - - - - - 5 5 5 5 5 5 F F F F F F F F F F " " " " " " B B B B B B              0 / / / / / . . . . . . . . 5 5 5 5 5 5 O O O O O O O O O O                    V
U
UV= V= V= V= V= V= V= V=rE E E E E E E EP
 
 
  0/ / /dK
 K
 K
 K
 K
%} K
 K
 K
 K
\d< d< d< d< d<< d< d< d<N}
 }
 }
 }
 }
 }
 }
 }
 }
 }
rR   