-
-
Notifications
You must be signed in to change notification settings - Fork 25.5k
/
Copy pathestimator_checks.py
5349 lines (4498 loc) · 188 KB
/
estimator_checks.py
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
"""Various utilities to check the compatibility of estimators with scikit-learn API."""
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import pickle
import re
import textwrap
import warnings
from contextlib import nullcontext
from copy import deepcopy
from functools import partial, wraps
from inspect import signature
from numbers import Integral, Real
from typing import Callable, Literal
import joblib
import numpy as np
from scipy import sparse
from scipy.stats import rankdata
from sklearn.base import (
BaseEstimator,
BiclusterMixin,
ClassifierMixin,
ClassNamePrefixFeaturesOutMixin,
DensityMixin,
MetaEstimatorMixin,
MultiOutputMixin,
OneToOneFeatureMixin,
OutlierMixin,
RegressorMixin,
TransformerMixin,
)
from .. import config_context
from ..base import (
ClusterMixin,
clone,
is_classifier,
is_outlier_detector,
is_regressor,
)
from ..datasets import (
load_iris,
make_blobs,
make_classification,
make_multilabel_classification,
make_regression,
)
from ..exceptions import (
DataConversionWarning,
EstimatorCheckFailedWarning,
NotFittedError,
SkipTestWarning,
)
from ..linear_model._base import LinearClassifierMixin
from ..metrics import accuracy_score, adjusted_rand_score, f1_score
from ..metrics.pairwise import linear_kernel, pairwise_distances, rbf_kernel
from ..model_selection import LeaveOneGroupOut, ShuffleSplit, train_test_split
from ..model_selection._validation import _safe_split
from ..pipeline import make_pipeline
from ..preprocessing import StandardScaler, scale
from ..utils import _safe_indexing
from ..utils._array_api import (
_atol_for_type,
_convert_to_numpy,
get_namespace,
yield_namespace_device_dtype_combinations,
)
from ..utils._array_api import device as array_device
from ..utils._param_validation import (
InvalidParameterError,
generate_invalid_param_val,
make_constraint,
)
from . import shuffle
from ._missing import is_scalar_nan
from ._param_validation import Interval, StrOptions, validate_params
from ._tags import (
ClassifierTags,
InputTags,
RegressorTags,
TargetTags,
TransformerTags,
get_tags,
)
from ._test_common.instance_generator import (
CROSS_DECOMPOSITION,
_get_check_estimator_ids,
_yield_instances_for_check,
)
from ._testing import (
SkipTest,
_array_api_for_tests,
_get_args,
assert_allclose,
assert_allclose_dense_sparse,
assert_array_almost_equal,
assert_array_equal,
assert_array_less,
create_memmap_backed_data,
ignore_warnings,
raises,
set_random_state,
)
from .fixes import SPARSE_ARRAY_PRESENT
from .validation import _num_samples, check_is_fitted, has_fit_parameter
REGRESSION_DATASET = None
def _raise_for_missing_tags(estimator, tag_name, Mixin):
tags = get_tags(estimator)
estimator_type = Mixin.__name__.replace("Mixin", "")
if getattr(tags, tag_name) is None:
raise RuntimeError(
f"Estimator {estimator.__class__.__name__} seems to be a {estimator_type},"
f" but the `{tag_name}` tag is not set. Either set the tag manually"
f" or inherit from the {Mixin.__name__}. Note that the order of inheritance"
f" matters, the {Mixin.__name__} should come before BaseEstimator."
)
def _yield_api_checks(estimator):
if not isinstance(estimator, BaseEstimator):
warnings.warn(
f"Estimator {estimator.__class__.__name__} does not inherit from"
" `sklearn.base.BaseEstimator`. This might lead to unexpected behavior, or"
" even errors when collecting tests.",
category=UserWarning,
)
tags = get_tags(estimator)
yield check_estimator_cloneable
yield check_estimator_tags_renamed
yield check_valid_tag_types
yield check_estimator_repr
yield check_no_attributes_set_in_init
yield check_fit_score_takes_y
yield check_estimators_overwrite_params
yield check_dont_overwrite_parameters
yield check_estimators_fit_returns_self
yield check_readonly_memmap_input
if tags.requires_fit:
yield check_estimators_unfitted
yield check_do_not_raise_errors_in_init_or_set_params
yield check_n_features_in_after_fitting
yield check_mixin_order
yield check_positive_only_tag_during_fit
def _yield_checks(estimator):
name = estimator.__class__.__name__
tags = get_tags(estimator)
yield check_estimators_dtypes
if has_fit_parameter(estimator, "sample_weight"):
yield check_sample_weights_pandas_series
yield check_sample_weights_not_an_array
yield check_sample_weights_list
if not tags.input_tags.pairwise:
# We skip pairwise because the data is not pairwise
yield check_sample_weights_shape
yield check_sample_weights_not_overwritten
yield check_sample_weight_equivalence_on_dense_data
if tags.input_tags.sparse:
yield check_sample_weight_equivalence_on_sparse_data
# Check that all estimator yield informative messages when
# trained on empty datasets
if not tags.no_validation:
yield check_complex_data
yield check_dtype_object
yield check_estimators_empty_data_messages
if name not in CROSS_DECOMPOSITION:
# cross-decomposition's "transform" returns X and Y
yield check_pipeline_consistency
if not tags.input_tags.allow_nan and not tags.no_validation:
# Test that all estimators check their input for NaN's and infs
yield check_estimators_nan_inf
if tags.input_tags.pairwise:
# Check that pairwise estimator throws error on non-square input
yield check_nonsquare_error
if hasattr(estimator, "sparsify"):
yield check_sparsify_coefficients
yield check_estimator_sparse_tag
yield check_estimator_sparse_array
yield check_estimator_sparse_matrix
# Test that estimators can be pickled, and once pickled
# give the same answer as before.
yield check_estimators_pickle
yield partial(check_estimators_pickle, readonly_memmap=True)
if tags.array_api_support:
for check in _yield_array_api_checks(estimator):
yield check
yield check_f_contiguous_array_estimator
def _yield_classifier_checks(classifier):
_raise_for_missing_tags(classifier, "classifier_tags", ClassifierMixin)
tags = get_tags(classifier)
# test classifiers can handle non-array data and pandas objects
yield check_classifier_data_not_an_array
# test classifiers trained on a single label always return this label
yield check_classifiers_one_label
yield check_classifiers_one_label_sample_weights
yield check_classifiers_classes
yield check_estimators_partial_fit_n_features
if tags.target_tags.multi_output:
yield check_classifier_multioutput
# basic consistency testing
yield check_classifiers_train
yield partial(check_classifiers_train, readonly_memmap=True)
yield partial(check_classifiers_train, readonly_memmap=True, X_dtype="float32")
yield check_classifiers_regression_target
if tags.classifier_tags.multi_label:
yield check_classifiers_multilabel_representation_invariance
yield check_classifiers_multilabel_output_format_predict
yield check_classifiers_multilabel_output_format_predict_proba
yield check_classifiers_multilabel_output_format_decision_function
if not tags.no_validation:
yield check_supervised_y_no_nan
if tags.target_tags.single_output:
yield check_supervised_y_2d
if "class_weight" in classifier.get_params().keys():
yield check_class_weight_classifiers
yield check_non_transformer_estimators_n_iter
# test if predict_proba is a monotonic transformation of decision_function
yield check_decision_proba_consistency
if isinstance(classifier, LinearClassifierMixin):
if "class_weight" in classifier.get_params().keys():
yield check_class_weight_balanced_linear_classifier
if (
isinstance(classifier, LinearClassifierMixin)
and "class_weight" in classifier.get_params().keys()
):
yield check_class_weight_balanced_linear_classifier
if not tags.classifier_tags.multi_class:
yield check_classifier_not_supporting_multiclass
def _yield_regressor_checks(regressor):
_raise_for_missing_tags(regressor, "regressor_tags", RegressorMixin)
tags = get_tags(regressor)
# TODO: test with intercept
# TODO: test with multiple responses
# basic testing
yield check_regressors_train
yield partial(check_regressors_train, readonly_memmap=True)
yield partial(check_regressors_train, readonly_memmap=True, X_dtype="float32")
yield check_regressor_data_not_an_array
yield check_estimators_partial_fit_n_features
if tags.target_tags.multi_output:
yield check_regressor_multioutput
yield check_regressors_no_decision_function
if not tags.no_validation and tags.target_tags.single_output:
yield check_supervised_y_2d
yield check_supervised_y_no_nan
name = regressor.__class__.__name__
if name != "CCA":
# check that the regressor handles int input
yield check_regressors_int
yield check_non_transformer_estimators_n_iter
def _yield_transformer_checks(transformer):
_raise_for_missing_tags(transformer, "transformer_tags", TransformerMixin)
tags = get_tags(transformer)
# All transformers should either deal with sparse data or raise an
# exception with type TypeError and an intelligible error message
if not tags.no_validation:
yield check_transformer_data_not_an_array
# these don't actually fit the data, so don't raise errors
yield check_transformer_general
if tags.transformer_tags.preserves_dtype:
yield check_transformer_preserve_dtypes
yield partial(check_transformer_general, readonly_memmap=True)
if get_tags(transformer).requires_fit:
yield check_transformers_unfitted
else:
yield check_transformers_unfitted_stateless
# Dependent on external solvers and hence accessing the iter
# param is non-trivial.
external_solver = [
"Isomap",
"KernelPCA",
"LocallyLinearEmbedding",
"LogisticRegressionCV",
"BisectingKMeans",
]
name = transformer.__class__.__name__
if name not in external_solver:
yield check_transformer_n_iter
def _yield_clustering_checks(clusterer):
yield check_clusterer_compute_labels_predict
name = clusterer.__class__.__name__
if name not in ("WardAgglomeration", "FeatureAgglomeration"):
# this is clustering on the features
# let's not test that here.
yield check_clustering
yield partial(check_clustering, readonly_memmap=True)
yield check_estimators_partial_fit_n_features
if not hasattr(clusterer, "transform"):
yield check_non_transformer_estimators_n_iter
def _yield_outliers_checks(estimator):
# checks for the contamination parameter
if hasattr(estimator, "contamination"):
yield check_outlier_contamination
# checks for outlier detectors that have a fit_predict method
if hasattr(estimator, "fit_predict"):
yield check_outliers_fit_predict
# checks for estimators that can be used on a test set
if hasattr(estimator, "predict"):
yield check_outliers_train
yield partial(check_outliers_train, readonly_memmap=True)
# test outlier detectors can handle non-array data
yield check_classifier_data_not_an_array
yield check_non_transformer_estimators_n_iter
def _yield_array_api_checks(estimator):
for (
array_namespace,
device,
dtype_name,
) in yield_namespace_device_dtype_combinations():
yield partial(
check_array_api_input,
array_namespace=array_namespace,
dtype_name=dtype_name,
device=device,
)
def _yield_all_checks(estimator, legacy: bool):
name = estimator.__class__.__name__
tags = get_tags(estimator)
if not tags.input_tags.two_d_array:
warnings.warn(
"Can't test estimator {} which requires input of type {}".format(
name, tags.input_tags
),
SkipTestWarning,
)
return
if tags._skip_test:
warnings.warn(
"Explicit SKIP via _skip_test tag for estimator {}.".format(name),
SkipTestWarning,
)
return
for check in _yield_api_checks(estimator):
yield check
if not legacy:
return # pragma: no cover
for check in _yield_checks(estimator):
yield check
if is_classifier(estimator):
for check in _yield_classifier_checks(estimator):
yield check
if is_regressor(estimator):
for check in _yield_regressor_checks(estimator):
yield check
if hasattr(estimator, "transform"):
for check in _yield_transformer_checks(estimator):
yield check
if isinstance(estimator, ClusterMixin):
for check in _yield_clustering_checks(estimator):
yield check
if is_outlier_detector(estimator):
for check in _yield_outliers_checks(estimator):
yield check
yield check_parameters_default_constructible
if not tags.non_deterministic:
yield check_methods_sample_order_invariance
yield check_methods_subset_invariance
yield check_fit2d_1sample
yield check_fit2d_1feature
yield check_get_params_invariance
yield check_set_params
yield check_dict_unchanged
yield check_fit_idempotent
yield check_fit_check_is_fitted
if not tags.no_validation:
yield check_n_features_in
yield check_fit1d
yield check_fit2d_predict1d
if tags.target_tags.required:
yield check_requires_y_none
if tags.input_tags.positive_only:
yield check_fit_non_negative
def _check_name(check):
if hasattr(check, "__wrapped__"):
return _check_name(check.__wrapped__)
return check.func.__name__ if isinstance(check, partial) else check.__name__
def _maybe_mark(
estimator,
check,
expected_failed_checks: dict[str, str] | None = None,
mark: Literal["xfail", "skip", None] = None,
pytest=None,
):
"""Mark the test as xfail or skip if needed.
Parameters
----------
estimator : estimator object
Estimator instance for which to generate checks.
check : partial or callable
Check to be marked.
expected_failed_checks : dict[str, str], default=None
Dictionary of the form {check_name: reason} for checks that are expected to
fail.
mark : "xfail" or "skip" or None
Whether to mark the check as xfail or skip.
pytest : pytest module, default=None
Pytest module to use to mark the check. This is only needed if ``mark`` is
`"xfail"`. Note that one can run `check_estimator` without having `pytest`
installed. This is used in combination with `parametrize_with_checks` only.
"""
should_be_marked, reason = _should_be_skipped_or_marked(
estimator, check, expected_failed_checks
)
if not should_be_marked or mark is None:
return estimator, check
estimator_name = estimator.__class__.__name__
if mark == "xfail":
return pytest.param(estimator, check, marks=pytest.mark.xfail(reason=reason))
else:
@wraps(check)
def wrapped(*args, **kwargs):
raise SkipTest(
f"Skipping {_check_name(check)} for {estimator_name}: {reason}"
)
return estimator, wrapped
def _should_be_skipped_or_marked(
estimator, check, expected_failed_checks: dict[str, str] | None = None
) -> tuple[bool, str]:
"""Check whether a check should be skipped or marked as xfail.
Parameters
----------
estimator : estimator object
Estimator instance for which to generate checks.
check : partial or callable
Check to be marked.
expected_failed_checks : dict[str, str], default=None
Dictionary of the form {check_name: reason} for checks that are expected to
fail.
Returns
-------
should_be_marked : bool
Whether the check should be marked as xfail or skipped.
reason : str
Reason for skipping the check.
"""
expected_failed_checks = expected_failed_checks or {}
check_name = _check_name(check)
if check_name in expected_failed_checks:
return True, expected_failed_checks[check_name]
return False, "Check is not expected to fail"
def estimator_checks_generator(
estimator,
*,
legacy: bool = True,
expected_failed_checks: dict[str, str] | None = None,
mark: Literal["xfail", "skip", None] = None,
):
"""Iteratively yield all check callables for an estimator.
.. versionadded:: 1.6
Parameters
----------
estimator : estimator object
Estimator instance for which to generate checks.
legacy : bool, default=True
Whether to include legacy checks. Over time we remove checks from this category
and move them into their specific category.
expected_failed_checks : dict[str, str], default=None
Dictionary of the form {check_name: reason} for checks that are expected to
fail.
mark : {"xfail", "skip"} or None, default=None
Whether to mark the checks that are expected to fail as
xfail(`pytest.mark.xfail`) or skip. Marking a test as "skip" is done via
wrapping the check in a function that raises a
:class:`~sklearn.exceptions.SkipTest` exception.
Returns
-------
estimator_checks_generator : generator
Generator that yields (estimator, check) tuples.
"""
if mark == "xfail":
import pytest
else:
pytest = None # type: ignore
name = type(estimator).__name__
# First check that the estimator is cloneable which is needed for the rest
# of the checks to run
yield estimator, partial(check_estimator_cloneable, name)
for check in _yield_all_checks(estimator, legacy=legacy):
check_with_name = partial(check, name)
for check_instance in _yield_instances_for_check(check, estimator):
yield _maybe_mark(
check_instance,
check_with_name,
expected_failed_checks=expected_failed_checks,
mark=mark,
pytest=pytest,
)
def parametrize_with_checks(
estimators,
*,
legacy: bool = True,
expected_failed_checks: Callable | None = None,
):
"""Pytest specific decorator for parametrizing estimator checks.
Checks are categorised into the following groups:
- API checks: a set of checks to ensure API compatibility with scikit-learn.
Refer to https://scikit-learn.org/dev/developers/develop.html a requirement of
scikit-learn estimators.
- legacy: a set of checks which gradually will be grouped into other categories.
The `id` of each check is set to be a pprint version of the estimator
and the name of the check with its keyword arguments.
This allows to use `pytest -k` to specify which tests to run::
pytest test_check_estimators.py -k check_estimators_fit_returns_self
Parameters
----------
estimators : list of estimators instances
Estimators to generated checks for.
.. versionchanged:: 0.24
Passing a class was deprecated in version 0.23, and support for
classes was removed in 0.24. Pass an instance instead.
.. versionadded:: 0.24
legacy : bool, default=True
Whether to include legacy checks. Over time we remove checks from this category
and move them into their specific category.
.. versionadded:: 1.6
expected_failed_checks : callable, default=None
A callable that takes an estimator as input and returns a dictionary of the
form::
{
"check_name": "my reason",
}
Where `"check_name"` is the name of the check, and `"my reason"` is why
the check fails. These tests will be marked as xfail if the check fails.
.. versionadded:: 1.6
Returns
-------
decorator : `pytest.mark.parametrize`
See Also
--------
check_estimator : Check if estimator adheres to scikit-learn conventions.
Examples
--------
>>> from sklearn.utils.estimator_checks import parametrize_with_checks
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.tree import DecisionTreeRegressor
>>> @parametrize_with_checks([LogisticRegression(),
... DecisionTreeRegressor()])
... def test_sklearn_compatible_estimator(estimator, check):
... check(estimator)
"""
import pytest
if any(isinstance(est, type) for est in estimators):
msg = (
"Passing a class was deprecated in version 0.23 "
"and isn't supported anymore from 0.24."
"Please pass an instance instead."
)
raise TypeError(msg)
def _checks_generator(estimators, legacy, expected_failed_checks):
for estimator in estimators:
args = {"estimator": estimator, "legacy": legacy, "mark": "xfail"}
if callable(expected_failed_checks):
args["expected_failed_checks"] = expected_failed_checks(estimator)
yield from estimator_checks_generator(**args)
return pytest.mark.parametrize(
"estimator, check",
_checks_generator(estimators, legacy, expected_failed_checks),
ids=_get_check_estimator_ids,
)
@validate_params(
{
"generate_only": ["boolean"],
"legacy": ["boolean"],
"expected_failed_checks": [dict, None],
"on_skip": [StrOptions({"warn"}), None],
"on_fail": [StrOptions({"raise", "warn"}), None],
"callback": [callable, None],
},
prefer_skip_nested_validation=False,
)
def check_estimator(
estimator=None,
generate_only=False,
*,
legacy: bool = True,
expected_failed_checks: dict[str, str] | None = None,
on_skip: Literal["warn"] | None = "warn",
on_fail: Literal["raise", "warn"] | None = "raise",
callback: Callable | None = None,
):
"""Check if estimator adheres to scikit-learn conventions.
This function will run an extensive test-suite for input validation,
shapes, etc, making sure that the estimator complies with `scikit-learn`
conventions as detailed in :ref:`rolling_your_own_estimator`.
Additional tests for classifiers, regressors, clustering or transformers
will be run if the Estimator class inherits from the corresponding mixin
from sklearn.base.
scikit-learn also provides a pytest specific decorator,
:func:`~sklearn.utils.estimator_checks.parametrize_with_checks`, making it
easier to test multiple estimators.
Checks are categorised into the following groups:
- API checks: a set of checks to ensure API compatibility with scikit-learn.
Refer to https://scikit-learn.org/dev/developers/develop.html a requirement of
scikit-learn estimators.
- legacy: a set of checks which gradually will be grouped into other categories.
Parameters
----------
estimator : estimator object
Estimator instance to check.
generate_only : bool, default=False
When `False`, checks are evaluated when `check_estimator` is called.
When `True`, `check_estimator` returns a generator that yields
(estimator, check) tuples. The check is run by calling
`check(estimator)`.
.. versionadded:: 0.22
.. deprecated:: 1.6
`generate_only` will be removed in 1.8. Use
:func:`~sklearn.utils.estimator_checks.estimator_checks_generator` instead.
legacy : bool, default=True
Whether to include legacy checks. Over time we remove checks from this category
and move them into their specific category.
.. versionadded:: 1.6
expected_failed_checks : dict, default=None
A dictionary of the form::
{
"check_name": "this check is expected to fail because ...",
}
Where `"check_name"` is the name of the check, and `"my reason"` is why
the check fails.
.. versionadded:: 1.6
on_skip : "warn", None, default="warn"
This parameter controls what happens when a check is skipped.
- "warn": A :class:`~sklearn.exceptions.SkipTestWarning` is logged
and running tests continue.
- None: No warning is logged and running tests continue.
.. versionadded:: 1.6
on_fail : {"raise", "warn"}, None, default="raise"
This parameter controls what happens when a check fails.
- "raise": The exception raised by the first failing check is raised and
running tests are aborted. This does not included tests that are expected
to fail.
- "warn": A :class:`~sklearn.exceptions.EstimatorCheckFailedWarning` is logged
and running tests continue.
- None: No exception is raised and no warning is logged.
Note that if ``on_fail != "raise"``, no exception is raised, even if the checks
fail. You'd need to inspect the return result of ``check_estimator`` to check
if any checks failed.
.. versionadded:: 1.6
callback : callable, or None, default=None
This callback will be called with the estimator and the check name,
the exception (if any), the status of the check (xfail, failed, skipped,
passed), and the reason for the expected failure if the check is
expected to fail. The callable's signature needs to be::
def callback(
estimator,
check_name: str,
exception: Exception,
status: Literal["xfail", "failed", "skipped", "passed"],
expected_to_fail: bool,
expected_to_fail_reason: str,
)
``callback`` cannot be provided together with ``on_fail="raise"``.
.. versionadded:: 1.6
Returns
-------
test_results : list
List of dictionaries with the results of the failing tests, of the form::
{
"estimator": estimator,
"check_name": check_name,
"exception": exception,
"status": status (one of "xfail", "failed", "skipped", "passed"),
"expected_to_fail": expected_to_fail,
"expected_to_fail_reason": expected_to_fail_reason,
}
estimator_checks_generator : generator
Generator that yields (estimator, check) tuples. Returned when
`generate_only=True`.
..
TODO(1.8): remove return value
.. deprecated:: 1.6
``generate_only`` will be removed in 1.8. Use
:func:`~sklearn.utils.estimator_checks.estimator_checks_generator` instead.
Raises
------
Exception
If ``on_fail="raise"``, the exception raised by the first failing check is
raised and running tests are aborted.
Note that if ``on_fail != "raise"``, no exception is raised, even if the checks
fail. You'd need to inspect the return result of ``check_estimator`` to check
if any checks failed.
See Also
--------
parametrize_with_checks : Pytest specific decorator for parametrizing estimator
checks.
estimator_checks_generator : Generator that yields (estimator, check) tuples.
Examples
--------
>>> from sklearn.utils.estimator_checks import check_estimator
>>> from sklearn.linear_model import LogisticRegression
>>> check_estimator(LogisticRegression())
[...]
"""
if isinstance(estimator, type):
msg = (
"Passing a class was deprecated in version 0.23 "
"and isn't supported anymore from 0.24."
"Please pass an instance instead."
)
raise TypeError(msg)
if on_fail == "raise" and callback is not None:
raise ValueError("callback cannot be provided together with on_fail='raise'")
name = type(estimator).__name__
# TODO(1.8): remove generate_only
if generate_only:
warnings.warn(
"`generate_only` is deprecated in 1.6 and will be removed in 1.8. "
"Use :func:`~sklearn.utils.estimator_checks.estimator_checks` instead.",
FutureWarning,
)
return estimator_checks_generator(
estimator, legacy=legacy, expected_failed_checks=None, mark="skip"
)
test_results = []
for estimator, check in estimator_checks_generator(
estimator,
legacy=legacy,
expected_failed_checks=expected_failed_checks,
# Not marking tests to be skipped here, we run and simulate an xfail behavior
mark=None,
):
test_can_fail, reason = _should_be_skipped_or_marked(
estimator, check, expected_failed_checks
)
try:
check(estimator)
except SkipTest as e:
# We get here if the test raises SkipTest, which is expected in cases where
# the check cannot run for instance if a required dependency is not
# installed.
check_result = {
"estimator": estimator,
"check_name": _check_name(check),
"exception": e,
"status": "skipped",
"expected_to_fail": test_can_fail,
"expected_to_fail_reason": reason,
}
if on_skip == "warn":
warnings.warn(
f"Skipping check {_check_name(check)} for {name} because it raised "
f"{type(e).__name__}: {e}",
SkipTestWarning,
)
except Exception as e:
if on_fail == "raise" and not test_can_fail:
raise
check_result = {
"estimator": estimator,
"check_name": _check_name(check),
"exception": e,
"expected_to_fail": test_can_fail,
"expected_to_fail_reason": reason,
}
if test_can_fail:
# This check failed, but could be expected to fail, therefore we mark it
# as xfail.
check_result["status"] = "xfail"
else:
failed = True
check_result["status"] = "failed"
if on_fail == "warn":
warning = EstimatorCheckFailedWarning(**check_result)
warnings.warn(warning)
else:
check_result = {
"estimator": estimator,
"check_name": _check_name(check),
"exception": None,
"status": "passed",
"expected_to_fail": test_can_fail,
"expected_to_fail_reason": reason,
}
test_results.append(check_result)
if callback:
callback(**check_result)
return test_results
def _regression_dataset():
global REGRESSION_DATASET
if REGRESSION_DATASET is None:
X, y = make_regression(
n_samples=200,
n_features=10,
n_informative=1,
bias=5.0,
noise=20,
random_state=42,
)
X = StandardScaler().fit_transform(X)
REGRESSION_DATASET = X, y
return REGRESSION_DATASET
class _NotAnArray:
"""An object that is convertible to an array.
Parameters
----------
data : array-like
The data.
"""
def __init__(self, data):
self.data = np.asarray(data)
def __array__(self, dtype=None, copy=None):
return self.data
def __array_function__(self, func, types, args, kwargs):
if func.__name__ == "may_share_memory":
return True
raise TypeError("Don't want to call array_function {}!".format(func.__name__))
def _is_pairwise_metric(estimator):
"""Returns True if estimator accepts pairwise metric.
Parameters
----------
estimator : object
Estimator object to test.
Returns
-------
out : bool
True if _pairwise is set to True and False otherwise.
"""
metric = getattr(estimator, "metric", None)
return bool(metric == "precomputed")
def _generate_sparse_data(X_csr):
"""Generate sparse matrices or arrays with {32,64}bit indices of diverse format.
Parameters
----------
X_csr: scipy.sparse.csr_matrix or scipy.sparse.csr_array
Input in CSR format.
Returns
-------
out: iter(Matrices) or iter(Arrays)
In format['dok', 'lil', 'dia', 'bsr', 'csr', 'csc', 'coo',
'coo_64', 'csc_64', 'csr_64']
"""
assert X_csr.format == "csr"
yield "csr", X_csr.copy()
for sparse_format in ["dok", "lil", "dia", "bsr", "csc", "coo"]:
yield sparse_format, X_csr.asformat(sparse_format)
# Generate large indices matrix only if its supported by scipy
X_coo = X_csr.asformat("coo")
X_coo.row = X_coo.row.astype("int64")
X_coo.col = X_coo.col.astype("int64")
yield "coo_64", X_coo
for sparse_format in ["csc", "csr"]:
X = X_csr.asformat(sparse_format)
X.indices = X.indices.astype("int64")
X.indptr = X.indptr.astype("int64")