`L ivdZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddl m Z ddl ZddlmZddlmZd d lmZmZd d lmZmZd d lmZmZd d lmZd dlm Z d dl!m"Z"m#Z#m$Z$m%Z%d dl&m'Z'm(Z(d dl)m*Z*m+Z+m,Z,m-Z-m.Z.d dl/m0Z0m1Z1m2Z2m3Z3d dl4m5Z5d dl6m7Z7m8Z8d dl9m:Z:m;Z;ddldZ?dZ@e.e*dgddgddgddge-eAeeBeCeDeEdgdge+dgdgeEdge+eFgd gd gd ge-d!he gd"d#$ d^ddddddd%d#d#d#ejd& d'ZHd(ZId_d)ZJd*ZKe.e*dgddgddgddge-eAeeBdgdge+dgdgeEdge+eFdge-d!he gd+ d#$ d^ddddddd%ejd,d-ZLd#d#d#d#d#ddejd.d/ZMd`d0ZNe.e*dd1ggddggd2ddgdge+dgdgeEdge+eFdge-hd3gd4 d#$ d^dddddd%d1d5d6ZOd7ZPd8ZQd9ZRe.e*dgddgddgddgdge,e+ddd:;ge+dgdddddddd? d@ZSdAZTdBZUe.idCe*dggdDddgdEddgdFddgdGdgdHdgdIe-eAeeBdgdJd gdKe+dgdLe+eFgddgdMd gdRvF"6* Mc4|tr tdyy)Nz`groups` can only be passed if metadata routing is not enabled via `sklearn.set_config(enable_metadata_routing=True)`. When routing is enabled, pass `groups` alongside other metadata via the `params` argument instead.)rr0)r7s r9r4r4Xs( .0   1r;fit array-like sparse matrix cv_objectverbosebooleanraise) estimatorXyr7scoringcvn_jobsrAr6 pre_dispatchreturn_train_scorereturn_estimatorreturn_indices error_scoreF)prefer_skip_nested_validationz2*n_jobs) r7rGrHrIrAr6rJrKrLrMrNc   t|t\|in|}t|t}t | dk(t rt dj|tjdd  jtjdd  jtjdd  } t|dfi|n?ttd|i_t|_ti_|j&fij j&}| r t)|}t+|| }| f d|D}t-| t/|r t1| t3|}i}|d|d<|d|d< r|d|d<| ri|d<t5|\|dd<|dd<t7|d} rt7|d}|D]}|||d|z< sd|z}|||<|S#t$r@}tt|jdd|j|jd}~wwxYw) a2!Evaluate metric(s) by cross-validation and also record fit/score times. Read more in the :ref:`User Guide `. Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : {array-like, sparse matrix} of shape (n_samples, n_features) The data to fit. Can be for example a list, or an array. y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None The target variable to try to predict in the case of supervised learning. groups : array-like of shape (n_samples,), default=None Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a "Group" :term:`cv` instance (e.g., :class:`GroupKFold`). .. versionchanged:: 1.4 ``groups`` can only be passed if metadata routing is not enabled via ``sklearn.set_config(enable_metadata_routing=True)``. When routing is enabled, pass ``groups`` alongside other metadata via the ``params`` argument instead. E.g.: ``cross_validate(..., params={'groups': groups})``. scoring : str, callable, list, tuple, or dict, default=None Strategy to evaluate the performance of the `estimator` across cross-validation splits. 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 a values. See :ref:`multimetric_grid_search` for an example. cv : int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 5-fold cross validation, - int, to specify the number of folds in a `(Stratified)KFold`, - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. For int/None inputs, if the estimator is a classifier and ``y`` is either binary or multiclass, :class:`StratifiedKFold` is used. In all other cases, :class:`KFold` is used. These splitters are instantiated with `shuffle=False` so the splits will be the same across calls. Refer :ref:`User Guide ` for the various cross-validation strategies that can be used here. .. versionchanged:: 0.22 ``cv`` default value if None changed from 3-fold to 5-fold. n_jobs : int, default=None Number of jobs to run in parallel. Training the estimator and computing the score are parallelized over the cross-validation splits. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. verbose : int, default=0 The verbosity level. params : dict, default=None Parameters to pass to the underlying estimator's ``fit``, the scorer, and the CV splitter. .. versionadded:: 1.4 pre_dispatch : int or str, default='2*n_jobs' Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - An int, giving the exact number of total jobs that are spawned - A str, giving an expression as a function of n_jobs, as in '2*n_jobs' return_train_score : bool, default=False Whether to include train scores. Computing training scores is used to get insights on how different parameter settings impact the overfitting/underfitting trade-off. However computing the scores on the training set can be computationally expensive and is not strictly required to select the parameters that yield the best generalization performance. .. versionadded:: 0.19 .. versionchanged:: 0.21 Default value was changed from ``True`` to ``False`` return_estimator : bool, default=False Whether to return the estimators fitted on each split. .. versionadded:: 0.20 return_indices : bool, default=False Whether to return the train-test indices selected for each split. .. versionadded:: 1.3 error_score : 'raise' or numeric, default=np.nan Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. .. versionadded:: 0.20 Returns ------- scores : dict of float arrays of shape (n_splits,) Array of scores of the estimator for each run of the cross validation. A dict of arrays containing the score/time arrays for each scorer is returned. The possible keys for this ``dict`` are: ``test_score`` The score array for test scores on each cv split. Suffix ``_score`` in ``test_score`` changes to a specific metric like ``test_r2`` or ``test_auc`` if there are multiple scoring metrics in the scoring parameter. ``train_score`` The score array for train scores on each cv split. Suffix ``_score`` in ``train_score`` changes to a specific metric like ``train_r2`` or ``train_auc`` if there are multiple scoring metrics in the scoring parameter. This is available only if ``return_train_score`` parameter is ``True``. ``fit_time`` The time for fitting the estimator on the train set for each cv split. ``score_time`` The time for scoring the estimator on the test set for each cv split. (Note: time for scoring on the train set is not included even if ``return_train_score`` is set to ``True``). ``estimator`` The estimator objects for each cv split. This is available only if ``return_estimator`` parameter is set to ``True``. ``indices`` The train/test positional indices for each cv split. A dictionary is returned where the keys are either `"train"` or `"test"` and the associated values are a list of integer-dtyped NumPy arrays with the indices. Available only if `return_indices=True`. See Also -------- cross_val_score : Run cross-validation for single metric evaluation. cross_val_predict : Get predictions from each split of cross-validation for diagnostic purposes. sklearn.metrics.make_scorer : Make a scorer from a performance metric or loss function. Examples -------- >>> from sklearn import datasets, linear_model >>> from sklearn.model_selection import cross_validate >>> from sklearn.metrics import make_scorer >>> from sklearn.metrics import confusion_matrix >>> from sklearn.svm import LinearSVC >>> diabetes = datasets.load_diabetes() >>> X = diabetes.data[:150] >>> y = diabetes.target[:150] >>> lasso = linear_model.Lasso() Single metric evaluation using ``cross_validate`` >>> cv_results = cross_validate(lasso, X, y, cv=3) >>> sorted(cv_results.keys()) ['fit_time', 'score_time', 'test_score'] >>> cv_results['test_score'] array([0.3315057 , 0.08022103, 0.03531816]) Multiple metric evaluation using ``cross_validate`` (please refer the ``scoring`` parameter doc for more information) >>> scores = cross_validate(lasso, X, y, cv=3, ... scoring=('r2', 'neg_mean_squared_error'), ... return_train_score=True) >>> print(scores['test_neg_mean_squared_error']) [-3635.5 -3573.3 -6114.7] >>> print(scores['train_r2']) [0.28009951 0.3908844 0.22784907] N classifierrC)rG raise_excr*ownerr=splitcallercalleesplittermethod_mappingrDr\scorescorerr\zcross_validate.fitmessageunrequested_params routed_paramsr7rVr=r^rIrArJc3 K|][\}}ttt || djjj j d]yw)NT) r`traintestrA parametersr5 score_paramsrK return_timesrLrNr#_fit_and_scorer rDr=r`r^) .0rjrkrErNrDrLrKrdscorersrArFs r9 z!cross_validate..sw" E4!  )  $..22&--331-#  sA!A$fit_time score_timerDindicesrjrk test_scores train_scoresztest_%sztrain_%s)r4rr'r rrraddrr r strreplacercrdrr[rDr`rVlistr"!_warn_or_raise_about_fit_failurescallable_insert_error_scores_aggregate_score_dictszip_normalize_score_results)rDrErFr7rGrHrIrAr6rJrKrLrMrNrouterervparallelresultsrettest_scores_dicttrain_scores_dictnamekeyrdrrs``` ` `` ` @@r9r*r*bsh#6* Q?DAq>RvF "aM)$< =B7{g/EG !1 2 S,22%2PS# -22%2N  S,22%2P " +FEDVDM !&h-?!@ "'F"3 $2 bhhq!<}55;;>Jc2d}g}t|D]$\}}|d|j|| |d}&t|trL|Dcic]}||}}|D]6}|j ||d<d||vs!|j ||d<8yycc}w)zInsert error in `results` by replacing them inplace with `error_score`. This only applies to multimetric scores because `_fit_and_score` will handle the single metric case. N fit_errorrwrx) enumerateappend isinstancedictcopy)rrNsuccessful_scorefailed_indicesiresultrformatted_errors r9rrs Nw'5 6 +  *  ! !! $  %%m4  5 "D)9IJ4,JJ DA(7(<(<(>GAJ} %+-<-A-A-C >* D*Js BcFt|dtr t|S||iS)z:Creates a scoring dictionary based on the type of `scores`r)rrr)scoresscaler_score_keys r9rrs&&)T"%f-- f %%r;c\ |Dcgc] }|d |d}}|rt|}t|}t|}d dj fd|jD}||k(rd|d|}t |d|d|d|d |} t j | tyycc}w) NrzQ--------------------------------------------------------------------------------  c36K|]\}}|d|yw)z' fits failed with the following error: N)rqerrorn delimiters r9rsz4_warn_or_raise_about_fit_failures..s-' qk!DUG L' sz All the z fits failed. It is very likely that your model is misconfigured. You can try to debug the error by setting error_score='raise'. Below are more details about the failures: z fits failed out of a total of zO. The score on these train-test partitions for these parameters will be set to z. If these failures are not expected, you can try to debug them by setting error_score='raise'. Below are more details about the failures: )lenrjoinitemsr0r1r2r ) rrNr fit_errorsnum_failed_fitsnum_fitsfit_errors_counterfit_errors_summaryall_fits_failed_messagesome_fits_failed_messagers @r9r}r}s*1 &VK5H5T{Jj/w<$Z0# !YY' .446'   h &XJ'?@R>RT $ 45 5_%%DXJO##.-0?@R>R T % MM24D E9s B)B) rDrErFr7rGrHrIrAr6rJrN)r7rGrHrIrAr6rJrNc Vt||} t||||d| i||||| |  } | dS)ahEvaluate a score by cross-validation. Read more in the :ref:`User Guide `. Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : {array-like, sparse matrix} of shape (n_samples, n_features) The data to fit. Can be for example a list, or an array. y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None The target variable to try to predict in the case of supervised learning. groups : array-like of shape (n_samples,), default=None Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a "Group" :term:`cv` instance (e.g., :class:`GroupKFold`). .. versionchanged:: 1.4 ``groups`` can only be passed if metadata routing is not enabled via ``sklearn.set_config(enable_metadata_routing=True)``. When routing is enabled, pass ``groups`` alongside other metadata via the ``params`` argument instead. E.g.: ``cross_val_score(..., params={'groups': groups})``. scoring : str or callable, default=None Strategy to evaluate the performance of the `estimator` across cross-validation splits. - str: see :ref:`scoring_string_names` for options. - callable: a scorer callable object (e.g., function) with signature ``scorer(estimator, X, y)``, which should return only a single value. See :ref:`scoring_callable` for details. - `None`: the `estimator`'s :ref:`default evaluation criterion ` is used. Similar to the use of `scoring` in :func:`cross_validate` but only a single metric is permitted. cv : int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - `None`, to use the default 5-fold cross validation, - int, to specify the number of folds in a `(Stratified)KFold`, - :term:`CV splitter`, - An iterable that generates (train, test) splits as arrays of indices. For `int`/`None` inputs, if the estimator is a classifier and `y` is either binary or multiclass, :class:`StratifiedKFold` is used. In all other cases, :class:`KFold` is used. These splitters are instantiated with `shuffle=False` so the splits will be the same across calls. Refer :ref:`User Guide ` for the various cross-validation strategies that can be used here. .. versionchanged:: 0.22 `cv` default value if `None` changed from 3-fold to 5-fold. n_jobs : int, default=None Number of jobs to run in parallel. Training the estimator and computing the score are parallelized over the cross-validation splits. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. verbose : int, default=0 The verbosity level. params : dict, default=None Parameters to pass to the underlying estimator's ``fit``, the scorer, and the CV splitter. .. versionadded:: 1.4 pre_dispatch : int or str, default='2*n_jobs' Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - ``None``, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs - An int, giving the exact number of total jobs that are spawned - A str, giving an expression as a function of n_jobs, as in '2*n_jobs' error_score : 'raise' or numeric, default=np.nan Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. .. versionadded:: 0.20 Returns ------- scores : ndarray of float of shape=(len(list(cv)),) Array of scores of the estimator for each run of the cross validation. See Also -------- cross_validate : To run cross-validation on multiple metrics and also to return train scores, fit times and score times. cross_val_predict : Get predictions from each split of cross-validation for diagnostic purposes. sklearn.metrics.make_scorer : Make a scorer from a performance metric or loss function. Examples -------- >>> from sklearn import datasets, linear_model >>> from sklearn.model_selection import cross_val_score >>> diabetes = datasets.load_diabetes() >>> X = diabetes.data[:150] >>> y = diabetes.target[:150] >>> lasso = linear_model.Lasso() >>> print(cross_val_score(lasso, X, y, cv=3)) [0.3315057 0.08022103 0.03531816] rGr^r test_score)rr*) rDrErFr7rGrHrIrAr6rJrNr` cv_resultss r9r)r)sNx9g 6F &! ! J l ##r;)rKreturn_parametersreturn_n_test_samplesrnrLsplit_progresscandidate_progressrNcbt|\}}t|}|j|||j||}}t|tj s|dk7r t dd}|dkDr.|d|dd zd |d }|r|d kDr|d |dd zd |d z }|d kDr*d}n%t}d jfd|D}|d kDr&d|d}t|dt|z dz||ni}t|||}| | ni} t|| |}t|| |}|jd*itd}tj}t||||\}}t|||||\}}i} ||j |fi|n|j ||fi|d| d<tj|z }!t#||||||}"tj|z |!z }#| rt#||||||}$ |d kDr|#|!z}&d|d}'|rdndz}(|dkDret"t.r8t|"D])})|(d|)dz }(| r$|)}*|(d|*dd z }(|(d|"|)ddz }(+n|(dz }(| r|(d $dd!|"ddz }(n|(|"dz }(|(d"t1j2|&z }(|'ddt|'z t|(z zz }'|'|(z }'t|'"| d#<| r$| d$<| rt5|| d%<| r |!| d&<|#| d'<| r| d(<|r|| d)<| S#t$$rtj|z }!d}#|dk(rt|tj rIt|t&r3|j(D%cic]}%|%|ncc}%w}"}%| r|"j+}$n|}"| r|}$t-| d<YwxYw)+aW Fit estimator and compute scores for a given dataset split. Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : array-like of shape (n_samples, n_features) The data to fit. y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None The target variable to try to predict in the case of supervised learning. scorer : A single callable or dict mapping scorer name to the callable If it is a single callable, the return value for ``train_scores`` and ``test_scores`` is a single float. For a dict, it should be one mapping the scorer name to the scorer callable object / function. The callable object / fn should have signature ``scorer(estimator, X, y)``. train : array-like of shape (n_train_samples,) Indices of training samples. test : array-like of shape (n_test_samples,) Indices of test samples. verbose : int The verbosity level. error_score : 'raise' or numeric, default=np.nan Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. parameters : dict or None Parameters to be set on the estimator. fit_params : dict or None Parameters that will be passed to ``estimator.fit``. score_params : dict or None Parameters that will be passed to the scorer. return_train_score : bool, default=False Compute and return score on training set. return_parameters : bool, default=False Return parameters that has been used for the estimator. split_progress : {list, tuple} of int, default=None A list or tuple of format (, ). candidate_progress : {list, tuple} of int, default=None A list or tuple of format (, ). return_n_test_samples : bool, default=False Whether to return the ``n_test_samples``. return_times : bool, default=False Whether to return the fit/score times. return_estimator : bool, default=False Whether to return the fitted estimator. Returns ------- result : dict with the following attributes train_scores : dict of scorer name -> float Score on training set (for all the scorers), returned only if `return_train_score` is `True`. test_scores : dict of scorer name -> float Score on testing set (for all the scorers). n_test_samples : int Number of test samples. fit_time : float Time spent for fitting in seconds. score_time : float Time spent for scoring in seconds. parameters : dict or None The parameters that have been evaluated. estimator : estimator object The fitted estimator. fit_error : str or None Traceback str if the fit failed, None if the fit succeeded. )rrCzerror_score must be the string 'raise' or a numeric value. (Hint: if using 'raise', please make sure that it has been spelled correctly.)r N rr&/ z; z, c32K|]}|d|yw)=Nr)rqkrls r9rsz!_fit_and_score..>s "OaaS*Q-#9"Osz[CVz] START Pr/r6rvF)saferz] END ;z: (ztrain=z.3fztest=)z, score=z(train=z, test=z total time=rwrxn_test_samplesrtrurlrDr)rrasarrayrnumbersNumberr0sortedrprintrr$ set_paramsr timer!r=_score Exceptionr_scorersrrrrshort_format_timer%)+rDrErFr`rjrkrArlr5rmrKrrrnrLrrrNxp_X_device progress_msg params_msg sorted_keys start_msgscore_params_trainscore_params_test start_timeX_trainy_trainX_testy_testrrtrwrurxr total_timeend_msg result_msg scorer_name scorer_scoress+ ` r9rprps^ ! EBayH**U8*4bjjhj6W4E k7>> 2{g7M "  L{  %~a0145Q~a7H6IJL 'A+ b!3A!6!: ;1=OPQ=RNFF F! ? IMM' 0Z 0 IMM'7 9j 9&#{99;+ vvv/@+ YY[:-8 !7GV5GL{(*  ~V,*3"= Q;+t,#)+#6JKAk]#"66J)(4[(A "}S.A&DD E+k*B3)Gq"IIJ Jj( %GL+=W[QTDUUV"WWJ[$56J V%=%=j%I$JKK  3"s7|+c*o=>>: g'F=!-~#/#7 %z)|)|'{ ME +99;+ ' !   W^^ 4&"45=C__MTt[0MM M%#.#3#3#5L) %#.L(l{+s *LA N.2 M=<.N.-N.c|in|} | |||fi|}n ||||fi|}t|trf|jDcgc]\}}t|ts||f} }}| r/| D]*\}}|||<tjd|d|t ,d} t|tr|jD]r\}} t| dr(tt5| j} dddt| tjst| | t!| |fz| ||<t|St|dr(tt5|j}dddt|tjst| |t!||fz|S#t$rEt|tr|dk(r|}tjd|dt t YwxYwcc}}w#1swYxYw#1swYxYw)zCompute the score(s) of an estimator on a given test set. Will return a dict of floats if `scorer` is a _MultiMetricScorer, otherwise a single float is returned. NrCz[Scoring failed. The score on this train-test partition for these parameters will be set to z . Details: z>scoring must return a number, got %s (%s) instead. (scorer=%s)item)rrrr1r2r UserWarningrrzrhasattrrr0rrrtype) rDrrr`rmrNrrstr_eexception_messages error_msgr^s r9rrs! &-2Iv>>FIvvFFF*&,--3\\^ )dEz%QT?UT5M   1  e*t  ;;F-} '#  QI&$!<<> !KD%uf%j))!JJLE)eW^^4 eT%[$-G!GHH F4L ! M 66 "*% ' '&'..1Y&$v,)GGH H Mm  f0 1 g%$ ;;F-}%<.* * ()) ' 's6FG*G*G0 G=A G'&G'0G: =Hpredict)r>r?N>r predict_probadecision_functionpredict_log_proba) rDrErFr7rHrIrAr6rJmethod)r7rHrIrAr6rJrc t|t\|in|}trotdj |t j ddj t j dd} t | dfi|n.ttd |i _ t| _t|t!}t#|j$fijj$} t'j(| D cgc]\} }| c}} }t+|t-s t/d dvxrdu}|rt'j0j2dk(rt5}|j7npj2dk(rat'j8t:}t=j>dD])}t5j7dd|f|dd|f<+|tA|||}| fd| D}t'jBtE|t:}t'jFtE|||<tIjJ|dr%tIjL||djN}n|rntQ|dt"r[j>d}g}t=|D]9}t'j(|Dcgc]}|| c}}|jS|;|}nt'j(|}tQ|t"r|Dcgc]}|| c}S||S#t$r@} tt| jd d| j| j d} ~ wwxYwcc}} wcc}wcc}w)aGenerate cross-validated estimates for each input data point. The data is split according to the cv parameter. Each sample belongs to exactly one test set, and its prediction is computed with an estimator fitted on the corresponding training set. Passing these predictions into an evaluation metric may not be a valid way to measure generalization performance. Results can differ from :func:`cross_validate` and :func:`cross_val_score` unless all tests sets have equal size and the metric decomposes over samples. Read more in the :ref:`User Guide `. Parameters ---------- estimator : estimator The estimator instance to use to fit the data. It must implement a `fit` method and the method given by the `method` parameter. X : {array-like, sparse matrix} of shape (n_samples, n_features) The data to fit. Can be, for example a list, or an array at least 2d. y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs), default=None The target variable to try to predict in the case of supervised learning. groups : array-like of shape (n_samples,), default=None Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a "Group" :term:`cv` instance (e.g., :class:`GroupKFold`). .. versionchanged:: 1.4 ``groups`` can only be passed if metadata routing is not enabled via ``sklearn.set_config(enable_metadata_routing=True)``. When routing is enabled, pass ``groups`` alongside other metadata via the ``params`` argument instead. E.g.: ``cross_val_predict(..., params={'groups': groups})``. cv : int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 5-fold cross validation, - int, to specify the number of folds in a `(Stratified)KFold`, - :term:`CV splitter`, - An iterable that generates (train, test) splits as arrays of indices. For int/None inputs, if the estimator is a classifier and ``y`` is either binary or multiclass, :class:`StratifiedKFold` is used. In all other cases, :class:`KFold` is used. These splitters are instantiated with `shuffle=False` so the splits will be the same across calls. Refer :ref:`User Guide ` for the various cross-validation strategies that can be used here. .. versionchanged:: 0.22 ``cv`` default value if None changed from 3-fold to 5-fold. n_jobs : int, default=None Number of jobs to run in parallel. Training the estimator and predicting are parallelized over the cross-validation splits. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. verbose : int, default=0 The verbosity level. params : dict, default=None Parameters to pass to the underlying estimator's ``fit`` and the CV splitter. .. versionadded:: 1.4 pre_dispatch : int or str, default='2*n_jobs' Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs - An int, giving the exact number of total jobs that are spawned - A str, giving an expression as a function of n_jobs, as in '2*n_jobs' method : {'predict', 'predict_proba', 'predict_log_proba', 'decision_function'}, default='predict' The method to be invoked by `estimator`. Returns ------- predictions : ndarray This is the result of calling `method`. Shape: - When `method` is 'predict' and in special case where `method` is 'decision_function' and the target is binary: (n_samples,) - When `method` is one of {'predict_proba', 'predict_log_proba', 'decision_function'} (unless special case above): (n_samples, n_classes) - If `estimator` is :term:`multioutput`, an extra dimension 'n_outputs' is added to the end of each shape above. See Also -------- cross_val_score : Calculate score for each CV split. cross_validate : Calculate one or more scores and timings for each CV split. Notes ----- In the case that one or more classes are absent in a training portion, a default score needs to be assigned to all instances for that class if ``method`` produces columns per class, as in {'decision_function', 'predict_proba', 'predict_log_proba'}. For ``predict_proba`` this value is 0. In order to ensure finite output, we approximate negative infinity by the minimum finite float value for the dtype in other cases. Examples -------- >>> from sklearn import datasets, linear_model >>> from sklearn.model_selection import cross_val_predict >>> diabetes = datasets.load_diabetes() >>> X = diabetes.data[:150] >>> y = diabetes.target[:150] >>> lasso = linear_model.Lasso() >>> y_pred = cross_val_predict(lasso, X, y, cv=3) For a detailed example of using ``cross_val_predict`` to visualize prediction errors, please see :ref:`sphx_glr_auto_examples_model_selection_plot_cv_predict.py`. Nr(rTr=rVrWrZr]zcross_val_predict.fitrar7rerfrQz+cross_val_predict only works for partitionsrrrr&r dtyperhc 3K|]?\}}ttt||jjAywN)r#_fit_and_predictr rDr=)rqrjrkrErDrrdrFs r9rsz$cross_val_predict..sR  E4 " ! )     # # ' '   sAAr)format)*r4rrrryrr r rzr{rcrdrr[rDr'r r|rVnp concatenate_check_is_permutationr%r0rndimr fit_transform zeros_likeintrangeshaper"emptyrarangespissparsevstackrrr)rDrErFr7rHrIrAr6rJrrrsplitsrrk test_indicesencodeley_enci_labelr predictionsinv_test_indicesn_labels concat_predp label_predsrds``` ` @r9r(r(smT#6* Q?DAq>RvF !4 5 S,22%2PS#,22%2N  +FEDVDM !&h-?!@ "'F"3  "aM)$< =B ("((1a@=#9#9#?#?@ AF>>v">GAt4">?L |A ?FGG MM  TM  JJqM 66Q;B  #A VVq[MM!3/E , P$0N$@$@1g:$Oaj! PAvw\RH "  KxxL 1=%'YYs"ii KN4I4IJ J{1~t4 771: X ,G..k)J!G*)JKK   { + ," nn[1 +t$-89"#99+,,[(  +A'>@ST#$#7#7oo  $#?d*K:s* M+) N7  N=  O+ N44;N//N4cx||ni}t|||}t||||\}}t|||||\} } ||j|fi|n|j||fi|t||} | | } |dvxr|du} | rt | t rYt t| Dcgc]:}t|j|| |tt|dd|f|<} }| S|jdk(rtt|n|jd}t|j| ||} | Scc}w)a(Fit estimator and predict values for a given dataset split. Read more in the :ref:`User Guide `. Parameters ---------- estimator : estimator object implementing 'fit' and 'predict' The object to use to fit the data. X : array-like of shape (n_samples, n_features) The data to fit. .. versionchanged:: 0.20 X is only required to be an object with finite length or shape now y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None The target variable to try to predict in the case of supervised learning. train : array-like of shape (n_train_samples,) Indices of training samples. test : array-like of shape (n_test_samples,) Indices of test samples. fit_params : dict or None Parameters that will be passed to ``estimator.fit``. method : str Invokes the passed method name of the passed estimator. Returns ------- predictions : sequence Result of calling 'estimator.method' Nrr) n_classesrr&) r$r!r=getattrrr|rr_enforce_prediction_orderclasses_setrr)rDrErFrjrkr5rrrrrfuncr rr rs r9rrsfL *52J%a EJJ"9aE:GWIq!T59IFA g,, gw5*5 9f %Dv,K MM  TM  k4 ( %S%56 *&&w/(!#a7 m"45! K  ()vv{CF  I3""KFK s(?D7c |t|k7r1d}tjdjt|||t|dk(r|j dk(rJ|j dt|k7r/tdj|j |t|t|dkr%tdjt|||tj|jj}||dd }tjt||f|||j }||d d |f<|}|S) a Ensure that prediction arrays have correct column order When doing cross-validation, if one or more classes are not present in the subset of data used for training, then the output prediction array might not have the same columns as other folds. Use the list of class names (assumed to be ints) to enforce the correct column order. Note that `classes` is the list of classes in this fold (a subset of the classes in the full training set) and `n_classes` is the number of classes in the full training set. zTTo fix this, use a cross-validation technique resulting in properly stratified foldszNumber of classes in training fold ({}) does not match total number of classes ({}). Results may not be appropriate for your use case. {}rr r&zOutput shape {} of {} does not match number of classes ({}) in fold. Irregular decision_function outputs are not currently supported by cross_val_predictzOnly {} class/es in training fold, but {} in overall dataset. This is not supported for decision_function with imbalanced folds. {}r)rrrrN)rr1r2rRuntimeWarningrrr0rfinforminfullr%)classesr rrrecommendation float_mindefault_valuespredictions_for_all_classess r9rrDsOCL      G i@    ( (1$):):1)=W)M !()/{/@/@&#g,(W 7|q  017G i1 HH[../33 !*!*  ')gg + & 2 6 "##' # 3>#AwJ/1 r;ct||k7rytj|t}d||<tj|syy)a5Check whether indices is a reordering of the array np.arange(n_samples) Parameters ---------- indices : ndarray int array to test n_samples : int number of expected elements Returns ------- is_partition : bool True iff sorted(indices) is np.arange(n) FrT)rrzerosboolall)rv n_sampleshits r9rrs= 7|y  ((9D )CCL 66#; r;left)closed random_state) rDrErFr7rHn_permutationsrIr*rArGr5r6d) r7rHr+rIr*rArGr5r6c t| | d} t\ttt | t t rtdjtjddjtjdd  jtjdd  } t| dfi| n?t!t!| _t!di_t!i_t)t+j$j,j"j.j&j0}t3||fdt5|D}t7j8|}t7j:||k\dz|dzz }|||fS#t$r@} tt| jd d| j| jd} ~ wwxYw)aEvaluate the significance of a cross-validated score with permutations. Permutes targets to generate 'randomized data' and compute the empirical p-value against the null hypothesis that features and targets are independent. The p-value represents the fraction of randomized data sets where the estimator performed as well or better than on the original data. A small p-value suggests that there is a real dependency between features and targets which has been used by the estimator to give good predictions. A large p-value may be due to lack of real dependency between features and targets or the estimator was not able to use the dependency to give good predictions. Read more in the :ref:`User Guide `. Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : array-like of shape at least 2D The data to fit. y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None The target variable to try to predict in the case of supervised learning. groups : array-like of shape (n_samples,), default=None Labels to constrain permutation within groups, i.e. ``y`` values are permuted among samples with the same group identifier. When not specified, ``y`` values are permuted among all samples. When a grouped cross-validator is used, the group labels are also passed on to the ``split`` method of the cross-validator. The cross-validator uses them for grouping the samples while splitting the dataset into train/test set. .. versionchanged:: 1.6 ``groups`` can only be passed if metadata routing is not enabled via ``sklearn.set_config(enable_metadata_routing=True)``. When routing is enabled, pass ``groups`` alongside other metadata via the ``params`` argument instead. E.g.: ``permutation_test_score(..., params={'groups': groups})``. cv : int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - `None`, to use the default 5-fold cross validation, - int, to specify the number of folds in a `(Stratified)KFold`, - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. For `int`/`None` inputs, if the estimator is a classifier and `y` is either binary or multiclass, :class:`StratifiedKFold` is used. In all other cases, :class:`KFold` is used. These splitters are instantiated with `shuffle=False` so the splits will be the same across calls. Refer :ref:`User Guide ` for the various cross-validation strategies that can be used here. .. versionchanged:: 0.22 `cv` default value if `None` changed from 3-fold to 5-fold. n_permutations : int, default=100 Number of times to permute ``y``. n_jobs : int, default=None Number of jobs to run in parallel. Training the estimator and computing the cross-validated score are parallelized over the permutations. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. random_state : int, RandomState instance or None, default=0 Pass an int for reproducible output for permutation of ``y`` values among samples. See :term:`Glossary `. verbose : int, default=0 The verbosity level. scoring : str or callable, default=None Scoring method to use to evaluate the predictions on the validation set. - str: see :ref:`scoring_string_names` for options. - callable: a scorer callable object (e.g., function) with signature ``scorer(estimator, X, y)``, which should return only a single value. See :ref:`scoring_callable` for details. - `None`: the `estimator`'s :ref:`default evaluation criterion ` is used. fit_params : dict, default=None Parameters to pass to the fit method of the estimator. .. deprecated:: 1.6 This parameter is deprecated and will be removed in version 1.6. Use ``params`` instead. params : dict, default=None Parameters to pass to the `fit` method of the estimator, the scorer and the cv splitter. - If `enable_metadata_routing=False` (default): Parameters directly passed to the `fit` method of the estimator. - If `enable_metadata_routing=True`: Parameters safely routed to the `fit` method of the estimator, `cv` object and `scorer`. See :ref:`Metadata Routing User Guide ` for more details. .. versionadded:: 1.6 Returns ------- score : float The true score without permuting targets. permutation_scores : array of shape (n_permutations,) The scores obtained for each permutations. pvalue : float The p-value, which approximates the probability that the score would be obtained by chance. This is calculated as: `(C + 1) / (n_permutations + 1)` Where C is the number of permutations whose score >= the true score. The best possible p-value is 1/(n_permutations + 1), the worst is 1.0. Notes ----- This function implements Test 1 in: Ojala and Garriga. `Permutation Tests for Studying Classifier Performance `_. The Journal of Machine Learning Research (2010) vol. 11 Examples -------- >>> from sklearn.datasets import make_classification >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.model_selection import permutation_test_score >>> X, y = make_classification(random_state=0) >>> estimator = LogisticRegression() >>> score, permutation_scores, pvalue = permutation_test_score( ... estimator, X, y, random_state=0 ... ) >>> print(f"Original Score: {score:.3f}") Original Score: 0.810 >>> print( ... f"Permutation Scores: {permutation_scores.mean():.3f} +/- " ... f"{permutation_scores.std():.3f}" ... ) Permutation Scores: 0.505 +/- 0.057 >>> print(f"P-value: {pvalue:.3f}") P-value: 0.010 1.8rQrr,rTr=rWr]rVrZr^r_zpermutation_test_score.fitraNrfr7rerg split_paramsr5rm)rIrAc 3K|]q}tttt jj j jjjsyw)r/N) r#_permutation_test_scorer _shuffler[rVrDr=r`r^) rqrrErHrDr7r*rdr`rFs r9rsz)permutation_test_score..sy B  )'( )  Q -  &//55$..22&--33  BsA7A:?r&)r:rr'r rrrrryrr r rzr{rcrdrrDr[r`r2r rVr=r^r"rrarraysum)rDrErFr7rHr+rIr*rArGr5r6rrr^permutation_scorespvaluerdr`s````` ` @@r9r,r,s9|.j&&% PFQ6*LAq& "aM)$< =B 9g 6F%l3L !9 : S# -22%2N  S,22%2PS,22%2P $ +FEDVDM "'F"3 !&h-?!@ $2  $ i   "++11 **.."))// EBA B B~& B "45ff'501C7NQ$Y1dEB/*eT0|jAd}ng}|D]"\}}&D]}|jC|d||f$| $% fd|D}tE| tG|}|djId|jJ}|djId|jJ}||g}rQ|d jId|jJ}|d!jId|jJ} |jM|| g&|d|d"f}!r |!|d#|d$fz}!|!S#t$r@}tt|jdd|j|j d}~wwxYw)%aP Learning curve. Determines cross-validated training and test scores for different training set sizes. A cross-validation generator splits the whole dataset k times in training and test data. Subsets of the training set with varying sizes will be used to train the estimator and a score for each training subset size and the test set will be computed. Afterwards, the scores will be averaged over all k runs for each training subset size. Read more in the :ref:`User Guide `. Parameters ---------- estimator : object type that implements the "fit" method An object of that type which is cloned for each validation. It must also implement "predict" unless `scoring` is a callable that doesn't rely on "predict" to compute a score. X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None Target relative to X for classification or regression; None for unsupervised learning. groups : array-like of shape (n_samples,), default=None Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a "Group" :term:`cv` instance (e.g., :class:`GroupKFold`). .. versionchanged:: 1.6 ``groups`` can only be passed if metadata routing is not enabled via ``sklearn.set_config(enable_metadata_routing=True)``. When routing is enabled, pass ``groups`` alongside other metadata via the ``params`` argument instead. E.g.: ``learning_curve(..., params={'groups': groups})``. train_sizes : array-like of shape (n_ticks,), default=np.linspace(0.1, 1.0, 5) Relative or absolute numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of the maximum size of the training set (that is determined by the selected validation method), i.e. it has to be within (0, 1]. Otherwise it is interpreted as absolute sizes of the training sets. Note that for classification the number of samples usually has to be big enough to contain at least one sample from each class. cv : int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 5-fold cross validation, - int, to specify the number of folds in a `(Stratified)KFold`, - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. For int/None inputs, if the estimator is a classifier and ``y`` is either binary or multiclass, :class:`StratifiedKFold` is used. In all other cases, :class:`KFold` is used. These splitters are instantiated with `shuffle=False` so the splits will be the same across calls. Refer :ref:`User Guide ` for the various cross-validation strategies that can be used here. .. versionchanged:: 0.22 ``cv`` default value if None changed from 3-fold to 5-fold. scoring : str or callable, default=None Scoring method to use to evaluate the training and test sets. - str: see :ref:`scoring_string_names` for options. - callable: a scorer callable object (e.g., function) with signature ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. - `None`: the `estimator`'s :ref:`default evaluation criterion ` is used. exploit_incremental_learning : bool, default=False If the estimator supports incremental learning, this will be used to speed up fitting for different training set sizes. n_jobs : int, default=None Number of jobs to run in parallel. Training the estimator and computing the score are parallelized over the different training and test sets. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. pre_dispatch : int or str, default='all' Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The str can be an expression like '2*n_jobs'. verbose : int, default=0 Controls the verbosity: the higher, the more messages. shuffle : bool, default=False Whether to shuffle training data before taking prefixes of it based on``train_sizes``. random_state : int, RandomState instance or None, default=None Used when ``shuffle`` is True. Pass an int for reproducible output across multiple function calls. See :term:`Glossary `. error_score : 'raise' or numeric, default=np.nan Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. .. versionadded:: 0.20 return_times : bool, default=False Whether to return the fit and score times. fit_params : dict, default=None Parameters to pass to the fit method of the estimator. .. deprecated:: 1.6 This parameter is deprecated and will be removed in version 1.8. Use ``params`` instead. params : dict, default=None Parameters to pass to the `fit` method of the estimator and to the scorer. - If `enable_metadata_routing=False` (default): Parameters directly passed to the `fit` method of the estimator. - If `enable_metadata_routing=True`: Parameters safely routed to the `fit` method of the estimator. See :ref:`Metadata Routing User Guide ` for more details. .. versionadded:: 1.6 Returns ------- train_sizes_abs : array of shape (n_unique_ticks,) Numbers of training examples that has been used to generate the learning curve. Note that the number of ticks might be less than n_ticks because duplicate entries will be removed. train_scores : array of shape (n_ticks, n_cv_folds) Scores on training sets. test_scores : array of shape (n_ticks, n_cv_folds) Scores on test set. fit_times : array of shape (n_ticks, n_cv_folds) Times spent for fitting in seconds. Only present if ``return_times`` is True. score_times : array of shape (n_ticks, n_cv_folds) Times spent for scoring in seconds. Only present if ``return_times`` is True. See Also -------- LearningCurveDisplay.from_estimator : Plot a learning curve using an estimator and data. Examples -------- >>> from sklearn.datasets import make_classification >>> from sklearn.tree import DecisionTreeClassifier >>> from sklearn.model_selection import learning_curve >>> X, y = make_classification(n_samples=100, n_features=10, random_state=42) >>> tree = DecisionTreeClassifier(max_depth=4, random_state=42) >>> train_size_abs, train_scores, test_scores = learning_curve( ... tree, X, y, train_sizes=[0.3, 0.6, 0.9] ... ) >>> for train_size, cv_train_scores, cv_test_scores in zip( ... train_size_abs, train_scores, test_scores ... ): ... print(f"{train_size} samples were used to train the model") ... print(f"The average train accuracy is {cv_train_scores.mean():.2f}") ... print(f"The average test accuracy is {cv_test_scores.mean():.2f}") 24 samples were used to train the model The average train accuracy is 1.00 The average test accuracy is 0.85 48 samples were used to train the model The average train accuracy is 1.00 The average test accuracy is 0.90 72 samples were used to train the model The average train accuracy is 1.00 The average test accuracy is 0.93 partial_fitzSAn estimator must support the partial_fit interface to exploit incremental learningr.rQrr+rTr=rWr]rVrZr^r_zlearning_curve.fitraN)r=rGr7rergrz%[learning_curve] Training set sizes: rIrJrAc3JK|]\}}j||fywr)r>)rqrjrkrngs r9rsz!learning_curve..s#MkeTCOOE*D1Ms #c3 K|]Y\}}ttt || jjj j [yw))rNr5rmN)r#_incremental_fit_estimatorr rDrGr`r^) rqrjrkrErrNrDrnrdr`train_sizes_absrFs r9rsz!learning_curve..sr t 0G. /i '(22>>*1177   sAA")r r&rc3K|]Z\}}ttt || djjj j d \yw)NT) r`rjrkrArlr5rmrKrNrnro) rqrjrkrErNrDrnrdr`rArFs r9rsz!learning_curve..st t $GN #i (2266*1177#'')   sA A#rxrwrtrur&r )'rr0r:rr'r rrrryrr r rzr{rcrdrrDr[r`r|rVr_translate_train_sizesrrr"rrr?r transposerr}rreshapeTextend)'rDrErFr7rBrHrGrCrIrJrArDr*rNrnr5r6rrcv_itern_max_training_samplesn_unique_ticksrouttrain_test_proportionsrjrkn_train_samplesrrxrw fit_times score_timesrrrJrdr`rMs'``` ` `` @@@@@r9r+r+sL$GI},M .  .j&&% PFQ6*LAq& "aM)$< =B 9g 6F !1 2 S# -E%0E-8 S,22%2PS,22%2P ( +FEDVDM "'F"G !&h-?!@ $2 8288AqAM$:$:$@$@ABG A/-[:PQO$**1-N{ 5O8LLMvL'RH .MWM#"/ ":"))A,   '  "jjo'' 2!#" OKE4#2 O&--u5Eo/F.MN O O  6!  $ *';?(1~.66r>JLL m,44RHJJ [)  +33BGIII!,/77NKMMK JJ ;/ 0 3q63q6 )CSVSV$$ J(  +A';=MN#$#7#7oo  s M&& N//;N**N/crtj|}|jd}tj|}tj|}tj |j tjrL|dks|dkDrtd||fz||zjtd}tj|d|}n|dks||kDrtd|||fztj|}||jdkDr,tjd |jd|fzt|S) a~Determine absolute sizes of training subsets and validate 'train_sizes'. Examples: _translate_train_sizes([0.5, 1.0], 10) -> [5, 10] _translate_train_sizes([5, 10], 10) -> [5, 10] Parameters ---------- train_sizes : array-like of shape (n_ticks,) Numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of 'n_max_training_samples', i.e. it has to be within (0, 1]. n_max_training_samples : int Maximum number of training samples (upper bound of 'train_sizes'). Returns ------- train_sizes_abs : array of shape (n_unique_ticks,) Numbers of training examples that will be used to generate the learning curve. Note that the number of ticks might be less than n_ticks because duplicate entries will be removed. rrr4ztrain_sizes has been interpreted as fractions of the maximum number of training samples and must be within (0, 1], but is within [%f, %f].F)rrr&z|train_sizes has been interpreted as absolute numbers of training samples and must be within (0, %d], but is within [%d, %d].z|Removed duplicate entries from 'train_sizes'. Number of ticks will be less than the size of 'train_sizes': %d instead of %d.)rrrrmax issubdtyperfloatingr0astyperclipr?r1r2r)rBrWrMn_ticksn_min_required_samplesn_max_required_sampless r9rQrQ6sX0jj-O##A&GVVO4VVO4 }}_**BKK8 !S (,BS,HA*+ABC  +-CCKKEL ''/16LM #a '%(>>3+**  ii0O&&q))  /2A2G2G2JG1T U    r;c ggggf\} } }}t|tj||dd}| i} |t|jfi| }nt|jfd|i| }| | ni} t || |}t || |}|D] \}}|d|}t ||||\}}t ||||\}}t |||||\}}tj}| ||n |||tj|z }|j|tj}| jt|||||| | jt|||||| tj|z } |j| |r| | ||fn| | f}!tj|!jS)zETrain estimator on training subsets incrementally and compute scores.NrOrr)rmrN) rrrVrrGr$r!rrrr5rT)"rDrErFrrjrkrBr`rnrNr5rmrxrwr\r] partitionspartial_fit_funcrrr[ partial_train train_subsetrrX_partial_trainy_partial_trainrr start_fitrt start_scorerurs" r9rLrLzs9;BB5L+y+["((5+">s"CDJ "9#8#8GJG"9#8#8X'XZX#/#;<L-a eT,Q|TR*4$'&-o. &y!Q E+6y!Q +V($Y1dLIIIK  " _ - _o >99;*"iik  .'     /'   YY[;. :&I$'P  {I{;K ( 88C=??r;)rDrErF param_name param_ranger7rHrGrIrJrArNr5r6) r7rHrGrIrJrArNr5r6c @ t| | |d} t|\}t|t}t |t rt djtjddj|tjdd  jtjdd  } t|dfi| n?tt| _td|i_ti_t'|| }|  f d|j(fij"j(D}t+}t-|}|dj/d|j0}|dj/d|j0}||fS#t$r@}tt|jd d|j|jd}~wwxYw)aValidation curve. Determine training and test scores for varying parameter values. Compute scores for an estimator with different values of a specified parameter. This is similar to grid search with one parameter. However, this will also compute training scores and is merely a utility for plotting the results. Read more in the :ref:`User Guide `. Parameters ---------- estimator : object type that implements the "fit" method An object of that type which is cloned for each validation. It must also implement "predict" unless `scoring` is a callable that doesn't rely on "predict" to compute a score. X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None Target relative to X for classification or regression; None for unsupervised learning. param_name : str Name of the parameter that will be varied. param_range : array-like of shape (n_values,) The values of the parameter that will be evaluated. groups : array-like of shape (n_samples,), default=None Group labels for the samples used while splitting the dataset into train/test set. Only used in conjunction with a "Group" :term:`cv` instance (e.g., :class:`GroupKFold`). .. versionchanged:: 1.6 ``groups`` can only be passed if metadata routing is not enabled via ``sklearn.set_config(enable_metadata_routing=True)``. When routing is enabled, pass ``groups`` alongside other metadata via the ``params`` argument instead. E.g.: ``validation_curve(..., params={'groups': groups})``. cv : int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 5-fold cross validation, - int, to specify the number of folds in a `(Stratified)KFold`, - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. For int/None inputs, if the estimator is a classifier and ``y`` is either binary or multiclass, :class:`StratifiedKFold` is used. In all other cases, :class:`KFold` is used. These splitters are instantiated with `shuffle=False` so the splits will be the same across calls. Refer :ref:`User Guide ` for the various cross-validation strategies that can be used here. .. versionchanged:: 0.22 ``cv`` default value if None changed from 3-fold to 5-fold. scoring : str or callable, default=None Scoring method to use to evaluate the training and test sets. - str: see :ref:`scoring_string_names` for options. - callable: a scorer callable object (e.g., function) with signature ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. - `None`: the `estimator`'s :ref:`default evaluation criterion ` is used. n_jobs : int, default=None Number of jobs to run in parallel. Training the estimator and computing the score are parallelized over the combinations of each parameter value and each cross-validation split. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary ` for more details. pre_dispatch : int or str, default='all' Number of predispatched jobs for parallel execution (default is all). The option can reduce the allocated memory. The str can be an expression like '2*n_jobs'. verbose : int, default=0 Controls the verbosity: the higher, the more messages. error_score : 'raise' or numeric, default=np.nan Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. .. versionadded:: 0.20 fit_params : dict, default=None Parameters to pass to the fit method of the estimator. .. deprecated:: 1.6 This parameter is deprecated and will be removed in version 1.8. Use ``params`` instead. params : dict, default=None Parameters to pass to the estimator, scorer and cross-validation object. - If `enable_metadata_routing=False` (default): Parameters directly passed to the `fit` method of the estimator. - If `enable_metadata_routing=True`: Parameters safely routed to the `fit` method of the estimator, to the scorer and to the cross-validation object. See :ref:`Metadata Routing User Guide ` for more details. .. versionadded:: 1.6 Returns ------- train_scores : array of shape (n_ticks, n_cv_folds) Scores on training sets. test_scores : array of shape (n_ticks, n_cv_folds) Scores on test set. See Also -------- ValidationCurveDisplay.from_estimator : Plot the validation curve given an estimator, the data, and the parameter to vary. Notes ----- See :ref:`sphx_glr_auto_examples_model_selection_plot_train_error_vs_test_error.py` Examples -------- >>> import numpy as np >>> from sklearn.datasets import make_classification >>> from sklearn.model_selection import validation_curve >>> from sklearn.linear_model import LogisticRegression >>> X, y = make_classification(n_samples=1_000, random_state=0) >>> logistic_regression = LogisticRegression() >>> param_name, param_range = "C", np.logspace(-8, 3, 10) >>> train_scores, test_scores = validation_curve( ... logistic_regression, X, y, param_name=param_name, param_range=param_range ... ) >>> print(f"The average train accuracy is {train_scores.mean():.2f}") The average train accuracy is 0.81 >>> print(f"The average test accuracy is {test_scores.mean():.2f}") The average test accuracy is 0.81 r.rQrr-rTr=rWr]rVrZr^r_zvalidation_curve.fitraNrfr7rergrHc3 K|]b\}}D]X}ttt || |i jj j j d Zdyw)T) r`rjrkrArlr5rmrKrNNro) rqrjrkvrErNrDrprqrdr`rArFs r9rsz#validation_curve.. s E4#" !  )  "A$..22&--33##  sA(A+rxrOrw)r:rr'r rrrryrr r rzr{rcrdrrDr[r`r"rVrrrSrT)rDrErFrprqr7rHrGrIrJrArNr5r6rrrrn_paramsrxrwrdr`s````` `` @@r9r-r-s r.j&&% PFQ6*LAq& "aM)$< =B 9g 6F !3 4 S#,22%2NS,22%2PS,22%2P  +FEDVDM "'F"3 !&h-?!@ $2 vL'RH $288AqIM,B,B,H,HI!G&;H$W-G>*222x@BBL-(00X>@@K  $$W(  +A'=?QR#$#7#7oo  s" G H;HHc |dDcic]\}|t|d|tjr&tj|Dcgc]}|| c}n|Dcgc]}|| c}^c}}Scc}wcc}wcc}}w)aAggregate the list of dict to dict of np ndarray The aggregated output of _aggregate_score_dicts will be a list of dict of form [{'prec': 0.1, 'acc':1.0}, {'prec': 0.1, 'acc':1.0}, ...] Convert it to a dict of array {'prec': np.array([0.1 ...]), ...} Parameters ---------- scores : list of dict List of dicts of the scores for all scorers. This is a flat list, assumed originally to be of row major order. Example ------- >>> scores = [{'a': 1, 'b':10}, {'a': 2, 'b':2}, {'a': 3, 'b':3}, ... {'a': 10, 'b': 10}] # doctest: +SKIP >>> _aggregate_score_dicts(scores) # doctest: +SKIP {'a': array([1, 2, 3, 10]), 'b': array([10, 2, 3, 10])} r)rrrrr)rrr^s r9rr sz:!9    &)C.'..9 JJ7uc 7 8*01%*1 2 71  s#9A8 A. A8 A3%A8. A8rrg)rC)\__doc__rrr1 collectionsr contextlibr functoolsrr tracebackrnumpyr scipy.sparsesparserjoblibrbaser r exceptionsr r metricsrrmetrics._scorerr preprocessingrutilsrrrrutils._array_apirrutils._param_validationrrrrrutils.metadata_routingrrrr utils.metaestimatorsr!utils.parallelr"r#utils.validationr$r%_splitr'__all__r:r4rr~r|tuplerrznanr*rrr}r)rprr(rrrr,r2r3linspacer+rQrLr-rrr;r9rs!  'C50(HH4 /.A >  '(O ,D !& s+-. /       mT";,!3(k&K$+"G9-t4+.#(1: F    F54FR D,& FF '(O ,D !&s#3#5674HmT";,!3-"G9-t4 #(& [$    [$! [$T'jZCL %!345O , 2&mT";,!3-    *#(-6 u-    u-10u-pIX?D0 '(O ,D !&m#HafEFT"'(;s#3#5674HTl, #(,     x-#"x-v& &j%)* lO , lD ! <&   ~  {m  Js#3#5674H '  8T" 3 I; I; (  G9-t4   tTl!" 4,#&#()6  Ca( !&   %T-,Tn AHGT %)*O ,D !e$~&ms#3#5674HT"!3;"G9-t4Tl, #(#4     j%'&j%Zr;