test_common.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. """
  2. General tests for all estimators in sklearn.
  3. """
  4. # Authors: Andreas Mueller <amueller@ais.uni-bonn.de>
  5. # Gael Varoquaux gael.varoquaux@normalesup.org
  6. # License: BSD 3 clause
  7. import os
  8. import pkgutil
  9. import re
  10. import sys
  11. import warnings
  12. from functools import partial
  13. from inspect import isgenerator, signature
  14. from itertools import chain, product
  15. import numpy as np
  16. import pytest
  17. import sklearn
  18. from sklearn.cluster import (
  19. OPTICS,
  20. AffinityPropagation,
  21. Birch,
  22. MeanShift,
  23. SpectralClustering,
  24. )
  25. from sklearn.compose import ColumnTransformer
  26. from sklearn.datasets import make_blobs
  27. from sklearn.decomposition import PCA
  28. from sklearn.exceptions import ConvergenceWarning, FitFailedWarning
  29. # make it possible to discover experimental estimators when calling `all_estimators`
  30. from sklearn.experimental import (
  31. enable_halving_search_cv, # noqa
  32. enable_iterative_imputer, # noqa
  33. )
  34. from sklearn.linear_model import LogisticRegression, Ridge
  35. from sklearn.linear_model._base import LinearClassifierMixin
  36. from sklearn.manifold import TSNE, Isomap, LocallyLinearEmbedding
  37. from sklearn.model_selection import (
  38. GridSearchCV,
  39. HalvingGridSearchCV,
  40. HalvingRandomSearchCV,
  41. RandomizedSearchCV,
  42. )
  43. from sklearn.neighbors import (
  44. KNeighborsClassifier,
  45. KNeighborsRegressor,
  46. LocalOutlierFactor,
  47. RadiusNeighborsClassifier,
  48. RadiusNeighborsRegressor,
  49. )
  50. from sklearn.pipeline import Pipeline, make_pipeline
  51. from sklearn.preprocessing import (
  52. FunctionTransformer,
  53. MinMaxScaler,
  54. OneHotEncoder,
  55. StandardScaler,
  56. )
  57. from sklearn.semi_supervised import LabelPropagation, LabelSpreading
  58. from sklearn.utils import IS_PYPY, all_estimators
  59. from sklearn.utils._tags import _DEFAULT_TAGS, _safe_tags
  60. from sklearn.utils._testing import (
  61. SkipTest,
  62. ignore_warnings,
  63. set_random_state,
  64. )
  65. from sklearn.utils.estimator_checks import (
  66. _construct_instance,
  67. _get_check_estimator_ids,
  68. _set_checking_parameters,
  69. check_class_weight_balanced_linear_classifier,
  70. check_dataframe_column_names_consistency,
  71. check_estimator,
  72. check_get_feature_names_out_error,
  73. check_global_output_transform_pandas,
  74. check_n_features_in_after_fitting,
  75. check_param_validation,
  76. check_set_output_transform,
  77. check_set_output_transform_pandas,
  78. check_transformer_get_feature_names_out,
  79. check_transformer_get_feature_names_out_pandas,
  80. parametrize_with_checks,
  81. )
  82. def test_all_estimator_no_base_class():
  83. # test that all_estimators doesn't find abstract classes.
  84. for name, Estimator in all_estimators():
  85. msg = (
  86. "Base estimators such as {0} should not be included in all_estimators"
  87. ).format(name)
  88. assert not name.lower().startswith("base"), msg
  89. def _sample_func(x, y=1):
  90. pass
  91. @pytest.mark.parametrize(
  92. "val, expected",
  93. [
  94. (partial(_sample_func, y=1), "_sample_func(y=1)"),
  95. (_sample_func, "_sample_func"),
  96. (partial(_sample_func, "world"), "_sample_func"),
  97. (LogisticRegression(C=2.0), "LogisticRegression(C=2.0)"),
  98. (
  99. LogisticRegression(
  100. random_state=1,
  101. solver="newton-cg",
  102. class_weight="balanced",
  103. warm_start=True,
  104. ),
  105. (
  106. "LogisticRegression(class_weight='balanced',random_state=1,"
  107. "solver='newton-cg',warm_start=True)"
  108. ),
  109. ),
  110. ],
  111. )
  112. def test_get_check_estimator_ids(val, expected):
  113. assert _get_check_estimator_ids(val) == expected
  114. def _tested_estimators(type_filter=None):
  115. for name, Estimator in all_estimators(type_filter=type_filter):
  116. try:
  117. estimator = _construct_instance(Estimator)
  118. except SkipTest:
  119. continue
  120. yield estimator
  121. def _generate_pipeline():
  122. for final_estimator in [Ridge(), LogisticRegression()]:
  123. yield Pipeline(
  124. steps=[
  125. ("scaler", StandardScaler()),
  126. ("final_estimator", final_estimator),
  127. ]
  128. )
  129. @parametrize_with_checks(list(chain(_tested_estimators(), _generate_pipeline())))
  130. def test_estimators(estimator, check, request):
  131. # Common tests for estimator instances
  132. with ignore_warnings(category=(FutureWarning, ConvergenceWarning, UserWarning)):
  133. _set_checking_parameters(estimator)
  134. check(estimator)
  135. def test_check_estimator_generate_only():
  136. all_instance_gen_checks = check_estimator(LogisticRegression(), generate_only=True)
  137. assert isgenerator(all_instance_gen_checks)
  138. def test_configure():
  139. # Smoke test `python setup.py config` command run at the root of the
  140. # scikit-learn source tree.
  141. # This test requires Cython which is not necessarily there when running
  142. # the tests of an installed version of scikit-learn or when scikit-learn
  143. # is installed in editable mode by pip build isolation enabled.
  144. pytest.importorskip("Cython")
  145. cwd = os.getcwd()
  146. setup_path = os.path.abspath(os.path.join(sklearn.__path__[0], ".."))
  147. setup_filename = os.path.join(setup_path, "setup.py")
  148. if not os.path.exists(setup_filename):
  149. pytest.skip("setup.py not available")
  150. try:
  151. os.chdir(setup_path)
  152. old_argv = sys.argv
  153. sys.argv = ["setup.py", "config"]
  154. with warnings.catch_warnings():
  155. # The configuration spits out warnings when not finding
  156. # Blas/Atlas development headers
  157. warnings.simplefilter("ignore", UserWarning)
  158. with open("setup.py") as f:
  159. exec(f.read(), dict(__name__="__main__"))
  160. finally:
  161. sys.argv = old_argv
  162. os.chdir(cwd)
  163. def _tested_linear_classifiers():
  164. classifiers = all_estimators(type_filter="classifier")
  165. with warnings.catch_warnings(record=True):
  166. for name, clazz in classifiers:
  167. required_parameters = getattr(clazz, "_required_parameters", [])
  168. if len(required_parameters):
  169. # FIXME
  170. continue
  171. if "class_weight" in clazz().get_params().keys() and issubclass(
  172. clazz, LinearClassifierMixin
  173. ):
  174. yield name, clazz
  175. @pytest.mark.parametrize("name, Classifier", _tested_linear_classifiers())
  176. def test_class_weight_balanced_linear_classifiers(name, Classifier):
  177. check_class_weight_balanced_linear_classifier(name, Classifier)
  178. @ignore_warnings
  179. def test_import_all_consistency():
  180. # Smoke test to check that any name in a __all__ list is actually defined
  181. # in the namespace of the module or package.
  182. pkgs = pkgutil.walk_packages(
  183. path=sklearn.__path__, prefix="sklearn.", onerror=lambda _: None
  184. )
  185. submods = [modname for _, modname, _ in pkgs]
  186. for modname in submods + ["sklearn"]:
  187. if ".tests." in modname:
  188. continue
  189. # Avoid test suite depending on setuptools
  190. if "sklearn._build_utils" in modname:
  191. continue
  192. if IS_PYPY and (
  193. "_svmlight_format_io" in modname
  194. or "feature_extraction._hashing_fast" in modname
  195. ):
  196. continue
  197. package = __import__(modname, fromlist="dummy")
  198. for name in getattr(package, "__all__", ()):
  199. assert hasattr(package, name), "Module '{0}' has no attribute '{1}'".format(
  200. modname, name
  201. )
  202. def test_root_import_all_completeness():
  203. EXCEPTIONS = ("utils", "tests", "base", "setup", "conftest")
  204. for _, modname, _ in pkgutil.walk_packages(
  205. path=sklearn.__path__, onerror=lambda _: None
  206. ):
  207. if "." in modname or modname.startswith("_") or modname in EXCEPTIONS:
  208. continue
  209. assert modname in sklearn.__all__
  210. def test_all_tests_are_importable():
  211. # Ensure that for each contentful subpackage, there is a test directory
  212. # within it that is also a subpackage (i.e. a directory with __init__.py)
  213. HAS_TESTS_EXCEPTIONS = re.compile(r"""(?x)
  214. \.externals(\.|$)|
  215. \.tests(\.|$)|
  216. \._
  217. """)
  218. resource_modules = {
  219. "sklearn.datasets.data",
  220. "sklearn.datasets.descr",
  221. "sklearn.datasets.images",
  222. }
  223. lookup = {
  224. name: ispkg
  225. for _, name, ispkg in pkgutil.walk_packages(sklearn.__path__, prefix="sklearn.")
  226. }
  227. missing_tests = [
  228. name
  229. for name, ispkg in lookup.items()
  230. if ispkg
  231. and name not in resource_modules
  232. and not HAS_TESTS_EXCEPTIONS.search(name)
  233. and name + ".tests" not in lookup
  234. ]
  235. assert missing_tests == [], (
  236. "{0} do not have `tests` subpackages. "
  237. "Perhaps they require "
  238. "__init__.py or an add_subpackage directive "
  239. "in the parent "
  240. "setup.py".format(missing_tests)
  241. )
  242. def test_class_support_removed():
  243. # Make sure passing classes to check_estimator or parametrize_with_checks
  244. # raises an error
  245. msg = "Passing a class was deprecated.* isn't supported anymore"
  246. with pytest.raises(TypeError, match=msg):
  247. check_estimator(LogisticRegression)
  248. with pytest.raises(TypeError, match=msg):
  249. parametrize_with_checks([LogisticRegression])
  250. def _generate_column_transformer_instances():
  251. yield ColumnTransformer(
  252. transformers=[
  253. ("trans1", StandardScaler(), [0, 1]),
  254. ]
  255. )
  256. def _generate_search_cv_instances():
  257. for SearchCV, (Estimator, param_grid) in product(
  258. [
  259. GridSearchCV,
  260. HalvingGridSearchCV,
  261. RandomizedSearchCV,
  262. HalvingGridSearchCV,
  263. ],
  264. [
  265. (Ridge, {"alpha": [0.1, 1.0]}),
  266. (LogisticRegression, {"C": [0.1, 1.0]}),
  267. ],
  268. ):
  269. init_params = signature(SearchCV).parameters
  270. extra_params = (
  271. {"min_resources": "smallest"} if "min_resources" in init_params else {}
  272. )
  273. search_cv = SearchCV(Estimator(), param_grid, cv=2, **extra_params)
  274. set_random_state(search_cv)
  275. yield search_cv
  276. for SearchCV, (Estimator, param_grid) in product(
  277. [
  278. GridSearchCV,
  279. HalvingGridSearchCV,
  280. RandomizedSearchCV,
  281. HalvingRandomSearchCV,
  282. ],
  283. [
  284. (Ridge, {"ridge__alpha": [0.1, 1.0]}),
  285. (LogisticRegression, {"logisticregression__C": [0.1, 1.0]}),
  286. ],
  287. ):
  288. init_params = signature(SearchCV).parameters
  289. extra_params = (
  290. {"min_resources": "smallest"} if "min_resources" in init_params else {}
  291. )
  292. search_cv = SearchCV(
  293. make_pipeline(PCA(), Estimator()), param_grid, cv=2, **extra_params
  294. ).set_params(error_score="raise")
  295. set_random_state(search_cv)
  296. yield search_cv
  297. @parametrize_with_checks(list(_generate_search_cv_instances()))
  298. def test_search_cv(estimator, check, request):
  299. # Common tests for SearchCV instances
  300. # We have a separate test because those meta-estimators can accept a
  301. # wide range of base estimators (classifiers, regressors, pipelines)
  302. with ignore_warnings(
  303. category=(
  304. FutureWarning,
  305. ConvergenceWarning,
  306. UserWarning,
  307. FitFailedWarning,
  308. )
  309. ):
  310. check(estimator)
  311. @pytest.mark.parametrize(
  312. "estimator", _tested_estimators(), ids=_get_check_estimator_ids
  313. )
  314. def test_valid_tag_types(estimator):
  315. """Check that estimator tags are valid."""
  316. tags = _safe_tags(estimator)
  317. for name, tag in tags.items():
  318. correct_tags = type(_DEFAULT_TAGS[name])
  319. if name == "_xfail_checks":
  320. # _xfail_checks can be a dictionary
  321. correct_tags = (correct_tags, dict)
  322. assert isinstance(tag, correct_tags)
  323. @pytest.mark.parametrize(
  324. "estimator", _tested_estimators(), ids=_get_check_estimator_ids
  325. )
  326. def test_check_n_features_in_after_fitting(estimator):
  327. _set_checking_parameters(estimator)
  328. check_n_features_in_after_fitting(estimator.__class__.__name__, estimator)
  329. def _estimators_that_predict_in_fit():
  330. for estimator in _tested_estimators():
  331. est_params = set(estimator.get_params())
  332. if "oob_score" in est_params:
  333. yield estimator.set_params(oob_score=True, bootstrap=True)
  334. elif "early_stopping" in est_params:
  335. est = estimator.set_params(early_stopping=True, n_iter_no_change=1)
  336. if est.__class__.__name__ in {"MLPClassifier", "MLPRegressor"}:
  337. # TODO: FIX MLP to not check validation set during MLP
  338. yield pytest.param(
  339. est, marks=pytest.mark.xfail(msg="MLP still validates in fit")
  340. )
  341. else:
  342. yield est
  343. elif "n_iter_no_change" in est_params:
  344. yield estimator.set_params(n_iter_no_change=1)
  345. # NOTE: When running `check_dataframe_column_names_consistency` on a meta-estimator that
  346. # delegates validation to a base estimator, the check is testing that the base estimator
  347. # is checking for column name consistency.
  348. column_name_estimators = list(
  349. chain(
  350. _tested_estimators(),
  351. [make_pipeline(LogisticRegression(C=1))],
  352. list(_generate_search_cv_instances()),
  353. _estimators_that_predict_in_fit(),
  354. )
  355. )
  356. @pytest.mark.parametrize(
  357. "estimator", column_name_estimators, ids=_get_check_estimator_ids
  358. )
  359. def test_pandas_column_name_consistency(estimator):
  360. _set_checking_parameters(estimator)
  361. with ignore_warnings(category=(FutureWarning)):
  362. with warnings.catch_warnings(record=True) as record:
  363. check_dataframe_column_names_consistency(
  364. estimator.__class__.__name__, estimator
  365. )
  366. for warning in record:
  367. assert "was fitted without feature names" not in str(warning.message)
  368. # TODO: As more modules support get_feature_names_out they should be removed
  369. # from this list to be tested
  370. GET_FEATURES_OUT_MODULES_TO_IGNORE = [
  371. "ensemble",
  372. "kernel_approximation",
  373. ]
  374. def _include_in_get_feature_names_out_check(transformer):
  375. if hasattr(transformer, "get_feature_names_out"):
  376. return True
  377. module = transformer.__module__.split(".")[1]
  378. return module not in GET_FEATURES_OUT_MODULES_TO_IGNORE
  379. GET_FEATURES_OUT_ESTIMATORS = [
  380. est
  381. for est in _tested_estimators("transformer")
  382. if _include_in_get_feature_names_out_check(est)
  383. ]
  384. @pytest.mark.parametrize(
  385. "transformer", GET_FEATURES_OUT_ESTIMATORS, ids=_get_check_estimator_ids
  386. )
  387. def test_transformers_get_feature_names_out(transformer):
  388. _set_checking_parameters(transformer)
  389. with ignore_warnings(category=(FutureWarning)):
  390. check_transformer_get_feature_names_out(
  391. transformer.__class__.__name__, transformer
  392. )
  393. check_transformer_get_feature_names_out_pandas(
  394. transformer.__class__.__name__, transformer
  395. )
  396. ESTIMATORS_WITH_GET_FEATURE_NAMES_OUT = [
  397. est for est in _tested_estimators() if hasattr(est, "get_feature_names_out")
  398. ]
  399. @pytest.mark.parametrize(
  400. "estimator", ESTIMATORS_WITH_GET_FEATURE_NAMES_OUT, ids=_get_check_estimator_ids
  401. )
  402. def test_estimators_get_feature_names_out_error(estimator):
  403. estimator_name = estimator.__class__.__name__
  404. _set_checking_parameters(estimator)
  405. check_get_feature_names_out_error(estimator_name, estimator)
  406. @pytest.mark.parametrize(
  407. "Estimator",
  408. [est for name, est in all_estimators()],
  409. )
  410. def test_estimators_do_not_raise_errors_in_init_or_set_params(Estimator):
  411. """Check that init or set_param does not raise errors."""
  412. params = signature(Estimator).parameters
  413. smoke_test_values = [-1, 3.0, "helloworld", np.array([1.0, 4.0]), [1], {}, []]
  414. for value in smoke_test_values:
  415. new_params = {key: value for key in params}
  416. # Does not raise
  417. est = Estimator(**new_params)
  418. # Also do does not raise
  419. est.set_params(**new_params)
  420. @pytest.mark.parametrize(
  421. "estimator",
  422. chain(
  423. _tested_estimators(),
  424. _generate_pipeline(),
  425. _generate_column_transformer_instances(),
  426. _generate_search_cv_instances(),
  427. ),
  428. ids=_get_check_estimator_ids,
  429. )
  430. def test_check_param_validation(estimator):
  431. name = estimator.__class__.__name__
  432. _set_checking_parameters(estimator)
  433. check_param_validation(name, estimator)
  434. @pytest.mark.parametrize(
  435. "Estimator",
  436. [
  437. AffinityPropagation,
  438. Birch,
  439. MeanShift,
  440. KNeighborsClassifier,
  441. KNeighborsRegressor,
  442. RadiusNeighborsClassifier,
  443. RadiusNeighborsRegressor,
  444. LabelPropagation,
  445. LabelSpreading,
  446. OPTICS,
  447. SpectralClustering,
  448. LocalOutlierFactor,
  449. LocallyLinearEmbedding,
  450. Isomap,
  451. TSNE,
  452. ],
  453. )
  454. def test_f_contiguous_array_estimator(Estimator):
  455. # Non-regression test for:
  456. # https://github.com/scikit-learn/scikit-learn/issues/23988
  457. # https://github.com/scikit-learn/scikit-learn/issues/24013
  458. X, _ = make_blobs(n_samples=80, n_features=4, random_state=0)
  459. X = np.asfortranarray(X)
  460. y = np.round(X[:, 0])
  461. est = Estimator()
  462. est.fit(X, y)
  463. if hasattr(est, "transform"):
  464. est.transform(X)
  465. if hasattr(est, "predict"):
  466. est.predict(X)
  467. SET_OUTPUT_ESTIMATORS = list(
  468. chain(
  469. _tested_estimators("transformer"),
  470. [
  471. make_pipeline(StandardScaler(), MinMaxScaler()),
  472. OneHotEncoder(sparse_output=False),
  473. FunctionTransformer(feature_names_out="one-to-one"),
  474. ],
  475. )
  476. )
  477. @pytest.mark.parametrize(
  478. "estimator", SET_OUTPUT_ESTIMATORS, ids=_get_check_estimator_ids
  479. )
  480. def test_set_output_transform(estimator):
  481. name = estimator.__class__.__name__
  482. if not hasattr(estimator, "set_output"):
  483. pytest.skip(
  484. f"Skipping check_set_output_transform for {name}: Does not support"
  485. " set_output API"
  486. )
  487. _set_checking_parameters(estimator)
  488. with ignore_warnings(category=(FutureWarning)):
  489. check_set_output_transform(estimator.__class__.__name__, estimator)
  490. @pytest.mark.parametrize(
  491. "estimator", SET_OUTPUT_ESTIMATORS, ids=_get_check_estimator_ids
  492. )
  493. def test_set_output_transform_pandas(estimator):
  494. name = estimator.__class__.__name__
  495. if not hasattr(estimator, "set_output"):
  496. pytest.skip(
  497. f"Skipping check_set_output_transform_pandas for {name}: Does not support"
  498. " set_output API yet"
  499. )
  500. _set_checking_parameters(estimator)
  501. with ignore_warnings(category=(FutureWarning)):
  502. check_set_output_transform_pandas(estimator.__class__.__name__, estimator)
  503. @pytest.mark.parametrize(
  504. "estimator", SET_OUTPUT_ESTIMATORS, ids=_get_check_estimator_ids
  505. )
  506. def test_global_output_transform_pandas(estimator):
  507. name = estimator.__class__.__name__
  508. if not hasattr(estimator, "set_output"):
  509. pytest.skip(
  510. f"Skipping check_global_output_transform_pandas for {name}: Does not"
  511. " support set_output API yet"
  512. )
  513. _set_checking_parameters(estimator)
  514. with ignore_warnings(category=(FutureWarning)):
  515. check_global_output_transform_pandas(estimator.__class__.__name__, estimator)