_validation.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039
  1. """
  2. The :mod:`sklearn.model_selection._validation` module includes classes and
  3. functions to validate the model.
  4. """
  5. # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
  6. # Gael Varoquaux <gael.varoquaux@normalesup.org>
  7. # Olivier Grisel <olivier.grisel@ensta.org>
  8. # Raghav RV <rvraghav93@gmail.com>
  9. # Michal Karbownik <michakarbownik@gmail.com>
  10. # License: BSD 3 clause
  11. import numbers
  12. import time
  13. import warnings
  14. from collections import Counter
  15. from contextlib import suppress
  16. from functools import partial
  17. from numbers import Real
  18. from traceback import format_exc
  19. import numpy as np
  20. import scipy.sparse as sp
  21. from joblib import logger
  22. from ..base import clone, is_classifier
  23. from ..exceptions import FitFailedWarning
  24. from ..metrics import check_scoring, get_scorer_names
  25. from ..metrics._scorer import _check_multimetric_scoring, _MultimetricScorer
  26. from ..preprocessing import LabelEncoder
  27. from ..utils import _safe_indexing, check_random_state, indexable
  28. from ..utils._param_validation import (
  29. HasMethods,
  30. Integral,
  31. Interval,
  32. StrOptions,
  33. validate_params,
  34. )
  35. from ..utils.metaestimators import _safe_split
  36. from ..utils.parallel import Parallel, delayed
  37. from ..utils.validation import _check_fit_params, _num_samples
  38. from ._split import check_cv
  39. __all__ = [
  40. "cross_validate",
  41. "cross_val_score",
  42. "cross_val_predict",
  43. "permutation_test_score",
  44. "learning_curve",
  45. "validation_curve",
  46. ]
  47. @validate_params(
  48. {
  49. "estimator": [HasMethods("fit")],
  50. "X": ["array-like", "sparse matrix"],
  51. "y": ["array-like", None],
  52. "groups": ["array-like", None],
  53. "scoring": [
  54. StrOptions(set(get_scorer_names())),
  55. callable,
  56. list,
  57. tuple,
  58. dict,
  59. None,
  60. ],
  61. "cv": ["cv_object"],
  62. "n_jobs": [Integral, None],
  63. "verbose": ["verbose"],
  64. "fit_params": [dict, None],
  65. "pre_dispatch": [Integral, str],
  66. "return_train_score": ["boolean"],
  67. "return_estimator": ["boolean"],
  68. "return_indices": ["boolean"],
  69. "error_score": [StrOptions({"raise"}), Real],
  70. },
  71. prefer_skip_nested_validation=False, # estimator is not validated yet
  72. )
  73. def cross_validate(
  74. estimator,
  75. X,
  76. y=None,
  77. *,
  78. groups=None,
  79. scoring=None,
  80. cv=None,
  81. n_jobs=None,
  82. verbose=0,
  83. fit_params=None,
  84. pre_dispatch="2*n_jobs",
  85. return_train_score=False,
  86. return_estimator=False,
  87. return_indices=False,
  88. error_score=np.nan,
  89. ):
  90. """Evaluate metric(s) by cross-validation and also record fit/score times.
  91. Read more in the :ref:`User Guide <multimetric_cross_validation>`.
  92. Parameters
  93. ----------
  94. estimator : estimator object implementing 'fit'
  95. The object to use to fit the data.
  96. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  97. The data to fit. Can be for example a list, or an array.
  98. y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None
  99. The target variable to try to predict in the case of
  100. supervised learning.
  101. groups : array-like of shape (n_samples,), default=None
  102. Group labels for the samples used while splitting the dataset into
  103. train/test set. Only used in conjunction with a "Group" :term:`cv`
  104. instance (e.g., :class:`GroupKFold`).
  105. scoring : str, callable, list, tuple, or dict, default=None
  106. Strategy to evaluate the performance of the cross-validated model on
  107. the test set.
  108. If `scoring` represents a single score, one can use:
  109. - a single string (see :ref:`scoring_parameter`);
  110. - a callable (see :ref:`scoring`) that returns a single value.
  111. If `scoring` represents multiple scores, one can use:
  112. - a list or tuple of unique strings;
  113. - a callable returning a dictionary where the keys are the metric
  114. names and the values are the metric scores;
  115. - a dictionary with metric names as keys and callables a values.
  116. See :ref:`multimetric_grid_search` for an example.
  117. cv : int, cross-validation generator or an iterable, default=None
  118. Determines the cross-validation splitting strategy.
  119. Possible inputs for cv are:
  120. - None, to use the default 5-fold cross validation,
  121. - int, to specify the number of folds in a `(Stratified)KFold`,
  122. - :term:`CV splitter`,
  123. - An iterable yielding (train, test) splits as arrays of indices.
  124. For int/None inputs, if the estimator is a classifier and ``y`` is
  125. either binary or multiclass, :class:`StratifiedKFold` is used. In all
  126. other cases, :class:`KFold` is used. These splitters are instantiated
  127. with `shuffle=False` so the splits will be the same across calls.
  128. Refer :ref:`User Guide <cross_validation>` for the various
  129. cross-validation strategies that can be used here.
  130. .. versionchanged:: 0.22
  131. ``cv`` default value if None changed from 3-fold to 5-fold.
  132. n_jobs : int, default=None
  133. Number of jobs to run in parallel. Training the estimator and computing
  134. the score are parallelized over the cross-validation splits.
  135. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  136. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  137. for more details.
  138. verbose : int, default=0
  139. The verbosity level.
  140. fit_params : dict, default=None
  141. Parameters to pass to the fit method of the estimator.
  142. pre_dispatch : int or str, default='2*n_jobs'
  143. Controls the number of jobs that get dispatched during parallel
  144. execution. Reducing this number can be useful to avoid an
  145. explosion of memory consumption when more jobs get dispatched
  146. than CPUs can process. This parameter can be:
  147. - An int, giving the exact number of total jobs that are
  148. spawned
  149. - A str, giving an expression as a function of n_jobs,
  150. as in '2*n_jobs'
  151. return_train_score : bool, default=False
  152. Whether to include train scores.
  153. Computing training scores is used to get insights on how different
  154. parameter settings impact the overfitting/underfitting trade-off.
  155. However computing the scores on the training set can be computationally
  156. expensive and is not strictly required to select the parameters that
  157. yield the best generalization performance.
  158. .. versionadded:: 0.19
  159. .. versionchanged:: 0.21
  160. Default value was changed from ``True`` to ``False``
  161. return_estimator : bool, default=False
  162. Whether to return the estimators fitted on each split.
  163. .. versionadded:: 0.20
  164. return_indices : bool, default=False
  165. Whether to return the train-test indices selected for each split.
  166. .. versionadded:: 1.3
  167. error_score : 'raise' or numeric, default=np.nan
  168. Value to assign to the score if an error occurs in estimator fitting.
  169. If set to 'raise', the error is raised.
  170. If a numeric value is given, FitFailedWarning is raised.
  171. .. versionadded:: 0.20
  172. Returns
  173. -------
  174. scores : dict of float arrays of shape (n_splits,)
  175. Array of scores of the estimator for each run of the cross validation.
  176. A dict of arrays containing the score/time arrays for each scorer is
  177. returned. The possible keys for this ``dict`` are:
  178. ``test_score``
  179. The score array for test scores on each cv split.
  180. Suffix ``_score`` in ``test_score`` changes to a specific
  181. metric like ``test_r2`` or ``test_auc`` if there are
  182. multiple scoring metrics in the scoring parameter.
  183. ``train_score``
  184. The score array for train scores on each cv split.
  185. Suffix ``_score`` in ``train_score`` changes to a specific
  186. metric like ``train_r2`` or ``train_auc`` if there are
  187. multiple scoring metrics in the scoring parameter.
  188. This is available only if ``return_train_score`` parameter
  189. is ``True``.
  190. ``fit_time``
  191. The time for fitting the estimator on the train
  192. set for each cv split.
  193. ``score_time``
  194. The time for scoring the estimator on the test set for each
  195. cv split. (Note time for scoring on the train set is not
  196. included even if ``return_train_score`` is set to ``True``
  197. ``estimator``
  198. The estimator objects for each cv split.
  199. This is available only if ``return_estimator`` parameter
  200. is set to ``True``.
  201. ``indices``
  202. The train/test positional indices for each cv split. A dictionary
  203. is returned where the keys are either `"train"` or `"test"`
  204. and the associated values are a list of integer-dtyped NumPy
  205. arrays with the indices. Available only if `return_indices=True`.
  206. See Also
  207. --------
  208. cross_val_score : Run cross-validation for single metric evaluation.
  209. cross_val_predict : Get predictions from each split of cross-validation for
  210. diagnostic purposes.
  211. sklearn.metrics.make_scorer : Make a scorer from a performance metric or
  212. loss function.
  213. Examples
  214. --------
  215. >>> from sklearn import datasets, linear_model
  216. >>> from sklearn.model_selection import cross_validate
  217. >>> from sklearn.metrics import make_scorer
  218. >>> from sklearn.metrics import confusion_matrix
  219. >>> from sklearn.svm import LinearSVC
  220. >>> diabetes = datasets.load_diabetes()
  221. >>> X = diabetes.data[:150]
  222. >>> y = diabetes.target[:150]
  223. >>> lasso = linear_model.Lasso()
  224. Single metric evaluation using ``cross_validate``
  225. >>> cv_results = cross_validate(lasso, X, y, cv=3)
  226. >>> sorted(cv_results.keys())
  227. ['fit_time', 'score_time', 'test_score']
  228. >>> cv_results['test_score']
  229. array([0.3315057 , 0.08022103, 0.03531816])
  230. Multiple metric evaluation using ``cross_validate``
  231. (please refer the ``scoring`` parameter doc for more information)
  232. >>> scores = cross_validate(lasso, X, y, cv=3,
  233. ... scoring=('r2', 'neg_mean_squared_error'),
  234. ... return_train_score=True)
  235. >>> print(scores['test_neg_mean_squared_error'])
  236. [-3635.5... -3573.3... -6114.7...]
  237. >>> print(scores['train_r2'])
  238. [0.28009951 0.3908844 0.22784907]
  239. """
  240. X, y, groups = indexable(X, y, groups)
  241. cv = check_cv(cv, y, classifier=is_classifier(estimator))
  242. if callable(scoring):
  243. scorers = scoring
  244. elif scoring is None or isinstance(scoring, str):
  245. scorers = check_scoring(estimator, scoring)
  246. else:
  247. scorers = _check_multimetric_scoring(estimator, scoring)
  248. indices = cv.split(X, y, groups)
  249. if return_indices:
  250. # materialize the indices since we need to store them in the returned dict
  251. indices = list(indices)
  252. # We clone the estimator to make sure that all the folds are
  253. # independent, and that it is pickle-able.
  254. parallel = Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch)
  255. results = parallel(
  256. delayed(_fit_and_score)(
  257. clone(estimator),
  258. X,
  259. y,
  260. scorers,
  261. train,
  262. test,
  263. verbose,
  264. None,
  265. fit_params,
  266. return_train_score=return_train_score,
  267. return_times=True,
  268. return_estimator=return_estimator,
  269. error_score=error_score,
  270. )
  271. for train, test in indices
  272. )
  273. _warn_or_raise_about_fit_failures(results, error_score)
  274. # For callable scoring, the return type is only know after calling. If the
  275. # return type is a dictionary, the error scores can now be inserted with
  276. # the correct key.
  277. if callable(scoring):
  278. _insert_error_scores(results, error_score)
  279. results = _aggregate_score_dicts(results)
  280. ret = {}
  281. ret["fit_time"] = results["fit_time"]
  282. ret["score_time"] = results["score_time"]
  283. if return_estimator:
  284. ret["estimator"] = results["estimator"]
  285. if return_indices:
  286. ret["indices"] = {}
  287. ret["indices"]["train"], ret["indices"]["test"] = zip(*indices)
  288. test_scores_dict = _normalize_score_results(results["test_scores"])
  289. if return_train_score:
  290. train_scores_dict = _normalize_score_results(results["train_scores"])
  291. for name in test_scores_dict:
  292. ret["test_%s" % name] = test_scores_dict[name]
  293. if return_train_score:
  294. key = "train_%s" % name
  295. ret[key] = train_scores_dict[name]
  296. return ret
  297. def _insert_error_scores(results, error_score):
  298. """Insert error in `results` by replacing them inplace with `error_score`.
  299. This only applies to multimetric scores because `_fit_and_score` will
  300. handle the single metric case.
  301. """
  302. successful_score = None
  303. failed_indices = []
  304. for i, result in enumerate(results):
  305. if result["fit_error"] is not None:
  306. failed_indices.append(i)
  307. elif successful_score is None:
  308. successful_score = result["test_scores"]
  309. if isinstance(successful_score, dict):
  310. formatted_error = {name: error_score for name in successful_score}
  311. for i in failed_indices:
  312. results[i]["test_scores"] = formatted_error.copy()
  313. if "train_scores" in results[i]:
  314. results[i]["train_scores"] = formatted_error.copy()
  315. def _normalize_score_results(scores, scaler_score_key="score"):
  316. """Creates a scoring dictionary based on the type of `scores`"""
  317. if isinstance(scores[0], dict):
  318. # multimetric scoring
  319. return _aggregate_score_dicts(scores)
  320. # scaler
  321. return {scaler_score_key: scores}
  322. def _warn_or_raise_about_fit_failures(results, error_score):
  323. fit_errors = [
  324. result["fit_error"] for result in results if result["fit_error"] is not None
  325. ]
  326. if fit_errors:
  327. num_failed_fits = len(fit_errors)
  328. num_fits = len(results)
  329. fit_errors_counter = Counter(fit_errors)
  330. delimiter = "-" * 80 + "\n"
  331. fit_errors_summary = "\n".join(
  332. f"{delimiter}{n} fits failed with the following error:\n{error}"
  333. for error, n in fit_errors_counter.items()
  334. )
  335. if num_failed_fits == num_fits:
  336. all_fits_failed_message = (
  337. f"\nAll the {num_fits} fits failed.\n"
  338. "It is very likely that your model is misconfigured.\n"
  339. "You can try to debug the error by setting error_score='raise'.\n\n"
  340. f"Below are more details about the failures:\n{fit_errors_summary}"
  341. )
  342. raise ValueError(all_fits_failed_message)
  343. else:
  344. some_fits_failed_message = (
  345. f"\n{num_failed_fits} fits failed out of a total of {num_fits}.\n"
  346. "The score on these train-test partitions for these parameters"
  347. f" will be set to {error_score}.\n"
  348. "If these failures are not expected, you can try to debug them "
  349. "by setting error_score='raise'.\n\n"
  350. f"Below are more details about the failures:\n{fit_errors_summary}"
  351. )
  352. warnings.warn(some_fits_failed_message, FitFailedWarning)
  353. def cross_val_score(
  354. estimator,
  355. X,
  356. y=None,
  357. *,
  358. groups=None,
  359. scoring=None,
  360. cv=None,
  361. n_jobs=None,
  362. verbose=0,
  363. fit_params=None,
  364. pre_dispatch="2*n_jobs",
  365. error_score=np.nan,
  366. ):
  367. """Evaluate a score by cross-validation.
  368. Read more in the :ref:`User Guide <cross_validation>`.
  369. Parameters
  370. ----------
  371. estimator : estimator object implementing 'fit'
  372. The object to use to fit the data.
  373. X : array-like of shape (n_samples, n_features)
  374. The data to fit. Can be for example a list, or an array.
  375. y : array-like of shape (n_samples,) or (n_samples, n_outputs), \
  376. default=None
  377. The target variable to try to predict in the case of
  378. supervised learning.
  379. groups : array-like of shape (n_samples,), default=None
  380. Group labels for the samples used while splitting the dataset into
  381. train/test set. Only used in conjunction with a "Group" :term:`cv`
  382. instance (e.g., :class:`GroupKFold`).
  383. scoring : str or callable, default=None
  384. A str (see model evaluation documentation) or
  385. a scorer callable object / function with signature
  386. ``scorer(estimator, X, y)`` which should return only
  387. a single value.
  388. Similar to :func:`cross_validate`
  389. but only a single metric is permitted.
  390. If `None`, the estimator's default scorer (if available) is used.
  391. cv : int, cross-validation generator or an iterable, default=None
  392. Determines the cross-validation splitting strategy.
  393. Possible inputs for cv are:
  394. - `None`, to use the default 5-fold cross validation,
  395. - int, to specify the number of folds in a `(Stratified)KFold`,
  396. - :term:`CV splitter`,
  397. - An iterable that generates (train, test) splits as arrays of indices.
  398. For `int`/`None` inputs, if the estimator is a classifier and `y` is
  399. either binary or multiclass, :class:`StratifiedKFold` is used. In all
  400. other cases, :class:`KFold` is used. These splitters are instantiated
  401. with `shuffle=False` so the splits will be the same across calls.
  402. Refer :ref:`User Guide <cross_validation>` for the various
  403. cross-validation strategies that can be used here.
  404. .. versionchanged:: 0.22
  405. `cv` default value if `None` changed from 3-fold to 5-fold.
  406. n_jobs : int, default=None
  407. Number of jobs to run in parallel. Training the estimator and computing
  408. the score are parallelized over the cross-validation splits.
  409. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  410. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  411. for more details.
  412. verbose : int, default=0
  413. The verbosity level.
  414. fit_params : dict, default=None
  415. Parameters to pass to the fit method of the estimator.
  416. pre_dispatch : int or str, default='2*n_jobs'
  417. Controls the number of jobs that get dispatched during parallel
  418. execution. Reducing this number can be useful to avoid an
  419. explosion of memory consumption when more jobs get dispatched
  420. than CPUs can process. This parameter can be:
  421. - ``None``, in which case all the jobs are immediately
  422. created and spawned. Use this for lightweight and
  423. fast-running jobs, to avoid delays due to on-demand
  424. spawning of the jobs
  425. - An int, giving the exact number of total jobs that are
  426. spawned
  427. - A str, giving an expression as a function of n_jobs,
  428. as in '2*n_jobs'
  429. error_score : 'raise' or numeric, default=np.nan
  430. Value to assign to the score if an error occurs in estimator fitting.
  431. If set to 'raise', the error is raised.
  432. If a numeric value is given, FitFailedWarning is raised.
  433. .. versionadded:: 0.20
  434. Returns
  435. -------
  436. scores : ndarray of float of shape=(len(list(cv)),)
  437. Array of scores of the estimator for each run of the cross validation.
  438. See Also
  439. --------
  440. cross_validate : To run cross-validation on multiple metrics and also to
  441. return train scores, fit times and score times.
  442. cross_val_predict : Get predictions from each split of cross-validation for
  443. diagnostic purposes.
  444. sklearn.metrics.make_scorer : Make a scorer from a performance metric or
  445. loss function.
  446. Examples
  447. --------
  448. >>> from sklearn import datasets, linear_model
  449. >>> from sklearn.model_selection import cross_val_score
  450. >>> diabetes = datasets.load_diabetes()
  451. >>> X = diabetes.data[:150]
  452. >>> y = diabetes.target[:150]
  453. >>> lasso = linear_model.Lasso()
  454. >>> print(cross_val_score(lasso, X, y, cv=3))
  455. [0.3315057 0.08022103 0.03531816]
  456. """
  457. # To ensure multimetric format is not supported
  458. scorer = check_scoring(estimator, scoring=scoring)
  459. cv_results = cross_validate(
  460. estimator=estimator,
  461. X=X,
  462. y=y,
  463. groups=groups,
  464. scoring={"score": scorer},
  465. cv=cv,
  466. n_jobs=n_jobs,
  467. verbose=verbose,
  468. fit_params=fit_params,
  469. pre_dispatch=pre_dispatch,
  470. error_score=error_score,
  471. )
  472. return cv_results["test_score"]
  473. def _fit_and_score(
  474. estimator,
  475. X,
  476. y,
  477. scorer,
  478. train,
  479. test,
  480. verbose,
  481. parameters,
  482. fit_params,
  483. return_train_score=False,
  484. return_parameters=False,
  485. return_n_test_samples=False,
  486. return_times=False,
  487. return_estimator=False,
  488. split_progress=None,
  489. candidate_progress=None,
  490. error_score=np.nan,
  491. ):
  492. """Fit estimator and compute scores for a given dataset split.
  493. Parameters
  494. ----------
  495. estimator : estimator object implementing 'fit'
  496. The object to use to fit the data.
  497. X : array-like of shape (n_samples, n_features)
  498. The data to fit.
  499. y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
  500. The target variable to try to predict in the case of
  501. supervised learning.
  502. scorer : A single callable or dict mapping scorer name to the callable
  503. If it is a single callable, the return value for ``train_scores`` and
  504. ``test_scores`` is a single float.
  505. For a dict, it should be one mapping the scorer name to the scorer
  506. callable object / function.
  507. The callable object / fn should have signature
  508. ``scorer(estimator, X, y)``.
  509. train : array-like of shape (n_train_samples,)
  510. Indices of training samples.
  511. test : array-like of shape (n_test_samples,)
  512. Indices of test samples.
  513. verbose : int
  514. The verbosity level.
  515. error_score : 'raise' or numeric, default=np.nan
  516. Value to assign to the score if an error occurs in estimator fitting.
  517. If set to 'raise', the error is raised.
  518. If a numeric value is given, FitFailedWarning is raised.
  519. parameters : dict or None
  520. Parameters to be set on the estimator.
  521. fit_params : dict or None
  522. Parameters that will be passed to ``estimator.fit``.
  523. return_train_score : bool, default=False
  524. Compute and return score on training set.
  525. return_parameters : bool, default=False
  526. Return parameters that has been used for the estimator.
  527. split_progress : {list, tuple} of int, default=None
  528. A list or tuple of format (<current_split_id>, <total_num_of_splits>).
  529. candidate_progress : {list, tuple} of int, default=None
  530. A list or tuple of format
  531. (<current_candidate_id>, <total_number_of_candidates>).
  532. return_n_test_samples : bool, default=False
  533. Whether to return the ``n_test_samples``.
  534. return_times : bool, default=False
  535. Whether to return the fit/score times.
  536. return_estimator : bool, default=False
  537. Whether to return the fitted estimator.
  538. Returns
  539. -------
  540. result : dict with the following attributes
  541. train_scores : dict of scorer name -> float
  542. Score on training set (for all the scorers),
  543. returned only if `return_train_score` is `True`.
  544. test_scores : dict of scorer name -> float
  545. Score on testing set (for all the scorers).
  546. n_test_samples : int
  547. Number of test samples.
  548. fit_time : float
  549. Time spent for fitting in seconds.
  550. score_time : float
  551. Time spent for scoring in seconds.
  552. parameters : dict or None
  553. The parameters that have been evaluated.
  554. estimator : estimator object
  555. The fitted estimator.
  556. fit_error : str or None
  557. Traceback str if the fit failed, None if the fit succeeded.
  558. """
  559. if not isinstance(error_score, numbers.Number) and error_score != "raise":
  560. raise ValueError(
  561. "error_score must be the string 'raise' or a numeric value. "
  562. "(Hint: if using 'raise', please make sure that it has been "
  563. "spelled correctly.)"
  564. )
  565. progress_msg = ""
  566. if verbose > 2:
  567. if split_progress is not None:
  568. progress_msg = f" {split_progress[0]+1}/{split_progress[1]}"
  569. if candidate_progress and verbose > 9:
  570. progress_msg += f"; {candidate_progress[0]+1}/{candidate_progress[1]}"
  571. if verbose > 1:
  572. if parameters is None:
  573. params_msg = ""
  574. else:
  575. sorted_keys = sorted(parameters) # Ensure deterministic o/p
  576. params_msg = ", ".join(f"{k}={parameters[k]}" for k in sorted_keys)
  577. if verbose > 9:
  578. start_msg = f"[CV{progress_msg}] START {params_msg}"
  579. print(f"{start_msg}{(80 - len(start_msg)) * '.'}")
  580. # Adjust length of sample weights
  581. fit_params = fit_params if fit_params is not None else {}
  582. fit_params = _check_fit_params(X, fit_params, train)
  583. if parameters is not None:
  584. # here we clone the parameters, since sometimes the parameters
  585. # themselves might be estimators, e.g. when we search over different
  586. # estimators in a pipeline.
  587. # ref: https://github.com/scikit-learn/scikit-learn/pull/26786
  588. estimator = estimator.set_params(**clone(parameters, safe=False))
  589. start_time = time.time()
  590. X_train, y_train = _safe_split(estimator, X, y, train)
  591. X_test, y_test = _safe_split(estimator, X, y, test, train)
  592. result = {}
  593. try:
  594. if y_train is None:
  595. estimator.fit(X_train, **fit_params)
  596. else:
  597. estimator.fit(X_train, y_train, **fit_params)
  598. except Exception:
  599. # Note fit time as time until error
  600. fit_time = time.time() - start_time
  601. score_time = 0.0
  602. if error_score == "raise":
  603. raise
  604. elif isinstance(error_score, numbers.Number):
  605. if isinstance(scorer, dict):
  606. test_scores = {name: error_score for name in scorer}
  607. if return_train_score:
  608. train_scores = test_scores.copy()
  609. else:
  610. test_scores = error_score
  611. if return_train_score:
  612. train_scores = error_score
  613. result["fit_error"] = format_exc()
  614. else:
  615. result["fit_error"] = None
  616. fit_time = time.time() - start_time
  617. test_scores = _score(estimator, X_test, y_test, scorer, error_score)
  618. score_time = time.time() - start_time - fit_time
  619. if return_train_score:
  620. train_scores = _score(estimator, X_train, y_train, scorer, error_score)
  621. if verbose > 1:
  622. total_time = score_time + fit_time
  623. end_msg = f"[CV{progress_msg}] END "
  624. result_msg = params_msg + (";" if params_msg else "")
  625. if verbose > 2:
  626. if isinstance(test_scores, dict):
  627. for scorer_name in sorted(test_scores):
  628. result_msg += f" {scorer_name}: ("
  629. if return_train_score:
  630. scorer_scores = train_scores[scorer_name]
  631. result_msg += f"train={scorer_scores:.3f}, "
  632. result_msg += f"test={test_scores[scorer_name]:.3f})"
  633. else:
  634. result_msg += ", score="
  635. if return_train_score:
  636. result_msg += f"(train={train_scores:.3f}, test={test_scores:.3f})"
  637. else:
  638. result_msg += f"{test_scores:.3f}"
  639. result_msg += f" total time={logger.short_format_time(total_time)}"
  640. # Right align the result_msg
  641. end_msg += "." * (80 - len(end_msg) - len(result_msg))
  642. end_msg += result_msg
  643. print(end_msg)
  644. result["test_scores"] = test_scores
  645. if return_train_score:
  646. result["train_scores"] = train_scores
  647. if return_n_test_samples:
  648. result["n_test_samples"] = _num_samples(X_test)
  649. if return_times:
  650. result["fit_time"] = fit_time
  651. result["score_time"] = score_time
  652. if return_parameters:
  653. result["parameters"] = parameters
  654. if return_estimator:
  655. result["estimator"] = estimator
  656. return result
  657. def _score(estimator, X_test, y_test, scorer, error_score="raise"):
  658. """Compute the score(s) of an estimator on a given test set.
  659. Will return a dict of floats if `scorer` is a dict, otherwise a single
  660. float is returned.
  661. """
  662. if isinstance(scorer, dict):
  663. # will cache method calls if needed. scorer() returns a dict
  664. scorer = _MultimetricScorer(scorers=scorer, raise_exc=(error_score == "raise"))
  665. try:
  666. if y_test is None:
  667. scores = scorer(estimator, X_test)
  668. else:
  669. scores = scorer(estimator, X_test, y_test)
  670. except Exception:
  671. if isinstance(scorer, _MultimetricScorer):
  672. # If `_MultimetricScorer` raises exception, the `error_score`
  673. # parameter is equal to "raise".
  674. raise
  675. else:
  676. if error_score == "raise":
  677. raise
  678. else:
  679. scores = error_score
  680. warnings.warn(
  681. (
  682. "Scoring failed. The score on this train-test partition for "
  683. f"these parameters will be set to {error_score}. Details: \n"
  684. f"{format_exc()}"
  685. ),
  686. UserWarning,
  687. )
  688. # Check non-raised error messages in `_MultimetricScorer`
  689. if isinstance(scorer, _MultimetricScorer):
  690. exception_messages = [
  691. (name, str_e) for name, str_e in scores.items() if isinstance(str_e, str)
  692. ]
  693. if exception_messages:
  694. # error_score != "raise"
  695. for name, str_e in exception_messages:
  696. scores[name] = error_score
  697. warnings.warn(
  698. (
  699. "Scoring failed. The score on this train-test partition for "
  700. f"these parameters will be set to {error_score}. Details: \n"
  701. f"{str_e}"
  702. ),
  703. UserWarning,
  704. )
  705. error_msg = "scoring must return a number, got %s (%s) instead. (scorer=%s)"
  706. if isinstance(scores, dict):
  707. for name, score in scores.items():
  708. if hasattr(score, "item"):
  709. with suppress(ValueError):
  710. # e.g. unwrap memmapped scalars
  711. score = score.item()
  712. if not isinstance(score, numbers.Number):
  713. raise ValueError(error_msg % (score, type(score), name))
  714. scores[name] = score
  715. else: # scalar
  716. if hasattr(scores, "item"):
  717. with suppress(ValueError):
  718. # e.g. unwrap memmapped scalars
  719. scores = scores.item()
  720. if not isinstance(scores, numbers.Number):
  721. raise ValueError(error_msg % (scores, type(scores), scorer))
  722. return scores
  723. def cross_val_predict(
  724. estimator,
  725. X,
  726. y=None,
  727. *,
  728. groups=None,
  729. cv=None,
  730. n_jobs=None,
  731. verbose=0,
  732. fit_params=None,
  733. pre_dispatch="2*n_jobs",
  734. method="predict",
  735. ):
  736. """Generate cross-validated estimates for each input data point.
  737. The data is split according to the cv parameter. Each sample belongs
  738. to exactly one test set, and its prediction is computed with an
  739. estimator fitted on the corresponding training set.
  740. Passing these predictions into an evaluation metric may not be a valid
  741. way to measure generalization performance. Results can differ from
  742. :func:`cross_validate` and :func:`cross_val_score` unless all tests sets
  743. have equal size and the metric decomposes over samples.
  744. Read more in the :ref:`User Guide <cross_validation>`.
  745. Parameters
  746. ----------
  747. estimator : estimator object implementing 'fit' and 'predict'
  748. The object to use to fit the data.
  749. X : array-like of shape (n_samples, n_features)
  750. The data to fit. Can be, for example a list, or an array at least 2d.
  751. y : array-like of shape (n_samples,) or (n_samples, n_outputs), \
  752. default=None
  753. The target variable to try to predict in the case of
  754. supervised learning.
  755. groups : array-like of shape (n_samples,), default=None
  756. Group labels for the samples used while splitting the dataset into
  757. train/test set. Only used in conjunction with a "Group" :term:`cv`
  758. instance (e.g., :class:`GroupKFold`).
  759. cv : int, cross-validation generator or an iterable, default=None
  760. Determines the cross-validation splitting strategy.
  761. Possible inputs for cv are:
  762. - None, to use the default 5-fold cross validation,
  763. - int, to specify the number of folds in a `(Stratified)KFold`,
  764. - :term:`CV splitter`,
  765. - An iterable that generates (train, test) splits as arrays of indices.
  766. For int/None inputs, if the estimator is a classifier and ``y`` is
  767. either binary or multiclass, :class:`StratifiedKFold` is used. In all
  768. other cases, :class:`KFold` is used. These splitters are instantiated
  769. with `shuffle=False` so the splits will be the same across calls.
  770. Refer :ref:`User Guide <cross_validation>` for the various
  771. cross-validation strategies that can be used here.
  772. .. versionchanged:: 0.22
  773. ``cv`` default value if None changed from 3-fold to 5-fold.
  774. n_jobs : int, default=None
  775. Number of jobs to run in parallel. Training the estimator and
  776. predicting are parallelized over the cross-validation splits.
  777. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  778. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  779. for more details.
  780. verbose : int, default=0
  781. The verbosity level.
  782. fit_params : dict, default=None
  783. Parameters to pass to the fit method of the estimator.
  784. pre_dispatch : int or str, default='2*n_jobs'
  785. Controls the number of jobs that get dispatched during parallel
  786. execution. Reducing this number can be useful to avoid an
  787. explosion of memory consumption when more jobs get dispatched
  788. than CPUs can process. This parameter can be:
  789. - None, in which case all the jobs are immediately
  790. created and spawned. Use this for lightweight and
  791. fast-running jobs, to avoid delays due to on-demand
  792. spawning of the jobs
  793. - An int, giving the exact number of total jobs that are
  794. spawned
  795. - A str, giving an expression as a function of n_jobs,
  796. as in '2*n_jobs'
  797. method : {'predict', 'predict_proba', 'predict_log_proba', \
  798. 'decision_function'}, default='predict'
  799. The method to be invoked by `estimator`.
  800. Returns
  801. -------
  802. predictions : ndarray
  803. This is the result of calling `method`. Shape:
  804. - When `method` is 'predict' and in special case where `method` is
  805. 'decision_function' and the target is binary: (n_samples,)
  806. - When `method` is one of {'predict_proba', 'predict_log_proba',
  807. 'decision_function'} (unless special case above):
  808. (n_samples, n_classes)
  809. - If `estimator` is :term:`multioutput`, an extra dimension
  810. 'n_outputs' is added to the end of each shape above.
  811. See Also
  812. --------
  813. cross_val_score : Calculate score for each CV split.
  814. cross_validate : Calculate one or more scores and timings for each CV
  815. split.
  816. Notes
  817. -----
  818. In the case that one or more classes are absent in a training portion, a
  819. default score needs to be assigned to all instances for that class if
  820. ``method`` produces columns per class, as in {'decision_function',
  821. 'predict_proba', 'predict_log_proba'}. For ``predict_proba`` this value is
  822. 0. In order to ensure finite output, we approximate negative infinity by
  823. the minimum finite float value for the dtype in other cases.
  824. Examples
  825. --------
  826. >>> from sklearn import datasets, linear_model
  827. >>> from sklearn.model_selection import cross_val_predict
  828. >>> diabetes = datasets.load_diabetes()
  829. >>> X = diabetes.data[:150]
  830. >>> y = diabetes.target[:150]
  831. >>> lasso = linear_model.Lasso()
  832. >>> y_pred = cross_val_predict(lasso, X, y, cv=3)
  833. """
  834. X, y, groups = indexable(X, y, groups)
  835. cv = check_cv(cv, y, classifier=is_classifier(estimator))
  836. splits = list(cv.split(X, y, groups))
  837. test_indices = np.concatenate([test for _, test in splits])
  838. if not _check_is_permutation(test_indices, _num_samples(X)):
  839. raise ValueError("cross_val_predict only works for partitions")
  840. # If classification methods produce multiple columns of output,
  841. # we need to manually encode classes to ensure consistent column ordering.
  842. encode = (
  843. method in ["decision_function", "predict_proba", "predict_log_proba"]
  844. and y is not None
  845. )
  846. if encode:
  847. y = np.asarray(y)
  848. if y.ndim == 1:
  849. le = LabelEncoder()
  850. y = le.fit_transform(y)
  851. elif y.ndim == 2:
  852. y_enc = np.zeros_like(y, dtype=int)
  853. for i_label in range(y.shape[1]):
  854. y_enc[:, i_label] = LabelEncoder().fit_transform(y[:, i_label])
  855. y = y_enc
  856. # We clone the estimator to make sure that all the folds are
  857. # independent, and that it is pickle-able.
  858. parallel = Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch)
  859. predictions = parallel(
  860. delayed(_fit_and_predict)(
  861. clone(estimator), X, y, train, test, verbose, fit_params, method
  862. )
  863. for train, test in splits
  864. )
  865. inv_test_indices = np.empty(len(test_indices), dtype=int)
  866. inv_test_indices[test_indices] = np.arange(len(test_indices))
  867. if sp.issparse(predictions[0]):
  868. predictions = sp.vstack(predictions, format=predictions[0].format)
  869. elif encode and isinstance(predictions[0], list):
  870. # `predictions` is a list of method outputs from each fold.
  871. # If each of those is also a list, then treat this as a
  872. # multioutput-multiclass task. We need to separately concatenate
  873. # the method outputs for each label into an `n_labels` long list.
  874. n_labels = y.shape[1]
  875. concat_pred = []
  876. for i_label in range(n_labels):
  877. label_preds = np.concatenate([p[i_label] for p in predictions])
  878. concat_pred.append(label_preds)
  879. predictions = concat_pred
  880. else:
  881. predictions = np.concatenate(predictions)
  882. if isinstance(predictions, list):
  883. return [p[inv_test_indices] for p in predictions]
  884. else:
  885. return predictions[inv_test_indices]
  886. def _fit_and_predict(estimator, X, y, train, test, verbose, fit_params, method):
  887. """Fit estimator and predict values for a given dataset split.
  888. Read more in the :ref:`User Guide <cross_validation>`.
  889. Parameters
  890. ----------
  891. estimator : estimator object implementing 'fit' and 'predict'
  892. The object to use to fit the data.
  893. X : array-like of shape (n_samples, n_features)
  894. The data to fit.
  895. .. versionchanged:: 0.20
  896. X is only required to be an object with finite length or shape now
  897. y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
  898. The target variable to try to predict in the case of
  899. supervised learning.
  900. train : array-like of shape (n_train_samples,)
  901. Indices of training samples.
  902. test : array-like of shape (n_test_samples,)
  903. Indices of test samples.
  904. verbose : int
  905. The verbosity level.
  906. fit_params : dict or None
  907. Parameters that will be passed to ``estimator.fit``.
  908. method : str
  909. Invokes the passed method name of the passed estimator.
  910. Returns
  911. -------
  912. predictions : sequence
  913. Result of calling 'estimator.method'
  914. """
  915. # Adjust length of sample weights
  916. fit_params = fit_params if fit_params is not None else {}
  917. fit_params = _check_fit_params(X, fit_params, train)
  918. X_train, y_train = _safe_split(estimator, X, y, train)
  919. X_test, _ = _safe_split(estimator, X, y, test, train)
  920. if y_train is None:
  921. estimator.fit(X_train, **fit_params)
  922. else:
  923. estimator.fit(X_train, y_train, **fit_params)
  924. func = getattr(estimator, method)
  925. predictions = func(X_test)
  926. encode = (
  927. method in ["decision_function", "predict_proba", "predict_log_proba"]
  928. and y is not None
  929. )
  930. if encode:
  931. if isinstance(predictions, list):
  932. predictions = [
  933. _enforce_prediction_order(
  934. estimator.classes_[i_label],
  935. predictions[i_label],
  936. n_classes=len(set(y[:, i_label])),
  937. method=method,
  938. )
  939. for i_label in range(len(predictions))
  940. ]
  941. else:
  942. # A 2D y array should be a binary label indicator matrix
  943. n_classes = len(set(y)) if y.ndim == 1 else y.shape[1]
  944. predictions = _enforce_prediction_order(
  945. estimator.classes_, predictions, n_classes, method
  946. )
  947. return predictions
  948. def _enforce_prediction_order(classes, predictions, n_classes, method):
  949. """Ensure that prediction arrays have correct column order
  950. When doing cross-validation, if one or more classes are
  951. not present in the subset of data used for training,
  952. then the output prediction array might not have the same
  953. columns as other folds. Use the list of class names
  954. (assumed to be ints) to enforce the correct column order.
  955. Note that `classes` is the list of classes in this fold
  956. (a subset of the classes in the full training set)
  957. and `n_classes` is the number of classes in the full training set.
  958. """
  959. if n_classes != len(classes):
  960. recommendation = (
  961. "To fix this, use a cross-validation "
  962. "technique resulting in properly "
  963. "stratified folds"
  964. )
  965. warnings.warn(
  966. "Number of classes in training fold ({}) does "
  967. "not match total number of classes ({}). "
  968. "Results may not be appropriate for your use case. "
  969. "{}".format(len(classes), n_classes, recommendation),
  970. RuntimeWarning,
  971. )
  972. if method == "decision_function":
  973. if predictions.ndim == 2 and predictions.shape[1] != len(classes):
  974. # This handles the case when the shape of predictions
  975. # does not match the number of classes used to train
  976. # it with. This case is found when sklearn.svm.SVC is
  977. # set to `decision_function_shape='ovo'`.
  978. raise ValueError(
  979. "Output shape {} of {} does not match "
  980. "number of classes ({}) in fold. "
  981. "Irregular decision_function outputs "
  982. "are not currently supported by "
  983. "cross_val_predict".format(predictions.shape, method, len(classes))
  984. )
  985. if len(classes) <= 2:
  986. # In this special case, `predictions` contains a 1D array.
  987. raise ValueError(
  988. "Only {} class/es in training fold, but {} "
  989. "in overall dataset. This "
  990. "is not supported for decision_function "
  991. "with imbalanced folds. {}".format(
  992. len(classes), n_classes, recommendation
  993. )
  994. )
  995. float_min = np.finfo(predictions.dtype).min
  996. default_values = {
  997. "decision_function": float_min,
  998. "predict_log_proba": float_min,
  999. "predict_proba": 0,
  1000. }
  1001. predictions_for_all_classes = np.full(
  1002. (_num_samples(predictions), n_classes),
  1003. default_values[method],
  1004. dtype=predictions.dtype,
  1005. )
  1006. predictions_for_all_classes[:, classes] = predictions
  1007. predictions = predictions_for_all_classes
  1008. return predictions
  1009. def _check_is_permutation(indices, n_samples):
  1010. """Check whether indices is a reordering of the array np.arange(n_samples)
  1011. Parameters
  1012. ----------
  1013. indices : ndarray
  1014. int array to test
  1015. n_samples : int
  1016. number of expected elements
  1017. Returns
  1018. -------
  1019. is_partition : bool
  1020. True iff sorted(indices) is np.arange(n)
  1021. """
  1022. if len(indices) != n_samples:
  1023. return False
  1024. hit = np.zeros(n_samples, dtype=bool)
  1025. hit[indices] = True
  1026. if not np.all(hit):
  1027. return False
  1028. return True
  1029. @validate_params(
  1030. {
  1031. "estimator": [HasMethods("fit")],
  1032. "X": ["array-like", "sparse matrix"],
  1033. "y": ["array-like", None],
  1034. "groups": ["array-like", None],
  1035. "cv": ["cv_object"],
  1036. "n_permutations": [Interval(Integral, 1, None, closed="left")],
  1037. "n_jobs": [Integral, None],
  1038. "random_state": ["random_state"],
  1039. "verbose": ["verbose"],
  1040. "scoring": [StrOptions(set(get_scorer_names())), callable, None],
  1041. "fit_params": [dict, None],
  1042. },
  1043. prefer_skip_nested_validation=False, # estimator is not validated yet
  1044. )
  1045. def permutation_test_score(
  1046. estimator,
  1047. X,
  1048. y,
  1049. *,
  1050. groups=None,
  1051. cv=None,
  1052. n_permutations=100,
  1053. n_jobs=None,
  1054. random_state=0,
  1055. verbose=0,
  1056. scoring=None,
  1057. fit_params=None,
  1058. ):
  1059. """Evaluate the significance of a cross-validated score with permutations.
  1060. Permutes targets to generate 'randomized data' and compute the empirical
  1061. p-value against the null hypothesis that features and targets are
  1062. independent.
  1063. The p-value represents the fraction of randomized data sets where the
  1064. estimator performed as well or better than in the original data. A small
  1065. p-value suggests that there is a real dependency between features and
  1066. targets which has been used by the estimator to give good predictions.
  1067. A large p-value may be due to lack of real dependency between features
  1068. and targets or the estimator was not able to use the dependency to
  1069. give good predictions.
  1070. Read more in the :ref:`User Guide <permutation_test_score>`.
  1071. Parameters
  1072. ----------
  1073. estimator : estimator object implementing 'fit'
  1074. The object to use to fit the data.
  1075. X : array-like of shape at least 2D
  1076. The data to fit.
  1077. y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
  1078. The target variable to try to predict in the case of
  1079. supervised learning.
  1080. groups : array-like of shape (n_samples,), default=None
  1081. Labels to constrain permutation within groups, i.e. ``y`` values
  1082. are permuted among samples with the same group identifier.
  1083. When not specified, ``y`` values are permuted among all samples.
  1084. When a grouped cross-validator is used, the group labels are
  1085. also passed on to the ``split`` method of the cross-validator. The
  1086. cross-validator uses them for grouping the samples while splitting
  1087. the dataset into train/test set.
  1088. cv : int, cross-validation generator or an iterable, default=None
  1089. Determines the cross-validation splitting strategy.
  1090. Possible inputs for cv are:
  1091. - `None`, to use the default 5-fold cross validation,
  1092. - int, to specify the number of folds in a `(Stratified)KFold`,
  1093. - :term:`CV splitter`,
  1094. - An iterable yielding (train, test) splits as arrays of indices.
  1095. For `int`/`None` inputs, if the estimator is a classifier and `y` is
  1096. either binary or multiclass, :class:`StratifiedKFold` is used. In all
  1097. other cases, :class:`KFold` is used. These splitters are instantiated
  1098. with `shuffle=False` so the splits will be the same across calls.
  1099. Refer :ref:`User Guide <cross_validation>` for the various
  1100. cross-validation strategies that can be used here.
  1101. .. versionchanged:: 0.22
  1102. `cv` default value if `None` changed from 3-fold to 5-fold.
  1103. n_permutations : int, default=100
  1104. Number of times to permute ``y``.
  1105. n_jobs : int, default=None
  1106. Number of jobs to run in parallel. Training the estimator and computing
  1107. the cross-validated score are parallelized over the permutations.
  1108. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  1109. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  1110. for more details.
  1111. random_state : int, RandomState instance or None, default=0
  1112. Pass an int for reproducible output for permutation of
  1113. ``y`` values among samples. See :term:`Glossary <random_state>`.
  1114. verbose : int, default=0
  1115. The verbosity level.
  1116. scoring : str or callable, default=None
  1117. A single str (see :ref:`scoring_parameter`) or a callable
  1118. (see :ref:`scoring`) to evaluate the predictions on the test set.
  1119. If `None` the estimator's score method is used.
  1120. fit_params : dict, default=None
  1121. Parameters to pass to the fit method of the estimator.
  1122. .. versionadded:: 0.24
  1123. Returns
  1124. -------
  1125. score : float
  1126. The true score without permuting targets.
  1127. permutation_scores : array of shape (n_permutations,)
  1128. The scores obtained for each permutations.
  1129. pvalue : float
  1130. The p-value, which approximates the probability that the score would
  1131. be obtained by chance. This is calculated as:
  1132. `(C + 1) / (n_permutations + 1)`
  1133. Where C is the number of permutations whose score >= the true score.
  1134. The best possible p-value is 1/(n_permutations + 1), the worst is 1.0.
  1135. Notes
  1136. -----
  1137. This function implements Test 1 in:
  1138. Ojala and Garriga. `Permutation Tests for Studying Classifier
  1139. Performance
  1140. <http://www.jmlr.org/papers/volume11/ojala10a/ojala10a.pdf>`_. The
  1141. Journal of Machine Learning Research (2010) vol. 11
  1142. """
  1143. X, y, groups = indexable(X, y, groups)
  1144. cv = check_cv(cv, y, classifier=is_classifier(estimator))
  1145. scorer = check_scoring(estimator, scoring=scoring)
  1146. random_state = check_random_state(random_state)
  1147. # We clone the estimator to make sure that all the folds are
  1148. # independent, and that it is pickle-able.
  1149. score = _permutation_test_score(
  1150. clone(estimator), X, y, groups, cv, scorer, fit_params=fit_params
  1151. )
  1152. permutation_scores = Parallel(n_jobs=n_jobs, verbose=verbose)(
  1153. delayed(_permutation_test_score)(
  1154. clone(estimator),
  1155. X,
  1156. _shuffle(y, groups, random_state),
  1157. groups,
  1158. cv,
  1159. scorer,
  1160. fit_params=fit_params,
  1161. )
  1162. for _ in range(n_permutations)
  1163. )
  1164. permutation_scores = np.array(permutation_scores)
  1165. pvalue = (np.sum(permutation_scores >= score) + 1.0) / (n_permutations + 1)
  1166. return score, permutation_scores, pvalue
  1167. def _permutation_test_score(estimator, X, y, groups, cv, scorer, fit_params):
  1168. """Auxiliary function for permutation_test_score"""
  1169. # Adjust length of sample weights
  1170. fit_params = fit_params if fit_params is not None else {}
  1171. avg_score = []
  1172. for train, test in cv.split(X, y, groups):
  1173. X_train, y_train = _safe_split(estimator, X, y, train)
  1174. X_test, y_test = _safe_split(estimator, X, y, test, train)
  1175. fit_params = _check_fit_params(X, fit_params, train)
  1176. estimator.fit(X_train, y_train, **fit_params)
  1177. avg_score.append(scorer(estimator, X_test, y_test))
  1178. return np.mean(avg_score)
  1179. def _shuffle(y, groups, random_state):
  1180. """Return a shuffled copy of y eventually shuffle among same groups."""
  1181. if groups is None:
  1182. indices = random_state.permutation(len(y))
  1183. else:
  1184. indices = np.arange(len(groups))
  1185. for group in np.unique(groups):
  1186. this_mask = groups == group
  1187. indices[this_mask] = random_state.permutation(indices[this_mask])
  1188. return _safe_indexing(y, indices)
  1189. @validate_params(
  1190. {
  1191. "estimator": [HasMethods(["fit"])],
  1192. "X": ["array-like", "sparse matrix"],
  1193. "y": ["array-like", None],
  1194. "groups": ["array-like", None],
  1195. "train_sizes": ["array-like"],
  1196. "cv": ["cv_object"],
  1197. "scoring": [StrOptions(set(get_scorer_names())), callable, None],
  1198. "exploit_incremental_learning": ["boolean"],
  1199. "n_jobs": [Integral, None],
  1200. "pre_dispatch": [Integral, str],
  1201. "verbose": ["verbose"],
  1202. "shuffle": ["boolean"],
  1203. "random_state": ["random_state"],
  1204. "error_score": [StrOptions({"raise"}), Real],
  1205. "return_times": ["boolean"],
  1206. "fit_params": [dict, None],
  1207. },
  1208. prefer_skip_nested_validation=False, # estimator is not validated yet
  1209. )
  1210. def learning_curve(
  1211. estimator,
  1212. X,
  1213. y,
  1214. *,
  1215. groups=None,
  1216. train_sizes=np.linspace(0.1, 1.0, 5),
  1217. cv=None,
  1218. scoring=None,
  1219. exploit_incremental_learning=False,
  1220. n_jobs=None,
  1221. pre_dispatch="all",
  1222. verbose=0,
  1223. shuffle=False,
  1224. random_state=None,
  1225. error_score=np.nan,
  1226. return_times=False,
  1227. fit_params=None,
  1228. ):
  1229. """Learning curve.
  1230. Determines cross-validated training and test scores for different training
  1231. set sizes.
  1232. A cross-validation generator splits the whole dataset k times in training
  1233. and test data. Subsets of the training set with varying sizes will be used
  1234. to train the estimator and a score for each training subset size and the
  1235. test set will be computed. Afterwards, the scores will be averaged over
  1236. all k runs for each training subset size.
  1237. Read more in the :ref:`User Guide <learning_curve>`.
  1238. Parameters
  1239. ----------
  1240. estimator : object type that implements the "fit" method
  1241. An object of that type which is cloned for each validation. It must
  1242. also implement "predict" unless `scoring` is a callable that doesn't
  1243. rely on "predict" to compute a score.
  1244. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  1245. Training vector, where `n_samples` is the number of samples and
  1246. `n_features` is the number of features.
  1247. y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
  1248. Target relative to X for classification or regression;
  1249. None for unsupervised learning.
  1250. groups : array-like of shape (n_samples,), default=None
  1251. Group labels for the samples used while splitting the dataset into
  1252. train/test set. Only used in conjunction with a "Group" :term:`cv`
  1253. instance (e.g., :class:`GroupKFold`).
  1254. train_sizes : array-like of shape (n_ticks,), \
  1255. default=np.linspace(0.1, 1.0, 5)
  1256. Relative or absolute numbers of training examples that will be used to
  1257. generate the learning curve. If the dtype is float, it is regarded as a
  1258. fraction of the maximum size of the training set (that is determined
  1259. by the selected validation method), i.e. it has to be within (0, 1].
  1260. Otherwise it is interpreted as absolute sizes of the training sets.
  1261. Note that for classification the number of samples usually have to
  1262. be big enough to contain at least one sample from each class.
  1263. cv : int, cross-validation generator or an iterable, default=None
  1264. Determines the cross-validation splitting strategy.
  1265. Possible inputs for cv are:
  1266. - None, to use the default 5-fold cross validation,
  1267. - int, to specify the number of folds in a `(Stratified)KFold`,
  1268. - :term:`CV splitter`,
  1269. - An iterable yielding (train, test) splits as arrays of indices.
  1270. For int/None inputs, if the estimator is a classifier and ``y`` is
  1271. either binary or multiclass, :class:`StratifiedKFold` is used. In all
  1272. other cases, :class:`KFold` is used. These splitters are instantiated
  1273. with `shuffle=False` so the splits will be the same across calls.
  1274. Refer :ref:`User Guide <cross_validation>` for the various
  1275. cross-validation strategies that can be used here.
  1276. .. versionchanged:: 0.22
  1277. ``cv`` default value if None changed from 3-fold to 5-fold.
  1278. scoring : str or callable, default=None
  1279. A str (see model evaluation documentation) or
  1280. a scorer callable object / function with signature
  1281. ``scorer(estimator, X, y)``.
  1282. exploit_incremental_learning : bool, default=False
  1283. If the estimator supports incremental learning, this will be
  1284. used to speed up fitting for different training set sizes.
  1285. n_jobs : int, default=None
  1286. Number of jobs to run in parallel. Training the estimator and computing
  1287. the score are parallelized over the different training and test sets.
  1288. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  1289. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  1290. for more details.
  1291. pre_dispatch : int or str, default='all'
  1292. Number of predispatched jobs for parallel execution (default is
  1293. all). The option can reduce the allocated memory. The str can
  1294. be an expression like '2*n_jobs'.
  1295. verbose : int, default=0
  1296. Controls the verbosity: the higher, the more messages.
  1297. shuffle : bool, default=False
  1298. Whether to shuffle training data before taking prefixes of it
  1299. based on``train_sizes``.
  1300. random_state : int, RandomState instance or None, default=None
  1301. Used when ``shuffle`` is True. Pass an int for reproducible
  1302. output across multiple function calls.
  1303. See :term:`Glossary <random_state>`.
  1304. error_score : 'raise' or numeric, default=np.nan
  1305. Value to assign to the score if an error occurs in estimator fitting.
  1306. If set to 'raise', the error is raised.
  1307. If a numeric value is given, FitFailedWarning is raised.
  1308. .. versionadded:: 0.20
  1309. return_times : bool, default=False
  1310. Whether to return the fit and score times.
  1311. fit_params : dict, default=None
  1312. Parameters to pass to the fit method of the estimator.
  1313. .. versionadded:: 0.24
  1314. Returns
  1315. -------
  1316. train_sizes_abs : array of shape (n_unique_ticks,)
  1317. Numbers of training examples that has been used to generate the
  1318. learning curve. Note that the number of ticks might be less
  1319. than n_ticks because duplicate entries will be removed.
  1320. train_scores : array of shape (n_ticks, n_cv_folds)
  1321. Scores on training sets.
  1322. test_scores : array of shape (n_ticks, n_cv_folds)
  1323. Scores on test set.
  1324. fit_times : array of shape (n_ticks, n_cv_folds)
  1325. Times spent for fitting in seconds. Only present if ``return_times``
  1326. is True.
  1327. score_times : array of shape (n_ticks, n_cv_folds)
  1328. Times spent for scoring in seconds. Only present if ``return_times``
  1329. is True.
  1330. Examples
  1331. --------
  1332. >>> from sklearn.datasets import make_classification
  1333. >>> from sklearn.tree import DecisionTreeClassifier
  1334. >>> from sklearn.model_selection import learning_curve
  1335. >>> X, y = make_classification(n_samples=100, n_features=10, random_state=42)
  1336. >>> tree = DecisionTreeClassifier(max_depth=4, random_state=42)
  1337. >>> train_size_abs, train_scores, test_scores = learning_curve(
  1338. ... tree, X, y, train_sizes=[0.3, 0.6, 0.9]
  1339. ... )
  1340. >>> for train_size, cv_train_scores, cv_test_scores in zip(
  1341. ... train_size_abs, train_scores, test_scores
  1342. ... ):
  1343. ... print(f"{train_size} samples were used to train the model")
  1344. ... print(f"The average train accuracy is {cv_train_scores.mean():.2f}")
  1345. ... print(f"The average test accuracy is {cv_test_scores.mean():.2f}")
  1346. 24 samples were used to train the model
  1347. The average train accuracy is 1.00
  1348. The average test accuracy is 0.85
  1349. 48 samples were used to train the model
  1350. The average train accuracy is 1.00
  1351. The average test accuracy is 0.90
  1352. 72 samples were used to train the model
  1353. The average train accuracy is 1.00
  1354. The average test accuracy is 0.93
  1355. """
  1356. if exploit_incremental_learning and not hasattr(estimator, "partial_fit"):
  1357. raise ValueError(
  1358. "An estimator must support the partial_fit interface "
  1359. "to exploit incremental learning"
  1360. )
  1361. X, y, groups = indexable(X, y, groups)
  1362. cv = check_cv(cv, y, classifier=is_classifier(estimator))
  1363. # Store it as list as we will be iterating over the list multiple times
  1364. cv_iter = list(cv.split(X, y, groups))
  1365. scorer = check_scoring(estimator, scoring=scoring)
  1366. n_max_training_samples = len(cv_iter[0][0])
  1367. # Because the lengths of folds can be significantly different, it is
  1368. # not guaranteed that we use all of the available training data when we
  1369. # use the first 'n_max_training_samples' samples.
  1370. train_sizes_abs = _translate_train_sizes(train_sizes, n_max_training_samples)
  1371. n_unique_ticks = train_sizes_abs.shape[0]
  1372. if verbose > 0:
  1373. print("[learning_curve] Training set sizes: " + str(train_sizes_abs))
  1374. parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, verbose=verbose)
  1375. if shuffle:
  1376. rng = check_random_state(random_state)
  1377. cv_iter = ((rng.permutation(train), test) for train, test in cv_iter)
  1378. if exploit_incremental_learning:
  1379. classes = np.unique(y) if is_classifier(estimator) else None
  1380. out = parallel(
  1381. delayed(_incremental_fit_estimator)(
  1382. clone(estimator),
  1383. X,
  1384. y,
  1385. classes,
  1386. train,
  1387. test,
  1388. train_sizes_abs,
  1389. scorer,
  1390. verbose,
  1391. return_times,
  1392. error_score=error_score,
  1393. fit_params=fit_params,
  1394. )
  1395. for train, test in cv_iter
  1396. )
  1397. out = np.asarray(out).transpose((2, 1, 0))
  1398. else:
  1399. train_test_proportions = []
  1400. for train, test in cv_iter:
  1401. for n_train_samples in train_sizes_abs:
  1402. train_test_proportions.append((train[:n_train_samples], test))
  1403. results = parallel(
  1404. delayed(_fit_and_score)(
  1405. clone(estimator),
  1406. X,
  1407. y,
  1408. scorer,
  1409. train,
  1410. test,
  1411. verbose,
  1412. parameters=None,
  1413. fit_params=fit_params,
  1414. return_train_score=True,
  1415. error_score=error_score,
  1416. return_times=return_times,
  1417. )
  1418. for train, test in train_test_proportions
  1419. )
  1420. results = _aggregate_score_dicts(results)
  1421. train_scores = results["train_scores"].reshape(-1, n_unique_ticks).T
  1422. test_scores = results["test_scores"].reshape(-1, n_unique_ticks).T
  1423. out = [train_scores, test_scores]
  1424. if return_times:
  1425. fit_times = results["fit_time"].reshape(-1, n_unique_ticks).T
  1426. score_times = results["score_time"].reshape(-1, n_unique_ticks).T
  1427. out.extend([fit_times, score_times])
  1428. ret = train_sizes_abs, out[0], out[1]
  1429. if return_times:
  1430. ret = ret + (out[2], out[3])
  1431. return ret
  1432. def _translate_train_sizes(train_sizes, n_max_training_samples):
  1433. """Determine absolute sizes of training subsets and validate 'train_sizes'.
  1434. Examples:
  1435. _translate_train_sizes([0.5, 1.0], 10) -> [5, 10]
  1436. _translate_train_sizes([5, 10], 10) -> [5, 10]
  1437. Parameters
  1438. ----------
  1439. train_sizes : array-like of shape (n_ticks,)
  1440. Numbers of training examples that will be used to generate the
  1441. learning curve. If the dtype is float, it is regarded as a
  1442. fraction of 'n_max_training_samples', i.e. it has to be within (0, 1].
  1443. n_max_training_samples : int
  1444. Maximum number of training samples (upper bound of 'train_sizes').
  1445. Returns
  1446. -------
  1447. train_sizes_abs : array of shape (n_unique_ticks,)
  1448. Numbers of training examples that will be used to generate the
  1449. learning curve. Note that the number of ticks might be less
  1450. than n_ticks because duplicate entries will be removed.
  1451. """
  1452. train_sizes_abs = np.asarray(train_sizes)
  1453. n_ticks = train_sizes_abs.shape[0]
  1454. n_min_required_samples = np.min(train_sizes_abs)
  1455. n_max_required_samples = np.max(train_sizes_abs)
  1456. if np.issubdtype(train_sizes_abs.dtype, np.floating):
  1457. if n_min_required_samples <= 0.0 or n_max_required_samples > 1.0:
  1458. raise ValueError(
  1459. "train_sizes has been interpreted as fractions "
  1460. "of the maximum number of training samples and "
  1461. "must be within (0, 1], but is within [%f, %f]."
  1462. % (n_min_required_samples, n_max_required_samples)
  1463. )
  1464. train_sizes_abs = (train_sizes_abs * n_max_training_samples).astype(
  1465. dtype=int, copy=False
  1466. )
  1467. train_sizes_abs = np.clip(train_sizes_abs, 1, n_max_training_samples)
  1468. else:
  1469. if (
  1470. n_min_required_samples <= 0
  1471. or n_max_required_samples > n_max_training_samples
  1472. ):
  1473. raise ValueError(
  1474. "train_sizes has been interpreted as absolute "
  1475. "numbers of training samples and must be within "
  1476. "(0, %d], but is within [%d, %d]."
  1477. % (
  1478. n_max_training_samples,
  1479. n_min_required_samples,
  1480. n_max_required_samples,
  1481. )
  1482. )
  1483. train_sizes_abs = np.unique(train_sizes_abs)
  1484. if n_ticks > train_sizes_abs.shape[0]:
  1485. warnings.warn(
  1486. "Removed duplicate entries from 'train_sizes'. Number "
  1487. "of ticks will be less than the size of "
  1488. "'train_sizes': %d instead of %d." % (train_sizes_abs.shape[0], n_ticks),
  1489. RuntimeWarning,
  1490. )
  1491. return train_sizes_abs
  1492. def _incremental_fit_estimator(
  1493. estimator,
  1494. X,
  1495. y,
  1496. classes,
  1497. train,
  1498. test,
  1499. train_sizes,
  1500. scorer,
  1501. verbose,
  1502. return_times,
  1503. error_score,
  1504. fit_params,
  1505. ):
  1506. """Train estimator on training subsets incrementally and compute scores."""
  1507. train_scores, test_scores, fit_times, score_times = [], [], [], []
  1508. partitions = zip(train_sizes, np.split(train, train_sizes)[:-1])
  1509. if fit_params is None:
  1510. fit_params = {}
  1511. if classes is None:
  1512. partial_fit_func = partial(estimator.partial_fit, **fit_params)
  1513. else:
  1514. partial_fit_func = partial(estimator.partial_fit, classes=classes, **fit_params)
  1515. for n_train_samples, partial_train in partitions:
  1516. train_subset = train[:n_train_samples]
  1517. X_train, y_train = _safe_split(estimator, X, y, train_subset)
  1518. X_partial_train, y_partial_train = _safe_split(estimator, X, y, partial_train)
  1519. X_test, y_test = _safe_split(estimator, X, y, test, train_subset)
  1520. start_fit = time.time()
  1521. if y_partial_train is None:
  1522. partial_fit_func(X_partial_train)
  1523. else:
  1524. partial_fit_func(X_partial_train, y_partial_train)
  1525. fit_time = time.time() - start_fit
  1526. fit_times.append(fit_time)
  1527. start_score = time.time()
  1528. test_scores.append(_score(estimator, X_test, y_test, scorer, error_score))
  1529. train_scores.append(_score(estimator, X_train, y_train, scorer, error_score))
  1530. score_time = time.time() - start_score
  1531. score_times.append(score_time)
  1532. ret = (
  1533. (train_scores, test_scores, fit_times, score_times)
  1534. if return_times
  1535. else (train_scores, test_scores)
  1536. )
  1537. return np.array(ret).T
  1538. @validate_params(
  1539. {
  1540. "estimator": [HasMethods(["fit"])],
  1541. "X": ["array-like", "sparse matrix"],
  1542. "y": ["array-like", None],
  1543. "param_name": [str],
  1544. "param_range": ["array-like"],
  1545. "groups": ["array-like", None],
  1546. "cv": ["cv_object"],
  1547. "scoring": [StrOptions(set(get_scorer_names())), callable, None],
  1548. "n_jobs": [Integral, None],
  1549. "pre_dispatch": [Integral, str],
  1550. "verbose": ["verbose"],
  1551. "error_score": [StrOptions({"raise"}), Real],
  1552. "fit_params": [dict, None],
  1553. },
  1554. prefer_skip_nested_validation=False, # estimator is not validated yet
  1555. )
  1556. def validation_curve(
  1557. estimator,
  1558. X,
  1559. y,
  1560. *,
  1561. param_name,
  1562. param_range,
  1563. groups=None,
  1564. cv=None,
  1565. scoring=None,
  1566. n_jobs=None,
  1567. pre_dispatch="all",
  1568. verbose=0,
  1569. error_score=np.nan,
  1570. fit_params=None,
  1571. ):
  1572. """Validation curve.
  1573. Determine training and test scores for varying parameter values.
  1574. Compute scores for an estimator with different values of a specified
  1575. parameter. This is similar to grid search with one parameter. However, this
  1576. will also compute training scores and is merely a utility for plotting the
  1577. results.
  1578. Read more in the :ref:`User Guide <validation_curve>`.
  1579. Parameters
  1580. ----------
  1581. estimator : object type that implements the "fit" method
  1582. An object of that type which is cloned for each validation. It must
  1583. also implement "predict" unless `scoring` is a callable that doesn't
  1584. rely on "predict" to compute a score.
  1585. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  1586. Training vector, where `n_samples` is the number of samples and
  1587. `n_features` is the number of features.
  1588. y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
  1589. Target relative to X for classification or regression;
  1590. None for unsupervised learning.
  1591. param_name : str
  1592. Name of the parameter that will be varied.
  1593. param_range : array-like of shape (n_values,)
  1594. The values of the parameter that will be evaluated.
  1595. groups : array-like of shape (n_samples,), default=None
  1596. Group labels for the samples used while splitting the dataset into
  1597. train/test set. Only used in conjunction with a "Group" :term:`cv`
  1598. instance (e.g., :class:`GroupKFold`).
  1599. cv : int, cross-validation generator or an iterable, default=None
  1600. Determines the cross-validation splitting strategy.
  1601. Possible inputs for cv are:
  1602. - None, to use the default 5-fold cross validation,
  1603. - int, to specify the number of folds in a `(Stratified)KFold`,
  1604. - :term:`CV splitter`,
  1605. - An iterable yielding (train, test) splits as arrays of indices.
  1606. For int/None inputs, if the estimator is a classifier and ``y`` is
  1607. either binary or multiclass, :class:`StratifiedKFold` is used. In all
  1608. other cases, :class:`KFold` is used. These splitters are instantiated
  1609. with `shuffle=False` so the splits will be the same across calls.
  1610. Refer :ref:`User Guide <cross_validation>` for the various
  1611. cross-validation strategies that can be used here.
  1612. .. versionchanged:: 0.22
  1613. ``cv`` default value if None changed from 3-fold to 5-fold.
  1614. scoring : str or callable, default=None
  1615. A str (see model evaluation documentation) or
  1616. a scorer callable object / function with signature
  1617. ``scorer(estimator, X, y)``.
  1618. n_jobs : int, default=None
  1619. Number of jobs to run in parallel. Training the estimator and computing
  1620. the score are parallelized over the combinations of each parameter
  1621. value and each cross-validation split.
  1622. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
  1623. ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
  1624. for more details.
  1625. pre_dispatch : int or str, default='all'
  1626. Number of predispatched jobs for parallel execution (default is
  1627. all). The option can reduce the allocated memory. The str can
  1628. be an expression like '2*n_jobs'.
  1629. verbose : int, default=0
  1630. Controls the verbosity: the higher, the more messages.
  1631. error_score : 'raise' or numeric, default=np.nan
  1632. Value to assign to the score if an error occurs in estimator fitting.
  1633. If set to 'raise', the error is raised.
  1634. If a numeric value is given, FitFailedWarning is raised.
  1635. .. versionadded:: 0.20
  1636. fit_params : dict, default=None
  1637. Parameters to pass to the fit method of the estimator.
  1638. .. versionadded:: 0.24
  1639. Returns
  1640. -------
  1641. train_scores : array of shape (n_ticks, n_cv_folds)
  1642. Scores on training sets.
  1643. test_scores : array of shape (n_ticks, n_cv_folds)
  1644. Scores on test set.
  1645. Notes
  1646. -----
  1647. See :ref:`sphx_glr_auto_examples_model_selection_plot_validation_curve.py`
  1648. """
  1649. X, y, groups = indexable(X, y, groups)
  1650. cv = check_cv(cv, y, classifier=is_classifier(estimator))
  1651. scorer = check_scoring(estimator, scoring=scoring)
  1652. parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, verbose=verbose)
  1653. results = parallel(
  1654. delayed(_fit_and_score)(
  1655. clone(estimator),
  1656. X,
  1657. y,
  1658. scorer,
  1659. train,
  1660. test,
  1661. verbose,
  1662. parameters={param_name: v},
  1663. fit_params=fit_params,
  1664. return_train_score=True,
  1665. error_score=error_score,
  1666. )
  1667. # NOTE do not change order of iteration to allow one time cv splitters
  1668. for train, test in cv.split(X, y, groups)
  1669. for v in param_range
  1670. )
  1671. n_params = len(param_range)
  1672. results = _aggregate_score_dicts(results)
  1673. train_scores = results["train_scores"].reshape(-1, n_params).T
  1674. test_scores = results["test_scores"].reshape(-1, n_params).T
  1675. return train_scores, test_scores
  1676. def _aggregate_score_dicts(scores):
  1677. """Aggregate the list of dict to dict of np ndarray
  1678. The aggregated output of _aggregate_score_dicts will be a list of dict
  1679. of form [{'prec': 0.1, 'acc':1.0}, {'prec': 0.1, 'acc':1.0}, ...]
  1680. Convert it to a dict of array {'prec': np.array([0.1 ...]), ...}
  1681. Parameters
  1682. ----------
  1683. scores : list of dict
  1684. List of dicts of the scores for all scorers. This is a flat list,
  1685. assumed originally to be of row major order.
  1686. Example
  1687. -------
  1688. >>> scores = [{'a': 1, 'b':10}, {'a': 2, 'b':2}, {'a': 3, 'b':3},
  1689. ... {'a': 10, 'b': 10}] # doctest: +SKIP
  1690. >>> _aggregate_score_dicts(scores) # doctest: +SKIP
  1691. {'a': array([1, 2, 3, 10]),
  1692. 'b': array([10, 2, 3, 10])}
  1693. """
  1694. return {
  1695. key: (
  1696. np.asarray([score[key] for score in scores])
  1697. if isinstance(scores[0][key], numbers.Number)
  1698. else [score[key] for score in scores]
  1699. )
  1700. for key in scores[0]
  1701. }