-
-
Notifications
You must be signed in to change notification settings - Fork 26.9k
Expand file tree
/
Copy path_validation.py
More file actions
2493 lines (2120 loc) · 92.4 KB
/
_validation.py
File metadata and controls
2493 lines (2120 loc) · 92.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
The :mod:`sklearn.model_selection._validation` module includes classes and
functions to validate the model.
"""
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
import numbers
import time
import warnings
from collections import Counter
from contextlib import suppress
from functools import partial
from numbers import Real
from traceback import format_exc
import numpy as np
import scipy.sparse as sp
from joblib import logger
from sklearn.base import clone, is_classifier
from sklearn.exceptions import FitFailedWarning, UnsetMetadataPassedError
from sklearn.metrics import check_scoring, get_scorer_names
from sklearn.metrics._scorer import _MultimetricScorer
from sklearn.model_selection._split import check_cv
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import Bunch, _safe_indexing, check_random_state, indexable
from sklearn.utils._array_api import (
_convert_to_numpy,
device,
get_namespace,
get_namespace_and_device,
move_to,
)
from sklearn.utils._param_validation import (
HasMethods,
Integral,
Interval,
StrOptions,
validate_params,
)
from sklearn.utils.metadata_routing import (
MetadataRouter,
MethodMapping,
_routing_enabled,
process_routing,
)
from sklearn.utils.metaestimators import _safe_split
from sklearn.utils.parallel import Parallel, delayed
from sklearn.utils.validation import _check_method_params, _num_samples
__all__ = [
"cross_val_predict",
"cross_val_score",
"cross_validate",
"learning_curve",
"permutation_test_score",
"validation_curve",
]
# TODO(SLEP6): To be removed when set_config(enable_metadata_routing=False) is not
# possible.
def _check_groups_routing_disabled(groups):
if groups is not None and _routing_enabled():
raise ValueError(
"`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."
)
@validate_params(
{
"estimator": [HasMethods("fit")],
"X": ["array-like", "sparse matrix"],
"y": ["array-like", None],
"groups": ["array-like", None],
"scoring": [
StrOptions(set(get_scorer_names())),
callable,
list,
tuple,
dict,
None,
],
"cv": ["cv_object"],
"n_jobs": [Integral, None],
"verbose": ["verbose"],
"params": [dict, None],
"pre_dispatch": [Integral, str],
"return_train_score": ["boolean"],
"return_estimator": ["boolean"],
"return_indices": ["boolean"],
"error_score": [StrOptions({"raise"}), Real],
},
prefer_skip_nested_validation=False, # estimator is not validated yet
)
def cross_validate(
estimator,
X,
y=None,
*,
groups=None,
scoring=None,
cv=None,
n_jobs=None,
verbose=0,
params=None,
pre_dispatch="2*n_jobs",
return_train_score=False,
return_estimator=False,
return_indices=False,
error_score=np.nan,
):
"""Evaluate metric(s) by cross-validation and also record fit/score times.
Read more in the :ref:`User Guide <multimetric_cross_validation>`.
Parameters
----------
estimator : estimator object implementing 'fit'
The object to use to fit the data.
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to fit. Can be for example a list, or an array.
y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None
The target variable to try to predict in the case of
supervised learning.
groups : array-like of shape (n_samples,), default=None
Group labels for the samples used while splitting the dataset into
train/test set. Only used in conjunction with a "Group" :term:`cv`
instance (e.g., :class:`GroupKFold`).
.. versionchanged:: 1.4
``groups`` can only be passed if metadata routing is not enabled
via ``sklearn.set_config(enable_metadata_routing=True)``. When routing
is enabled, pass ``groups`` alongside other metadata via the ``params``
argument instead. E.g.:
``cross_validate(..., params={'groups': groups})``.
scoring : str, callable, list, tuple, or dict, default=None
Strategy to evaluate the performance of the `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 <scoring_api_overview>` 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 <cross_validation>` for the various
cross-validation strategies that can be used here.
.. versionchanged:: 0.22
``cv`` default value if None changed from 3-fold to 5-fold.
n_jobs : int, default=None
Number of jobs to run in parallel. Training the estimator and computing
the score are parallelized over the cross-validation splits.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
verbose : int, default=0
The verbosity level.
params : dict, default=None
Parameters to pass to the underlying estimator's ``fit``, the scorer,
and the CV splitter.
.. versionadded:: 1.4
pre_dispatch : int or str, default='2*n_jobs'
Controls the number of jobs that get dispatched during parallel
execution. Reducing this number can be useful to avoid an
explosion of memory consumption when more jobs get dispatched
than CPUs can process. This parameter can be:
- An int, giving the exact number of total jobs that are spawned
- A str, giving an expression as a function of n_jobs, as in '2*n_jobs'
return_train_score : bool, default=False
Whether to include train scores.
Computing training scores is used to get insights on how different
parameter settings impact the overfitting/underfitting trade-off.
However computing the scores on the training set can be computationally
expensive and is not strictly required to select the parameters that
yield the best generalization performance.
.. versionadded:: 0.19
.. versionchanged:: 0.21
Default value was changed from ``True`` to ``False``
return_estimator : bool, default=False
Whether to return the estimators fitted on each split.
.. versionadded:: 0.20
return_indices : bool, default=False
Whether to return the train-test indices selected for each split.
.. versionadded:: 1.3
error_score : 'raise' or numeric, default=np.nan
Value to assign to the score if an error occurs in estimator fitting.
If set to 'raise', the error is raised.
If a numeric value is given, FitFailedWarning is raised.
.. versionadded:: 0.20
Returns
-------
scores : dict of float arrays of shape (n_splits,)
Array of scores of the estimator for each run of the cross validation.
A dict of arrays containing the score/time arrays for each scorer is
returned. The possible keys for this ``dict`` are:
``test_score``
The score array for test scores on each cv split.
Suffix ``_score`` in ``test_score`` changes to a specific
metric like ``test_r2`` or ``test_auc`` if there are
multiple scoring metrics in the scoring parameter.
``train_score``
The score array for train scores on each cv split.
Suffix ``_score`` in ``train_score`` changes to a specific
metric like ``train_r2`` or ``train_auc`` if there are
multiple scoring metrics in the scoring parameter.
This is available only if ``return_train_score`` parameter
is ``True``.
``fit_time``
The time for fitting the estimator on the train
set for each cv split.
``score_time``
The time for scoring the estimator on the test set for each
cv split. (Note: time for scoring on the train set is not
included even if ``return_train_score`` is set to ``True``).
``estimator``
The estimator objects for each cv split.
This is available only if ``return_estimator`` parameter
is set to ``True``.
``indices``
The train/test positional indices for each cv split. A dictionary
is returned where the keys are either `"train"` or `"test"`
and the associated values are a list of integer-dtyped NumPy
arrays with the indices. Available only if `return_indices=True`.
See Also
--------
cross_val_score : Run cross-validation for single metric evaluation.
cross_val_predict : Get predictions from each split of cross-validation for
diagnostic purposes.
sklearn.metrics.make_scorer : Make a scorer from a performance metric or
loss function.
Examples
--------
>>> from sklearn import datasets, linear_model
>>> from sklearn.model_selection import cross_validate
>>> 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]
"""
_check_groups_routing_disabled(groups)
X, y = indexable(X, y)
params = {} if params is None else params
cv = check_cv(cv, y, classifier=is_classifier(estimator))
scorers = check_scoring(
estimator, scoring=scoring, raise_exc=(error_score == "raise")
)
if _routing_enabled():
# For estimators, a MetadataRouter is created in get_metadata_routing
# methods. For these router methods, we create the router to use
# `process_routing` on it.
router = (
MetadataRouter(owner="cross_validate")
.add(
splitter=cv,
method_mapping=MethodMapping().add(caller="fit", callee="split"),
)
.add(
estimator=estimator,
# TODO(SLEP6): also pass metadata to the predict method for
# scoring?
method_mapping=MethodMapping().add(caller="fit", callee="fit"),
)
.add(
scorer=scorers,
method_mapping=MethodMapping().add(caller="fit", callee="score"),
)
)
try:
routed_params = process_routing(router, "fit", **params)
except UnsetMetadataPassedError as e:
# The default exception would mention `fit` since in the above
# `process_routing` code, we pass `fit` as the caller. However,
# the user is not calling `fit` directly, so we change the message
# to make it more suitable for this case.
raise UnsetMetadataPassedError(
message=str(e).replace("cross_validate.fit", "cross_validate"),
unrequested_params=e.unrequested_params,
routed_params=e.routed_params,
)
else:
routed_params = Bunch()
routed_params.splitter = Bunch(split={"groups": groups})
routed_params.estimator = Bunch(fit=params)
routed_params.scorer = Bunch(score={})
indices = cv.split(X, y, **routed_params.splitter.split)
if return_indices:
# materialize the indices since we need to store them in the returned dict
indices = list(indices)
# We clone the estimator to make sure that all the folds are
# independent, and that it is pickle-able.
parallel = Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch)
results = parallel(
delayed(_fit_and_score)(
clone(estimator),
X,
y,
scorer=scorers,
train=train,
test=test,
verbose=verbose,
parameters=None,
fit_params=routed_params.estimator.fit,
score_params=routed_params.scorer.score,
return_train_score=return_train_score,
return_times=True,
return_estimator=return_estimator,
error_score=error_score,
)
for train, test in indices
)
_warn_or_raise_about_fit_failures(results, error_score)
# For callable scoring, the return type is only know after calling. If the
# return type is a dictionary, the error scores can now be inserted with
# the correct key.
if callable(scoring):
_insert_error_scores(results, error_score)
results = _aggregate_score_dicts(results)
ret = {}
ret["fit_time"] = results["fit_time"]
ret["score_time"] = results["score_time"]
if return_estimator:
ret["estimator"] = results["estimator"]
if return_indices:
ret["indices"] = {}
ret["indices"]["train"], ret["indices"]["test"] = zip(*indices)
test_scores_dict = _normalize_score_results(results["test_scores"])
if return_train_score:
train_scores_dict = _normalize_score_results(results["train_scores"])
for name in test_scores_dict:
ret["test_%s" % name] = test_scores_dict[name]
if return_train_score:
key = "train_%s" % name
ret[key] = train_scores_dict[name]
return ret
def _insert_error_scores(results, error_score):
"""Insert 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.
"""
successful_score = None
failed_indices = []
for i, result in enumerate(results):
if result["fit_error"] is not None:
failed_indices.append(i)
elif successful_score is None:
successful_score = result["test_scores"]
if isinstance(successful_score, dict):
formatted_error = {name: error_score for name in successful_score}
for i in failed_indices:
results[i]["test_scores"] = formatted_error.copy()
if "train_scores" in results[i]:
results[i]["train_scores"] = formatted_error.copy()
def _normalize_score_results(scores, scaler_score_key="score"):
"""Creates a scoring dictionary based on the type of `scores`"""
if isinstance(scores[0], dict):
# multimetric scoring
return _aggregate_score_dicts(scores)
# scaler
return {scaler_score_key: scores}
def _warn_or_raise_about_fit_failures(results, error_score):
fit_errors = [
result["fit_error"] for result in results if result["fit_error"] is not None
]
if fit_errors:
num_failed_fits = len(fit_errors)
num_fits = len(results)
fit_errors_counter = Counter(fit_errors)
delimiter = "-" * 80 + "\n"
fit_errors_summary = "\n".join(
f"{delimiter}{n} fits failed with the following error:\n{error}"
for error, n in fit_errors_counter.items()
)
if num_failed_fits == num_fits:
all_fits_failed_message = (
f"\nAll the {num_fits} fits failed.\n"
"It is very likely that your model is misconfigured.\n"
"You can try to debug the error by setting error_score='raise'.\n\n"
f"Below are more details about the failures:\n{fit_errors_summary}"
)
raise ValueError(all_fits_failed_message)
else:
some_fits_failed_message = (
f"\n{num_failed_fits} fits failed out of a total of {num_fits}.\n"
"The score on these train-test partitions for these parameters"
f" will be set to {error_score}.\n"
"If these failures are not expected, you can try to debug them "
"by setting error_score='raise'.\n\n"
f"Below are more details about the failures:\n{fit_errors_summary}"
)
warnings.warn(some_fits_failed_message, FitFailedWarning)
@validate_params(
{
"estimator": [HasMethods("fit")],
"X": ["array-like", "sparse matrix"],
"y": ["array-like", None],
"groups": ["array-like", None],
"scoring": [StrOptions(set(get_scorer_names())), callable, None],
"cv": ["cv_object"],
"n_jobs": [Integral, None],
"verbose": ["verbose"],
"params": [dict, None],
"pre_dispatch": [Integral, str, None],
"error_score": [StrOptions({"raise"}), Real],
},
prefer_skip_nested_validation=False, # estimator is not validated yet
)
def cross_val_score(
estimator,
X,
y=None,
*,
groups=None,
scoring=None,
cv=None,
n_jobs=None,
verbose=0,
params=None,
pre_dispatch="2*n_jobs",
error_score=np.nan,
):
"""Evaluate a score by cross-validation.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
estimator : estimator object implementing 'fit'
The object to use to fit the data.
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The data to fit. Can be for example a list, or an array.
y : array-like of shape (n_samples,) or (n_samples, n_outputs), \
default=None
The target variable to try to predict in the case of
supervised learning.
groups : array-like of shape (n_samples,), default=None
Group labels for the samples used while splitting the dataset into
train/test set. Only used in conjunction with a "Group" :term:`cv`
instance (e.g., :class:`GroupKFold`).
.. versionchanged:: 1.4
``groups`` can only be passed if metadata routing is not enabled
via ``sklearn.set_config(enable_metadata_routing=True)``. When routing
is enabled, pass ``groups`` alongside other metadata via the ``params``
argument instead. E.g.:
``cross_val_score(..., params={'groups': groups})``.
scoring : str or callable, default=None
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 <scoring_api_overview>` 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 <cross_validation>` for the various
cross-validation strategies that can be used here.
.. versionchanged:: 0.22
`cv` default value if `None` changed from 3-fold to 5-fold.
n_jobs : int, default=None
Number of jobs to run in parallel. Training the estimator and computing
the score are parallelized over the cross-validation splits.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
verbose : int, default=0
The verbosity level.
params : dict, default=None
Parameters to pass to the underlying estimator's ``fit``, the scorer,
and the CV splitter.
.. versionadded:: 1.4
pre_dispatch : int or str, default='2*n_jobs'
Controls the number of jobs that get dispatched during parallel
execution. Reducing this number can be useful to avoid an
explosion of memory consumption when more jobs get dispatched
than CPUs can process. This parameter can be:
- ``None``, in which case all the jobs are immediately created and spawned. Use
this for lightweight and fast-running jobs, to avoid delays due to on-demand
spawning of the jobs
- An int, giving the exact number of total jobs that are spawned
- A str, giving an expression as a function of n_jobs, as in '2*n_jobs'
error_score : 'raise' or numeric, default=np.nan
Value to assign to the score if an error occurs in estimator fitting.
If set to 'raise', the error is raised.
If a numeric value is given, FitFailedWarning is raised.
.. versionadded:: 0.20
Returns
-------
scores : ndarray of float of shape=(len(list(cv)),)
Array of scores of the estimator for each run of the cross validation.
See Also
--------
cross_validate : To run cross-validation on multiple metrics and also to
return train scores, fit times and score times.
cross_val_predict : Get predictions from each split of cross-validation for
diagnostic purposes.
sklearn.metrics.make_scorer : Make a scorer from a performance metric or
loss function.
Examples
--------
>>> from sklearn import datasets, linear_model
>>> from sklearn.model_selection import cross_val_score
>>> diabetes = datasets.load_diabetes()
>>> X = diabetes.data[:150]
>>> y = diabetes.target[:150]
>>> lasso = linear_model.Lasso()
>>> print(cross_val_score(lasso, X, y, cv=3))
[0.3315057 0.08022103 0.03531816]
"""
# To ensure multimetric format is not supported
scorer = check_scoring(estimator, scoring=scoring)
cv_results = cross_validate(
estimator=estimator,
X=X,
y=y,
groups=groups,
scoring={"score": scorer},
cv=cv,
n_jobs=n_jobs,
verbose=verbose,
params=params,
pre_dispatch=pre_dispatch,
error_score=error_score,
)
return cv_results["test_score"]
def _fit_and_score(
estimator,
X,
y,
*,
scorer,
train,
test,
verbose,
parameters,
fit_params,
score_params,
return_train_score=False,
return_parameters=False,
return_n_test_samples=False,
return_times=False,
return_estimator=False,
split_progress=None,
candidate_progress=None,
error_score=np.nan,
):
"""Fit estimator and compute scores for a given dataset split.
Parameters
----------
estimator : estimator object implementing 'fit'
The object to use to fit the data.
X : array-like of shape (n_samples, n_features)
The data to fit.
y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
The target variable to try to predict in the case of
supervised learning.
scorer : A single callable or dict mapping scorer name to the callable
If it is a single callable, the return value for ``train_scores`` and
``test_scores`` is a single float.
For a dict, it should be one mapping the scorer name to the scorer
callable object / function.
The callable object / fn should have signature
``scorer(estimator, X, y)``.
train : array-like of shape (n_train_samples,)
Indices of training samples.
test : array-like of shape (n_test_samples,)
Indices of test samples.
verbose : int
The verbosity level.
error_score : 'raise' or numeric, default=np.nan
Value to assign to the score if an error occurs in estimator fitting.
If set to 'raise', the error is raised.
If a numeric value is given, FitFailedWarning is raised.
parameters : dict or None
Parameters to be set on the estimator.
fit_params : dict or None
Parameters that will be passed to ``estimator.fit``.
score_params : dict or None
Parameters that will be passed to the scorer.
return_train_score : bool, default=False
Compute and return score on training set.
return_parameters : bool, default=False
Return parameters that has been used for the estimator.
split_progress : {list, tuple} of int, default=None
A list or tuple of format (<current_split_id>, <total_num_of_splits>).
candidate_progress : {list, tuple} of int, default=None
A list or tuple of format
(<current_candidate_id>, <total_number_of_candidates>).
return_n_test_samples : bool, default=False
Whether to return the ``n_test_samples``.
return_times : bool, default=False
Whether to return the fit/score times.
return_estimator : bool, default=False
Whether to return the fitted estimator.
Returns
-------
result : dict with the following attributes
train_scores : dict of scorer name -> float
Score on training set (for all the scorers),
returned only if `return_train_score` is `True`.
test_scores : dict of scorer name -> float
Score on testing set (for all the scorers).
n_test_samples : int
Number of test samples.
fit_time : float
Time spent for fitting in seconds.
score_time : float
Time spent for scoring in seconds.
parameters : dict or None
The parameters that have been evaluated.
estimator : estimator object
The fitted estimator.
fit_error : str or None
Traceback str if the fit failed, None if the fit succeeded.
"""
xp, _ = get_namespace(X)
X_device = device(X)
# Make sure that we can fancy index X even if train and test are provided
# as NumPy arrays by NumPy only cross-validation splitters.
train, test = xp.asarray(train, device=X_device), xp.asarray(test, device=X_device)
if not isinstance(error_score, numbers.Number) and error_score != "raise":
raise ValueError(
"error_score must be the string 'raise' or a numeric value. "
"(Hint: if using 'raise', please make sure that it has been "
"spelled correctly.)"
)
progress_msg = ""
if verbose > 2:
if split_progress is not None:
progress_msg = f" {split_progress[0] + 1}/{split_progress[1]}"
if candidate_progress and verbose > 9:
progress_msg += f"; {candidate_progress[0] + 1}/{candidate_progress[1]}"
if verbose > 1:
if parameters is None:
params_msg = ""
else:
sorted_keys = sorted(parameters) # Ensure deterministic o/p
params_msg = ", ".join(f"{k}={parameters[k]}" for k in sorted_keys)
if verbose > 9:
start_msg = f"[CV{progress_msg}] START {params_msg}"
print(f"{start_msg}{(80 - len(start_msg)) * '.'}")
# Adjust length of sample weights
fit_params = fit_params if fit_params is not None else {}
fit_params = _check_method_params(X, params=fit_params, indices=train)
score_params = score_params if score_params is not None else {}
score_params_train = _check_method_params(X, params=score_params, indices=train)
score_params_test = _check_method_params(X, params=score_params, indices=test)
if parameters is not None:
# here we clone the parameters, since sometimes the parameters
# themselves might be estimators, e.g. when we search over different
# estimators in a pipeline.
# ref: https://github.com/scikit-learn/scikit-learn/pull/26786
estimator = estimator.set_params(**clone(parameters, safe=False))
start_time = time.time()
X_train, y_train = _safe_split(estimator, X, y, train)
X_test, y_test = _safe_split(estimator, X, y, test, train)
result = {}
try:
if y_train is None:
estimator.fit(X_train, **fit_params)
else:
estimator.fit(X_train, y_train, **fit_params)
except Exception:
# Note fit time as time until error
fit_time = time.time() - start_time
score_time = 0.0
if error_score == "raise":
raise
elif isinstance(error_score, numbers.Number):
if isinstance(scorer, _MultimetricScorer):
test_scores = {name: error_score for name in scorer._scorers}
if return_train_score:
train_scores = test_scores.copy()
else:
test_scores = error_score
if return_train_score:
train_scores = error_score
result["fit_error"] = format_exc()
else:
result["fit_error"] = None
fit_time = time.time() - start_time
test_scores = _score(
estimator, X_test, y_test, scorer, score_params_test, error_score
)
score_time = time.time() - start_time - fit_time
if return_train_score:
train_scores = _score(
estimator, X_train, y_train, scorer, score_params_train, error_score
)
if verbose > 1:
total_time = score_time + fit_time
end_msg = f"[CV{progress_msg}] END "
result_msg = params_msg + (";" if params_msg else "")
if verbose > 2:
if isinstance(test_scores, dict):
for scorer_name in sorted(test_scores):
result_msg += f" {scorer_name}: ("
if return_train_score:
scorer_scores = train_scores[scorer_name]
result_msg += f"train={scorer_scores:.3f}, "
result_msg += f"test={test_scores[scorer_name]:.3f})"
else:
result_msg += ", score="
if return_train_score:
result_msg += f"(train={train_scores:.3f}, test={test_scores:.3f})"
else:
result_msg += f"{test_scores:.3f}"
result_msg += f" total time={logger.short_format_time(total_time)}"
# Right align the result_msg
end_msg += "." * (80 - len(end_msg) - len(result_msg))
end_msg += result_msg
print(end_msg)
result["test_scores"] = test_scores
if return_train_score:
result["train_scores"] = train_scores
if return_n_test_samples:
result["n_test_samples"] = _num_samples(X_test)
if return_times:
result["fit_time"] = fit_time
result["score_time"] = score_time
if return_parameters:
result["parameters"] = parameters
if return_estimator:
result["estimator"] = estimator
return result
def _score(estimator, X_test, y_test, scorer, score_params, error_score="raise"):
"""Compute 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.
"""
score_params = {} if score_params is None else score_params
try:
if y_test is None:
scores = scorer(estimator, X_test, **score_params)
else:
scores = scorer(estimator, X_test, y_test, **score_params)
except Exception:
if isinstance(scorer, _MultimetricScorer):
# If `_MultimetricScorer` raises exception, the `error_score`
# parameter is equal to "raise".
raise
else:
if error_score == "raise":
raise
else:
scores = error_score
warnings.warn(
(
"Scoring failed. The score on this train-test partition for "
f"these parameters will be set to {error_score}. Details: \n"
f"{format_exc()}"
),
UserWarning,
)
# Check non-raised error messages in `_MultimetricScorer`
if isinstance(scorer, _MultimetricScorer):
exception_messages = [
(name, str_e) for name, str_e in scores.items() if isinstance(str_e, str)
]
if exception_messages:
# error_score != "raise"
for name, str_e in exception_messages:
scores[name] = error_score
warnings.warn(
(
"Scoring failed. The score on this train-test partition for "
f"these parameters will be set to {error_score}. Details: \n"
f"{str_e}"
),
UserWarning,
)
error_msg = "scoring must return a number, got %s (%s) instead. (scorer=%s)"
if isinstance(scores, dict):
for name, score in scores.items():
if hasattr(score, "item"):
with suppress(ValueError):
# e.g. unwrap memmapped scalars
score = score.item()
if not isinstance(score, numbers.Number):
raise ValueError(error_msg % (score, type(score), name))
scores[name] = score
else: # scalar
if hasattr(scores, "item"):
with suppress(ValueError):
# e.g. unwrap memmapped scalars
scores = scores.item()
if not isinstance(scores, numbers.Number):
raise ValueError(error_msg % (scores, type(scores), scorer))
return scores
@validate_params(
{
"estimator": [HasMethods(["fit", "predict"])],
"X": ["array-like", "sparse matrix"],
"y": ["array-like", "sparse matrix", None],
"groups": ["array-like", None],
"cv": ["cv_object"],
"n_jobs": [Integral, None],
"verbose": ["verbose"],
"params": [dict, None],
"pre_dispatch": [Integral, str, None],
"method": [
StrOptions(
{
"predict",
"predict_proba",
"predict_log_proba",
"decision_function",
}
)
],
},
prefer_skip_nested_validation=False, # estimator is not validated yet
)
def cross_val_predict(
estimator,
X,