`L i48:dZddlZddlZddlZddlZddlmZmZddlm Z ddl m Z m Z m Z ddlmZddlmZmZddlmZdd lmZddlZdd lmZdd lmZd d lmZmZm Z m!Z!m"Z"d dl#m$Z$d dl%m&Z&d dl'm(Z(m)Z)m*Z*d dl+m,Z,m-Z-d dl.m/Z/m0Z0m1Z1d dl2m3Z3d dl4m5Z5d dl6m7Z7m8Z8m9Z9m:Z:m;Z;d dlm?Z?m@Z@d dlAmBZBd dlCmDZDmEZEmFZFddlGmHZHddlImJZJmKZKmLZLmMZMmNZNgdZOGddZPGd d!ZQd"ZRd#ZSd$ZTGd%d&eee'ZUGd(d)eUZVGd*d+eUZWy),zl The :mod:`sklearn.model_selection._search` includes utilities to fine-tune the parameters of an estimator. N)ABCMetaabstractmethod) defaultdict)IterableMappingSequence)deepcopy)partialreduce) signature)product) MaskedArray)rankdata) BaseEstimatorMetaEstimatorMixin _fit_contextclone is_classifier)NotFittedError) check_scoring)_check_multimetric_scoring_MultimetricScorerget_scorer_names)Bunchcheck_random_state) HasMethodsInterval StrOptions) _VisualBlock)get_tags)MetadataRouter MethodMapping_raise_for_params_routing_enabledprocess_routing) available_if)Paralleldelayed)sample_without_replacement)_check_method_paramscheck_is_fitted indexable)check_cv)_aggregate_score_dicts_fit_and_score_insert_error_scores_normalize_score_results!_warn_or_raise_about_fit_failures) GridSearchCV ParameterGridParameterSamplerRandomizedSearchCVc(eZdZdZdZdZdZdZy)r6a"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 `. 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|ttfs$td|dt |j t|tr|g}|D]}t|t std|d|jD]\}}t|tjr-|jdkDrtd|d|d|jt|ts t|tjtfs(td |d |d t |j d t|d k(std |d|||_y)Nz0Parameter grid should be a dict or a list, got: of type zParameter grid is not a dict ()r.zParameter 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.rz' need to be a non-empty sequence, got: ) isinstancerr TypeErrortype__name__dictitemsnpndarrayndim ValueErrorshapestrrlen param_grid)selfrKgridkeyvalues e/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/model_selection/_search.py__init__zParameterGrid.__init__hs}*w&9:B:.Qj)2235  j' *%J DdD)"@ JKK"jjl  UeRZZ0UZZ!^$.sg6!9L ?eS)BJJ12$7w?116 ;//01II u:?$7w?<z2ParameterGrid.__len__...s/qCF/sr.N)rX)rarVr s rPrbz(ParameterGrid.__len__..s. @A1G/AHHJ/ /! ; s+.)r r operatormulsumrK)rLr s @rP__len__zParameterGrid.__len__s3&(,,/ EI__   rRc|jD]}|s|dk(ricS|dz}tt|jddd\}}|Dcgc] }t |}}t j |}||k\r||z}ti}t|||D]\} }} t|| \}} || || <|cStdcc}w)aGet 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] rr.Nz ParameterGrid index out of range) rKrUrTrCrJrDproddivmod IndexError) rLindsub_gridrW values_listsv_listsizestotaloutrNnoffsets rP __getitem__zParameterGrid.__getitem__s H!8I1HC"%fX^^-=&>tt&D!E D,/;`. 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 `. 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|ttfs$td|dt |j t|tr|g}|D]k}t|t stdj||D]:}t||trt||dr'td|d||dm||_ ||_ ||_ y)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>rrr?r@rArBformathasattrn_iterr|param_distributions)rLrrr|distrNs rPrQzParameterSampler.__init__ s-/BC,/y+,5568  )7 3$7"7 ' DdD)AHHN !$s)X6wIu@$7w?448I;aA    (#6 rRc:td|jDS)Nc3\K|]$}td|jD&yw)c36K|]}t|d yw)r~N)rr`s rPrbz;ParameterSampler._is_all_lists...-s=!GAu%%=sN)allrX)rars rPrbz1ParameterSampler._is_all_lists..,s)  =t{{}= = s*,)rrrLs rP _is_all_listszParameterSampler._is_all_lists+s" 00   rRc#Kt|j}|jrxt|j}t |}|j }||kr,tjd||j |fzt|}t|||D] }|| yt|j D]}|j|j}t|j}t} |D]G\} } t!| dr| j#|| | <(| |j%t | | | <I| yw)Nz}The total space of parameters %d is smaller than n_iter=%d. Running %d iterations. For exhaustive searches, use GridSearchCV.r{r~)rr|rr6rrJrwarningswarn UserWarningr*rangechoicerTrCrBrr~randint) rLrngrK grid_sizeri_rrCrZkrYs rPr[zParameterSampler.__iter__1s: !2!23    &t'?'?@JJI[[F6! 25> Y4WX  #/ 6PST $ m# $4;;' zz$":":;tzz|,!;DAqq%($%EEsE$;q $%ckk#a&&9$:q ;   sEE c|jr4tt|j}t |j |S|j S)z&Number of points that will be sampled.)rrJr6rminr)rLrs rPrfzParameterSampler.__len__Ts>    M$*B*BCDIt{{I. .;; rR)rArvrwrxrQrr[rfryrRrPr7r7s$5nEI7< !FrRr7cf|js%tdt|jd|dy)NzThis 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)refitAttributeErrorr@rA) search_cvattrs rP _check_refitr]sA ??DO,,-."V$' '   rRcfd}|S)ayCheck 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`. ct|t|drt|jyt|jy)Nbest_estimator_T)rrgetattrr estimator)rLrs rPcheckz$_search_estimator_has..checkrs<T4 4* + D(($ /%rRry)rrs` rP_search_estimator_hasrgs LrRc#Kt|}tt}t|D](\}}|j D]\}}||d|z|<*|j D]\}}t |j } tj| } | jjdk7r| jdk(r | jnt} ttj|| d} |j D] \} }|| | < || fy#t$rtjt} YlwxYww)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'`. zparam_%sUr.dtypeT)maskN)rJrrB enumeraterClistrXrDarrayrkindrFobjectrGrempty)candidate_params n_candidates param_resultscand_idxrZnamerOrN param_result param_listarr arr_dtypemaindexs rP"_yield_masked_array_for_each_paramrs: '(L%M%&67?&!<<> ?KD%9>M*t+ ,X 6 ??+002\,--/0  Y((:&C&)YY^^s%:sxx1} RXI,i@t L(..0 LE5BuI Bi1 )(I  )s+BEDBE"D?<E>D??Ec eZdZUdZedggeeeee e e dge jdgdeegdgdge jegedhe jgdgd Ze ed <eddd dd d ej(d d dZedZfdZd.dZeeddZeeddZeeddZeeddZeeddZ eeddZ!eeddZ"ed Z#ed!Z$d"Z%d#Z&e'd$Z(d%Z)d&Z*d'Z+e,d()d.d*Z-d.d+Z.d,Z/d-Z0xZ1S)/ BaseSearchCVzEAbstract base class for hyper parameter search with cross-validation.fitNboolean cv_objectverboseraise rscoringn_jobsrcvr pre_dispatch error_scorereturn_train_score_parameter_constraintsTr2*n_jobsrrrrrrrrc||_||_||_||_||_||_||_||_| |_yr_) rrrrrrrrr) rLrrrrrrrrrs rPrQzBaseSearchCV.__init__sF "   (&"4rRc.|jjSr_)r_estimator_typers rPrzBaseSearchCV._estimator_types~~---rRct|}t|j}|j|_t |j |_t |j|_|jj|j_ |jj|j_ |j|_ |Sr_) super__sklearn_tags__r!restimator_typer classifier_tagsregressor_tags input_tagspairwisesparsearray_api_support)rLtagssub_estimator_tags __class__s rPrzBaseSearchCV.__sklearn_tags__sw')%dnn50??'(:(J(JK&'9'H'HI#5#@#@#I#I !3!>!>!E!E!3!E!E rRc *t|dt|t||dtrt |dfi|j d}n t }|jtd|jzt|jt rG|jr|j|j}n |j}||j||fi|S|j|j||fi|}|jr||j}|S)aSReturn 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 ` for more details. Returns ------- score : float The score defined by ``scoring`` if provided, and the ``best_estimator_.score`` method otherwise. scorezNNo score function explicitly defined, and the estimator doesn't provide one %s) rr,r$r%r&scorerrBscorer_rGrr> multimetric_r)rLXyrZ score_paramsrrs rPrzBaseSearchCV.scores> T7#&$0  *4CFCJJ7SL6L << ;=A=Q=QR  dllD )  djj1$..1E E E T111aH<H   $**%E rR score_samplescNt||jj|S)aCall 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,rrrLrs rPrzBaseSearchCV.score_samples+#( ##11!44rRpredictcNt||jj|S)aCall 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,rrrs rPrzBaseSearchCV.predictBs#& ##++A..rR predict_probacNt||jj|S)aCall 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,rrrs rPrzBaseSearchCV.predict_probaXrrRpredict_log_probacNt||jj|S)aCall 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,rrrs rPrzBaseSearchCV.predict_log_probao#( ##55a88rRdecision_functioncNt||jj|S)aCall 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,rrrs rPrzBaseSearchCV.decision_functionrrR transformcNt||jj|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,rrrs rPrzBaseSearchCV.transforms#& ##--a00rRinverse_transformcNt||jj|S)aVCall 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. Returns ------- X_original : {ndarray, sparse matrix} of shape (n_samples, n_features) Result of the `inverse_transform` function for `X` based on the estimator with the best found parameters. )r,rrrs rPrzBaseSearchCV.inverse_transforms#& ##55a88rRc t||j jS#t$r4}tdj|jj |d}~wwxYw)z_Number of features seen during :term:`fit`. Only available when `refit=True`. z*{} object has no n_features_in_ attribute.N)r,rrrrrArn_features_in_)rLnfes rPrzBaseSearchCV.n_features_in_sb  D !##222  <CCNN++   s # A /AA cPtd||jjS)zcClass labels. Only available when `refit=True` and the estimator is a classifier. classes_)rrrrs rPrzBaseSearchCV.classes_s& *j)$/##,,,rRctd)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 Successive Halving 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.)NotImplementedErrorrLevaluate_candidatess rP _run_searchzBaseSearchCV._run_searchst""@AArRcd|jd}t|jtxr|j|v}|jdur$|s!t|js t |yyy)z2Check `refit` is compatible with `scores` is validaFor 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)rr>rIcallablerG)rLscoresmultimetric_refit_msgvalid_refit_dicts rP_check_refit_for_multimetricz)BaseSearchCV._check_refit_for_multimetric!s{ 89= ~F   &djj#6O4::;O JJe #$TZZ(23 3)% $rRct|rP||}t|tjs t d|dks|t |dk\r t d|S|d|j}|S)z8Select index of the best combination of hyperparemeters.z&best_index_ returned is not an integerrrZzbest_index_ index out of range rank_test_)rr>numbersIntegralr?rJrkargmin)r refit_metricresults best_indexs rP_select_best_indexzBaseSearchCV._select_best_index5s E?wJj'*:*:; HIIA~s783D/E!E !ABB!:l^!<=DDFJrRcd}t|jr|j}||fS|jt|jtr$t |j |j}||fSt |j |j}|j||j}t||jdk(}||fS)zGet the scorer(s) to be used. This is used in ``fit`` and ``get_metadata_routing``. Returns ------- scorers, refit_metric rr)scorers raise_exc) rrr>rIrrrrrrr)rLr rs rP _get_scorerszBaseSearchCV._get_scorersDs DLL !llG $$\\ !Z c%B#DNNDLLAG $$1NG  - -g 6::L(D,<,<,GG $$rRc |j\}}t|trb|jj D]5\}}|j rt jd|d|d|d7|j St|dr|j }ndt|jv}|st jd|d|d|S)Nz The scoring =z` does not support sample_weight, which may lead to statistically incorrect results when fitting z with sample_weight. _accept_sample_weight sample_weight) rr>r_scorersrCrrrrr parameters)rLrrrraccepts rP#_check_scorers_accept_sample_weightz0BaseSearchCV._check_scorers_accept_sample_weight]s&&(  g1 2 ' 0 0 6 6 8  f335MM&tfAfX6##'&(=? 002 2 73 4224F$ '(:(E(EEF MMwi(& 57   rRcRtrt|dfi|}|S|j}|jdd}t t |t d|it i}|j d,|j r|d|jjd<|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``. rgroupsN)r)split)r)rsplitterrr) r%r&copypoprgetrrr)rLrZ routed_paramsrs rP_get_routed_params_for_fitz'BaseSearchCV._get_routed_params_for_fitxs  +D%B6BM"[[]FZZ$/F!F+h%782M ?+7<<>>D_>U $$**?;rRF)prefer_skip_nested_validationc B j}j\}}t\t|}j |t j t|jfijjtjtjjt|jj j"j$j&dddj(j* i5g g t-t. d f d }j1| d d }t3|t_t7j8r)j4rj;|j<}dddj<s j4shj?j<|_ t7j<sd |j@_!d j@_"j<rtjFditjDd _$tKjJ} 3jHj fijj n1jHj fijj tKjJ} | | z _&tOjHdrjHjP_(t3|tRr|jT_+n|_+_,_-S#1swYxYw)aRun 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)rrTF) r fit_paramsrrreturn_n_test_samples return_timesreturn_parametersrrNc : |xs }t|}t|jdkDrtdj z fdt t |t |jfijjD}t|dkr tdt|zk7r'tdj t|zt|jtjrt|jj| j||,|j!D]\}} |j|j# S)Nrz@Fitting {0} folds for each of {1} candidates, totalling {2} fitsc 3K|];\\}}\}\}}ttt f|||| f| fd=yw))traintestrsplit_progresscandidate_progressN)r)r1r) rarr split_idxr-r.rbase_estimatorfit_and_score_kwargsrn_splitsrs rPrbz@BaseSearchCV.fit..evaluate_candidates..srK.:0JMUD,GN+n- $!#-(18'<,4l+C / sAAr.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 {})rrJrprintrr rrrrGr4rrrr2extendrC_format_results)rr more_resultsrrrNrOrrall_candidate_paramsall_more_resultsall_outr2cv_origr3r4parallelr r"rLrs @rPrz-BaseSearchCV.fit..evaluate_candidatess]7#'(8#9 "#34 <.>?$++,<=s#+&2&8&8&:< U(-44U;<..((G=MrRr test_scores mean_test_rZ)safefeature_names_in_)NNry).rrr-r+r#r/rr get_n_splitsrrrr(rrrBrrrrrrrrrr>rrrrrr best_index_ best_score_ best_params_ set_paramsrtime refit_time_rrArrr cv_results_ n_splits_)rLrrrZrrr rfirst_test_scorerefit_start_timerefit_end_timer9r:r;r2r<r3r4r=r r"s``` @@@@@@@@@@rPrzBaseSearchCV.fits5LNN $ 1 1 3A1%a777? 477A- 2JK'7''1M 0F0F0L0LMt~~.4;;T=N=NO#$..22&--33#66"&#((LL  R *#% G*40 A A A F   0 1 'qz-8  *+;T BD  %$*;*;112BC#zz eR *n ::T..#66 L' D DJJ'$+Z ~+F#G$$$ !( 1$2B2B CD  :: $D5#8#C#C$))6$D  $yy{ }($$((AM1H1H1L1LM($$((Jm.E.E.I.IJ!YY[N-0@@D t++-@A)-)=)=)O)O& g1 2"++DL"DL"! AR *R *s 7BNNc t| t|}t|xsijD]\}}t j ||<d fd }|d|d|d|dt |D] \}} | |< |d<t|d} |jrt|d} | D]3} |d| z| | ddd |js#|d | z | d 5S) Nctj|tjj }|r!t D]}|dd|f d||fz<tj |d|}| d|z<|j dr\tjtj|r3tjd|jd d d |t tjtj ||ddtjfz d zd|}| d|z<|rtj|j!r&tj"|tj$}n\tj&|dz } tj(|| }t+| dj-tj$d}| d|z<yy)z;A small helper to store the scores/times to the cv_results_rNz split%d_%sr.)axisweightszmean_%s)train_test_zOne or more of the rrz scores are non-finite: )categoryrzstd_%s)nanr)methodF)rzrank_%s)rDrfloat64reshaperaverage startswithanyisfiniterrrrsqrtnewaxisisnanr ones_likeint32nanmin nan_to_numrastype) key_namerrQsplitsrankr1 array_means array_stds rank_resultmin_array_meansrr4r s rP_storez,BaseSearchCV._format_results.._store_sHHU"**5==lHUE!&xXIDI!Y,DWGLIx+@@AX**UGDK,7GI( )""#67BFF[))= -hnnS.A!.D-EF++6-9)  [BJJ77A=AwJ ,6GHx' (88K(,,."$,,{"(("KK&(ii & train_scoresztest_%sT)rfrgrQztrain_%s)rf)NFF) rJr0rBrCrDasarrayrr3r)rLrr4rrr8rNvalrlparamrtest_scores_dicttrain_scores_dict scorer_namerr s ` @@rPr7zBaseSearchCV._format_resultsUs*+, $S)|)r*  +HC::c?GCL + - <^ z3z?+|S./;` on how the routing mechanism works. .. versionadded:: 1.4 Returns ------- routing : MetadataRouter A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating routing information. )ownerr)callercallee)rmethod_mappingr)rrzr)rrz)r"rrAaddrr#rr)rLrouterrrs rPget_metadata_routingz!BaseSearchCV.get_metadata_routings dnn&=&=> nn(?..eE.J  %%'  (? SS 0 SgS .   WW(?..eG.L   rRct|drd|j}}nd|j}}td|g|d|jj gt |gS)Nrrr=z: )names name_details)rrrr rrArI)rLrNrs rP_sk_visual_block_zBaseSearchCV._sk_visual_block_sf 4* +.0D0DC($..C  KU"Y0099:;<i.)   rRr_)2rArvrwrxrrsetrrrtuplerBrr rIRealr__annotations__rrDrUrQpropertyrrrr'rrrrrrrrrrrr staticmethodrrrr#rrr7r}r __classcell__rs@rPrrsHO!%)* s+-. /       ##T*S(+m; ))3/"G9-w||<(k!$D&  FF55... 9v'895:5,' 23/4/*'895:5,'(;<=9>9,'(;<=9>9,' 45161*'(;<=9>9*33$--:Bx4(  %264&+} }~TlB  rRr) metaclassc eZdZUdZiej deegiZeed<dddddde jdd fd Z d Z xZ S) r5a8Exhaustive 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 `. 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_string_names`); - a callable (see :ref:`scoring_callable`) that returns a single value; - `None`, the `estimator`'s :ref:`default evaluation criterion ` is used. 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 ` 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`. See :ref:`this example ` for an example of how to use ``refit=callable`` to balance model complexity and cross-validated score. .. 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 ` 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 (``'_'``) 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'] rKrNTrrFrc Dt ||||||||| |  ||_yNr)rrQrK) rLrrKrrrrrrrrrs rPrQzGridSearchCV.__init__(s; %#1  %rRc:|t|jy)z#Search all candidates in param_gridN)r6rKrs rPrzGridSearchCV._run_searchCsM$//:;rR)rArvrwrxrrrBrrrDrUrQrrrs@rPr5r5s]FP $  - -$tTl$D FF %6`. .. 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_string_names`); - a callable (see :ref:`scoring_callable`) that returns a single value; - `None`, the `estimator`'s :ref:`default evaluation criterion ` is used. 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 ` 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. See :ref:`this example ` for an example of how to use ``refit=callable`` to balance model complexity and cross-validated score. .. 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 ` 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 `. 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 (``'_'``) 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.195...), 'penalty': 'l1'} r.Nleft)closedr|)rrr|r TrrF) rrrrrrrr|rrc `||_||_| |_t |||||||| | |  yr)rrr|rrQ)rLrrrrrrrrrr|rrrs rPrQzRandomizedSearchCV.__init__sI $7  ( %#1  rRch|t|j|j|jy)z1Search n_iter candidates from param_distributionsr{N)r7rrr|rs rPrzRandomizedSearchCV._run_searchs) (($++DDUDU  rR)rArvrwrxrrrBrrrr rrDrUrQrrrs@rPr8r8Hs~Un $  - -$ $d|G,,afEF'( $D FF  > rRr8)XrxrrcrGrabcrr collectionsrcollections.abcrrrrr functoolsr r inspectr itertoolsr numpyrDnumpy.mar scipy.statsrbaserrrrr exceptionsrmetricsrmetrics._scorerrrrutilsrrutils._param_validationrrrutils._repr_html.estimatorr utils._tagsr!utils.metadata_routingr"r#r$r%r&utils.metaestimatorsr'utils.parallelr(r) utils.randomr*utils.validationr+r,r-_splitr/ _validationr0r1r2r3r4__all__r6r7rrrrr5r8ryrRrPrs '#77% XX'# .FF5"0.5OO VV=V=rEEP 0/df  %}f  Rk<<k<\ D D rR