_stacking.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. """Stacking classifier and regressor."""
  2. # Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
  3. # License: BSD 3 clause
  4. from abc import ABCMeta, abstractmethod
  5. from copy import deepcopy
  6. from numbers import Integral
  7. import numpy as np
  8. import scipy.sparse as sparse
  9. from ..base import (
  10. ClassifierMixin,
  11. RegressorMixin,
  12. TransformerMixin,
  13. _fit_context,
  14. clone,
  15. is_classifier,
  16. is_regressor,
  17. )
  18. from ..exceptions import NotFittedError
  19. from ..linear_model import LogisticRegression, RidgeCV
  20. from ..model_selection import check_cv, cross_val_predict
  21. from ..preprocessing import LabelEncoder
  22. from ..utils import Bunch
  23. from ..utils._estimator_html_repr import _VisualBlock
  24. from ..utils._param_validation import HasMethods, StrOptions
  25. from ..utils.metaestimators import available_if
  26. from ..utils.multiclass import check_classification_targets, type_of_target
  27. from ..utils.parallel import Parallel, delayed
  28. from ..utils.validation import (
  29. _check_feature_names_in,
  30. _check_response_method,
  31. check_is_fitted,
  32. column_or_1d,
  33. )
  34. from ._base import _BaseHeterogeneousEnsemble, _fit_single_estimator
  35. def _estimator_has(attr):
  36. """Check if we can delegate a method to the underlying estimator.
  37. First, we check the first fitted final estimator if available, otherwise we
  38. check the unfitted final estimator.
  39. """
  40. return lambda self: (
  41. hasattr(self.final_estimator_, attr)
  42. if hasattr(self, "final_estimator_")
  43. else hasattr(self.final_estimator, attr)
  44. )
  45. class _BaseStacking(TransformerMixin, _BaseHeterogeneousEnsemble, metaclass=ABCMeta):
  46. """Base class for stacking method."""
  47. _parameter_constraints: dict = {
  48. "estimators": [list],
  49. "final_estimator": [None, HasMethods("fit")],
  50. "cv": ["cv_object", StrOptions({"prefit"})],
  51. "n_jobs": [None, Integral],
  52. "passthrough": ["boolean"],
  53. "verbose": ["verbose"],
  54. }
  55. @abstractmethod
  56. def __init__(
  57. self,
  58. estimators,
  59. final_estimator=None,
  60. *,
  61. cv=None,
  62. stack_method="auto",
  63. n_jobs=None,
  64. verbose=0,
  65. passthrough=False,
  66. ):
  67. super().__init__(estimators=estimators)
  68. self.final_estimator = final_estimator
  69. self.cv = cv
  70. self.stack_method = stack_method
  71. self.n_jobs = n_jobs
  72. self.verbose = verbose
  73. self.passthrough = passthrough
  74. def _clone_final_estimator(self, default):
  75. if self.final_estimator is not None:
  76. self.final_estimator_ = clone(self.final_estimator)
  77. else:
  78. self.final_estimator_ = clone(default)
  79. def _concatenate_predictions(self, X, predictions):
  80. """Concatenate the predictions of each first layer learner and
  81. possibly the input dataset `X`.
  82. If `X` is sparse and `self.passthrough` is False, the output of
  83. `transform` will be dense (the predictions). If `X` is sparse
  84. and `self.passthrough` is True, the output of `transform` will
  85. be sparse.
  86. This helper is in charge of ensuring the predictions are 2D arrays and
  87. it will drop one of the probability column when using probabilities
  88. in the binary case. Indeed, the p(y|c=0) = 1 - p(y|c=1)
  89. When `y` type is `"multilabel-indicator"`` and the method used is
  90. `predict_proba`, `preds` can be either a `ndarray` of shape
  91. `(n_samples, n_class)` or for some estimators a list of `ndarray`.
  92. This function will drop one of the probability column in this situation as well.
  93. """
  94. X_meta = []
  95. for est_idx, preds in enumerate(predictions):
  96. if isinstance(preds, list):
  97. # `preds` is here a list of `n_targets` 2D ndarrays of
  98. # `n_classes` columns. The k-th column contains the
  99. # probabilities of the samples belonging the k-th class.
  100. #
  101. # Since those probabilities must sum to one for each sample,
  102. # we can work with probabilities of `n_classes - 1` classes.
  103. # Hence we drop the first column.
  104. for pred in preds:
  105. X_meta.append(pred[:, 1:])
  106. elif preds.ndim == 1:
  107. # Some estimator return a 1D array for predictions
  108. # which must be 2-dimensional arrays.
  109. X_meta.append(preds.reshape(-1, 1))
  110. elif (
  111. self.stack_method_[est_idx] == "predict_proba"
  112. and len(self.classes_) == 2
  113. ):
  114. # Remove the first column when using probabilities in
  115. # binary classification because both features `preds` are perfectly
  116. # collinear.
  117. X_meta.append(preds[:, 1:])
  118. else:
  119. X_meta.append(preds)
  120. self._n_feature_outs = [pred.shape[1] for pred in X_meta]
  121. if self.passthrough:
  122. X_meta.append(X)
  123. if sparse.issparse(X):
  124. return sparse.hstack(X_meta, format=X.format)
  125. return np.hstack(X_meta)
  126. @staticmethod
  127. def _method_name(name, estimator, method):
  128. if estimator == "drop":
  129. return None
  130. if method == "auto":
  131. method = ["predict_proba", "decision_function", "predict"]
  132. try:
  133. method_name = _check_response_method(estimator, method).__name__
  134. except AttributeError as e:
  135. raise ValueError(
  136. f"Underlying estimator {name} does not implement the method {method}."
  137. ) from e
  138. return method_name
  139. @_fit_context(
  140. # estimators in Stacking*.estimators are not validated yet
  141. prefer_skip_nested_validation=False
  142. )
  143. def fit(self, X, y, sample_weight=None):
  144. """Fit the estimators.
  145. Parameters
  146. ----------
  147. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  148. Training vectors, where `n_samples` is the number of samples and
  149. `n_features` is the number of features.
  150. y : array-like of shape (n_samples,)
  151. Target values.
  152. sample_weight : array-like of shape (n_samples,) or default=None
  153. Sample weights. If None, then samples are equally weighted.
  154. Note that this is supported only if all underlying estimators
  155. support sample weights.
  156. .. versionchanged:: 0.23
  157. when not None, `sample_weight` is passed to all underlying
  158. estimators
  159. Returns
  160. -------
  161. self : object
  162. """
  163. # all_estimators contains all estimators, the one to be fitted and the
  164. # 'drop' string.
  165. names, all_estimators = self._validate_estimators()
  166. self._validate_final_estimator()
  167. stack_method = [self.stack_method] * len(all_estimators)
  168. if self.cv == "prefit":
  169. self.estimators_ = []
  170. for estimator in all_estimators:
  171. if estimator != "drop":
  172. check_is_fitted(estimator)
  173. self.estimators_.append(estimator)
  174. else:
  175. # Fit the base estimators on the whole training data. Those
  176. # base estimators will be used in transform, predict, and
  177. # predict_proba. They are exposed publicly.
  178. self.estimators_ = Parallel(n_jobs=self.n_jobs)(
  179. delayed(_fit_single_estimator)(clone(est), X, y, sample_weight)
  180. for est in all_estimators
  181. if est != "drop"
  182. )
  183. self.named_estimators_ = Bunch()
  184. est_fitted_idx = 0
  185. for name_est, org_est in zip(names, all_estimators):
  186. if org_est != "drop":
  187. current_estimator = self.estimators_[est_fitted_idx]
  188. self.named_estimators_[name_est] = current_estimator
  189. est_fitted_idx += 1
  190. if hasattr(current_estimator, "feature_names_in_"):
  191. self.feature_names_in_ = current_estimator.feature_names_in_
  192. else:
  193. self.named_estimators_[name_est] = "drop"
  194. self.stack_method_ = [
  195. self._method_name(name, est, meth)
  196. for name, est, meth in zip(names, all_estimators, stack_method)
  197. ]
  198. if self.cv == "prefit":
  199. # Generate predictions from prefit models
  200. predictions = [
  201. getattr(estimator, predict_method)(X)
  202. for estimator, predict_method in zip(all_estimators, self.stack_method_)
  203. if estimator != "drop"
  204. ]
  205. else:
  206. # To train the meta-classifier using the most data as possible, we use
  207. # a cross-validation to obtain the output of the stacked estimators.
  208. # To ensure that the data provided to each estimator are the same,
  209. # we need to set the random state of the cv if there is one and we
  210. # need to take a copy.
  211. cv = check_cv(self.cv, y=y, classifier=is_classifier(self))
  212. if hasattr(cv, "random_state") and cv.random_state is None:
  213. cv.random_state = np.random.RandomState()
  214. fit_params = (
  215. {"sample_weight": sample_weight} if sample_weight is not None else None
  216. )
  217. predictions = Parallel(n_jobs=self.n_jobs)(
  218. delayed(cross_val_predict)(
  219. clone(est),
  220. X,
  221. y,
  222. cv=deepcopy(cv),
  223. method=meth,
  224. n_jobs=self.n_jobs,
  225. fit_params=fit_params,
  226. verbose=self.verbose,
  227. )
  228. for est, meth in zip(all_estimators, self.stack_method_)
  229. if est != "drop"
  230. )
  231. # Only not None or not 'drop' estimators will be used in transform.
  232. # Remove the None from the method as well.
  233. self.stack_method_ = [
  234. meth
  235. for (meth, est) in zip(self.stack_method_, all_estimators)
  236. if est != "drop"
  237. ]
  238. X_meta = self._concatenate_predictions(X, predictions)
  239. _fit_single_estimator(
  240. self.final_estimator_, X_meta, y, sample_weight=sample_weight
  241. )
  242. return self
  243. @property
  244. def n_features_in_(self):
  245. """Number of features seen during :term:`fit`."""
  246. try:
  247. check_is_fitted(self)
  248. except NotFittedError as nfe:
  249. raise AttributeError(
  250. f"{self.__class__.__name__} object has no attribute n_features_in_"
  251. ) from nfe
  252. return self.estimators_[0].n_features_in_
  253. def _transform(self, X):
  254. """Concatenate and return the predictions of the estimators."""
  255. check_is_fitted(self)
  256. predictions = [
  257. getattr(est, meth)(X)
  258. for est, meth in zip(self.estimators_, self.stack_method_)
  259. if est != "drop"
  260. ]
  261. return self._concatenate_predictions(X, predictions)
  262. def get_feature_names_out(self, input_features=None):
  263. """Get output feature names for transformation.
  264. Parameters
  265. ----------
  266. input_features : array-like of str or None, default=None
  267. Input features. The input feature names are only used when `passthrough` is
  268. `True`.
  269. - If `input_features` is `None`, then `feature_names_in_` is
  270. used as feature names in. If `feature_names_in_` is not defined,
  271. then names are generated: `[x0, x1, ..., x(n_features_in_ - 1)]`.
  272. - If `input_features` is an array-like, then `input_features` must
  273. match `feature_names_in_` if `feature_names_in_` is defined.
  274. If `passthrough` is `False`, then only the names of `estimators` are used
  275. to generate the output feature names.
  276. Returns
  277. -------
  278. feature_names_out : ndarray of str objects
  279. Transformed feature names.
  280. """
  281. check_is_fitted(self, "n_features_in_")
  282. input_features = _check_feature_names_in(
  283. self, input_features, generate_names=self.passthrough
  284. )
  285. class_name = self.__class__.__name__.lower()
  286. non_dropped_estimators = (
  287. name for name, est in self.estimators if est != "drop"
  288. )
  289. meta_names = []
  290. for est, n_features_out in zip(non_dropped_estimators, self._n_feature_outs):
  291. if n_features_out == 1:
  292. meta_names.append(f"{class_name}_{est}")
  293. else:
  294. meta_names.extend(
  295. f"{class_name}_{est}{i}" for i in range(n_features_out)
  296. )
  297. if self.passthrough:
  298. return np.concatenate((meta_names, input_features))
  299. return np.asarray(meta_names, dtype=object)
  300. @available_if(_estimator_has("predict"))
  301. def predict(self, X, **predict_params):
  302. """Predict target for X.
  303. Parameters
  304. ----------
  305. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  306. Training vectors, where `n_samples` is the number of samples and
  307. `n_features` is the number of features.
  308. **predict_params : dict of str -> obj
  309. Parameters to the `predict` called by the `final_estimator`. Note
  310. that this may be used to return uncertainties from some estimators
  311. with `return_std` or `return_cov`. Be aware that it will only
  312. accounts for uncertainty in the final estimator.
  313. Returns
  314. -------
  315. y_pred : ndarray of shape (n_samples,) or (n_samples, n_output)
  316. Predicted targets.
  317. """
  318. check_is_fitted(self)
  319. return self.final_estimator_.predict(self.transform(X), **predict_params)
  320. def _sk_visual_block_with_final_estimator(self, final_estimator):
  321. names, estimators = zip(*self.estimators)
  322. parallel = _VisualBlock("parallel", estimators, names=names, dash_wrapped=False)
  323. # final estimator is wrapped in a parallel block to show the label:
  324. # 'final_estimator' in the html repr
  325. final_block = _VisualBlock(
  326. "parallel", [final_estimator], names=["final_estimator"], dash_wrapped=False
  327. )
  328. return _VisualBlock("serial", (parallel, final_block), dash_wrapped=False)
  329. class StackingClassifier(ClassifierMixin, _BaseStacking):
  330. """Stack of estimators with a final classifier.
  331. Stacked generalization consists in stacking the output of individual
  332. estimator and use a classifier to compute the final prediction. Stacking
  333. allows to use the strength of each individual estimator by using their
  334. output as input of a final estimator.
  335. Note that `estimators_` are fitted on the full `X` while `final_estimator_`
  336. is trained using cross-validated predictions of the base estimators using
  337. `cross_val_predict`.
  338. Read more in the :ref:`User Guide <stacking>`.
  339. .. versionadded:: 0.22
  340. Parameters
  341. ----------
  342. estimators : list of (str, estimator)
  343. Base estimators which will be stacked together. Each element of the
  344. list is defined as a tuple of string (i.e. name) and an estimator
  345. instance. An estimator can be set to 'drop' using `set_params`.
  346. The type of estimator is generally expected to be a classifier.
  347. However, one can pass a regressor for some use case (e.g. ordinal
  348. regression).
  349. final_estimator : estimator, default=None
  350. A classifier which will be used to combine the base estimators.
  351. The default classifier is a
  352. :class:`~sklearn.linear_model.LogisticRegression`.
  353. cv : int, cross-validation generator, iterable, or "prefit", default=None
  354. Determines the cross-validation splitting strategy used in
  355. `cross_val_predict` to train `final_estimator`. Possible inputs for
  356. cv are:
  357. * None, to use the default 5-fold cross validation,
  358. * integer, to specify the number of folds in a (Stratified) KFold,
  359. * An object to be used as a cross-validation generator,
  360. * An iterable yielding train, test splits,
  361. * `"prefit"` to assume the `estimators` are prefit. In this case, the
  362. estimators will not be refitted.
  363. For integer/None inputs, if the estimator is a classifier and y is
  364. either binary or multiclass,
  365. :class:`~sklearn.model_selection.StratifiedKFold` is used.
  366. In all other cases, :class:`~sklearn.model_selection.KFold` is used.
  367. These splitters are instantiated with `shuffle=False` so the splits
  368. will be the same across calls.
  369. Refer :ref:`User Guide <cross_validation>` for the various
  370. cross-validation strategies that can be used here.
  371. If "prefit" is passed, it is assumed that all `estimators` have
  372. been fitted already. The `final_estimator_` is trained on the `estimators`
  373. predictions on the full training set and are **not** cross validated
  374. predictions. Please note that if the models have been trained on the same
  375. data to train the stacking model, there is a very high risk of overfitting.
  376. .. versionadded:: 1.1
  377. The 'prefit' option was added in 1.1
  378. .. note::
  379. A larger number of split will provide no benefits if the number
  380. of training samples is large enough. Indeed, the training time
  381. will increase. ``cv`` is not used for model evaluation but for
  382. prediction.
  383. stack_method : {'auto', 'predict_proba', 'decision_function', 'predict'}, \
  384. default='auto'
  385. Methods called for each base estimator. It can be:
  386. * if 'auto', it will try to invoke, for each estimator,
  387. `'predict_proba'`, `'decision_function'` or `'predict'` in that
  388. order.
  389. * otherwise, one of `'predict_proba'`, `'decision_function'` or
  390. `'predict'`. If the method is not implemented by the estimator, it
  391. will raise an error.
  392. n_jobs : int, default=None
  393. The number of jobs to run in parallel all `estimators` `fit`.
  394. `None` means 1 unless in a `joblib.parallel_backend` context. -1 means
  395. using all processors. See Glossary for more details.
  396. passthrough : bool, default=False
  397. When False, only the predictions of estimators will be used as
  398. training data for `final_estimator`. When True, the
  399. `final_estimator` is trained on the predictions as well as the
  400. original training data.
  401. verbose : int, default=0
  402. Verbosity level.
  403. Attributes
  404. ----------
  405. classes_ : ndarray of shape (n_classes,) or list of ndarray if `y` \
  406. is of type `"multilabel-indicator"`.
  407. Class labels.
  408. estimators_ : list of estimators
  409. The elements of the `estimators` parameter, having been fitted on the
  410. training data. If an estimator has been set to `'drop'`, it
  411. will not appear in `estimators_`. When `cv="prefit"`, `estimators_`
  412. is set to `estimators` and is not fitted again.
  413. named_estimators_ : :class:`~sklearn.utils.Bunch`
  414. Attribute to access any fitted sub-estimators by name.
  415. n_features_in_ : int
  416. Number of features seen during :term:`fit`. Only defined if the
  417. underlying classifier exposes such an attribute when fit.
  418. .. versionadded:: 0.24
  419. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  420. Names of features seen during :term:`fit`. Only defined if the
  421. underlying estimators expose such an attribute when fit.
  422. .. versionadded:: 1.0
  423. final_estimator_ : estimator
  424. The classifier which predicts given the output of `estimators_`.
  425. stack_method_ : list of str
  426. The method used by each base estimator.
  427. See Also
  428. --------
  429. StackingRegressor : Stack of estimators with a final regressor.
  430. Notes
  431. -----
  432. When `predict_proba` is used by each estimator (i.e. most of the time for
  433. `stack_method='auto'` or specifically for `stack_method='predict_proba'`),
  434. The first column predicted by each estimator will be dropped in the case
  435. of a binary classification problem. Indeed, both feature will be perfectly
  436. collinear.
  437. In some cases (e.g. ordinal regression), one can pass regressors as the
  438. first layer of the :class:`StackingClassifier`. However, note that `y` will
  439. be internally encoded in a numerically increasing order or lexicographic
  440. order. If this ordering is not adequate, one should manually numerically
  441. encode the classes in the desired order.
  442. References
  443. ----------
  444. .. [1] Wolpert, David H. "Stacked generalization." Neural networks 5.2
  445. (1992): 241-259.
  446. Examples
  447. --------
  448. >>> from sklearn.datasets import load_iris
  449. >>> from sklearn.ensemble import RandomForestClassifier
  450. >>> from sklearn.svm import LinearSVC
  451. >>> from sklearn.linear_model import LogisticRegression
  452. >>> from sklearn.preprocessing import StandardScaler
  453. >>> from sklearn.pipeline import make_pipeline
  454. >>> from sklearn.ensemble import StackingClassifier
  455. >>> X, y = load_iris(return_X_y=True)
  456. >>> estimators = [
  457. ... ('rf', RandomForestClassifier(n_estimators=10, random_state=42)),
  458. ... ('svr', make_pipeline(StandardScaler(),
  459. ... LinearSVC(dual="auto", random_state=42)))
  460. ... ]
  461. >>> clf = StackingClassifier(
  462. ... estimators=estimators, final_estimator=LogisticRegression()
  463. ... )
  464. >>> from sklearn.model_selection import train_test_split
  465. >>> X_train, X_test, y_train, y_test = train_test_split(
  466. ... X, y, stratify=y, random_state=42
  467. ... )
  468. >>> clf.fit(X_train, y_train).score(X_test, y_test)
  469. 0.9...
  470. """
  471. _parameter_constraints: dict = {
  472. **_BaseStacking._parameter_constraints,
  473. "stack_method": [
  474. StrOptions({"auto", "predict_proba", "decision_function", "predict"})
  475. ],
  476. }
  477. def __init__(
  478. self,
  479. estimators,
  480. final_estimator=None,
  481. *,
  482. cv=None,
  483. stack_method="auto",
  484. n_jobs=None,
  485. passthrough=False,
  486. verbose=0,
  487. ):
  488. super().__init__(
  489. estimators=estimators,
  490. final_estimator=final_estimator,
  491. cv=cv,
  492. stack_method=stack_method,
  493. n_jobs=n_jobs,
  494. passthrough=passthrough,
  495. verbose=verbose,
  496. )
  497. def _validate_final_estimator(self):
  498. self._clone_final_estimator(default=LogisticRegression())
  499. if not is_classifier(self.final_estimator_):
  500. raise ValueError(
  501. "'final_estimator' parameter should be a classifier. Got {}".format(
  502. self.final_estimator_
  503. )
  504. )
  505. def _validate_estimators(self):
  506. """Overload the method of `_BaseHeterogeneousEnsemble` to be more
  507. lenient towards the type of `estimators`.
  508. Regressors can be accepted for some cases such as ordinal regression.
  509. """
  510. if len(self.estimators) == 0:
  511. raise ValueError(
  512. "Invalid 'estimators' attribute, 'estimators' should be a "
  513. "non-empty list of (string, estimator) tuples."
  514. )
  515. names, estimators = zip(*self.estimators)
  516. self._validate_names(names)
  517. has_estimator = any(est != "drop" for est in estimators)
  518. if not has_estimator:
  519. raise ValueError(
  520. "All estimators are dropped. At least one is required "
  521. "to be an estimator."
  522. )
  523. return names, estimators
  524. def fit(self, X, y, sample_weight=None):
  525. """Fit the estimators.
  526. Parameters
  527. ----------
  528. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  529. Training vectors, where `n_samples` is the number of samples and
  530. `n_features` is the number of features.
  531. y : array-like of shape (n_samples,)
  532. Target values. Note that `y` will be internally encoded in
  533. numerically increasing order or lexicographic order. If the order
  534. matter (e.g. for ordinal regression), one should numerically encode
  535. the target `y` before calling :term:`fit`.
  536. sample_weight : array-like of shape (n_samples,), default=None
  537. Sample weights. If None, then samples are equally weighted.
  538. Note that this is supported only if all underlying estimators
  539. support sample weights.
  540. Returns
  541. -------
  542. self : object
  543. Returns a fitted instance of estimator.
  544. """
  545. check_classification_targets(y)
  546. if type_of_target(y) == "multilabel-indicator":
  547. self._label_encoder = [LabelEncoder().fit(yk) for yk in y.T]
  548. self.classes_ = [le.classes_ for le in self._label_encoder]
  549. y_encoded = np.array(
  550. [
  551. self._label_encoder[target_idx].transform(target)
  552. for target_idx, target in enumerate(y.T)
  553. ]
  554. ).T
  555. else:
  556. self._label_encoder = LabelEncoder().fit(y)
  557. self.classes_ = self._label_encoder.classes_
  558. y_encoded = self._label_encoder.transform(y)
  559. return super().fit(X, y_encoded, sample_weight)
  560. @available_if(_estimator_has("predict"))
  561. def predict(self, X, **predict_params):
  562. """Predict target for X.
  563. Parameters
  564. ----------
  565. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  566. Training vectors, where `n_samples` is the number of samples and
  567. `n_features` is the number of features.
  568. **predict_params : dict of str -> obj
  569. Parameters to the `predict` called by the `final_estimator`. Note
  570. that this may be used to return uncertainties from some estimators
  571. with `return_std` or `return_cov`. Be aware that it will only
  572. accounts for uncertainty in the final estimator.
  573. Returns
  574. -------
  575. y_pred : ndarray of shape (n_samples,) or (n_samples, n_output)
  576. Predicted targets.
  577. """
  578. y_pred = super().predict(X, **predict_params)
  579. if isinstance(self._label_encoder, list):
  580. # Handle the multilabel-indicator case
  581. y_pred = np.array(
  582. [
  583. self._label_encoder[target_idx].inverse_transform(target)
  584. for target_idx, target in enumerate(y_pred.T)
  585. ]
  586. ).T
  587. else:
  588. y_pred = self._label_encoder.inverse_transform(y_pred)
  589. return y_pred
  590. @available_if(_estimator_has("predict_proba"))
  591. def predict_proba(self, X):
  592. """Predict class probabilities for `X` using the final estimator.
  593. Parameters
  594. ----------
  595. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  596. Training vectors, where `n_samples` is the number of samples and
  597. `n_features` is the number of features.
  598. Returns
  599. -------
  600. probabilities : ndarray of shape (n_samples, n_classes) or \
  601. list of ndarray of shape (n_output,)
  602. The class probabilities of the input samples.
  603. """
  604. check_is_fitted(self)
  605. y_pred = self.final_estimator_.predict_proba(self.transform(X))
  606. if isinstance(self._label_encoder, list):
  607. # Handle the multilabel-indicator cases
  608. y_pred = np.array([preds[:, 0] for preds in y_pred]).T
  609. return y_pred
  610. @available_if(_estimator_has("decision_function"))
  611. def decision_function(self, X):
  612. """Decision function for samples in `X` using the final estimator.
  613. Parameters
  614. ----------
  615. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  616. Training vectors, where `n_samples` is the number of samples and
  617. `n_features` is the number of features.
  618. Returns
  619. -------
  620. decisions : ndarray of shape (n_samples,), (n_samples, n_classes), \
  621. or (n_samples, n_classes * (n_classes-1) / 2)
  622. The decision function computed the final estimator.
  623. """
  624. check_is_fitted(self)
  625. return self.final_estimator_.decision_function(self.transform(X))
  626. def transform(self, X):
  627. """Return class labels or probabilities for X for each estimator.
  628. Parameters
  629. ----------
  630. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  631. Training vectors, where `n_samples` is the number of samples and
  632. `n_features` is the number of features.
  633. Returns
  634. -------
  635. y_preds : ndarray of shape (n_samples, n_estimators) or \
  636. (n_samples, n_classes * n_estimators)
  637. Prediction outputs for each estimator.
  638. """
  639. return self._transform(X)
  640. def _sk_visual_block_(self):
  641. # If final_estimator's default changes then this should be
  642. # updated.
  643. if self.final_estimator is None:
  644. final_estimator = LogisticRegression()
  645. else:
  646. final_estimator = self.final_estimator
  647. return super()._sk_visual_block_with_final_estimator(final_estimator)
  648. class StackingRegressor(RegressorMixin, _BaseStacking):
  649. """Stack of estimators with a final regressor.
  650. Stacked generalization consists in stacking the output of individual
  651. estimator and use a regressor to compute the final prediction. Stacking
  652. allows to use the strength of each individual estimator by using their
  653. output as input of a final estimator.
  654. Note that `estimators_` are fitted on the full `X` while `final_estimator_`
  655. is trained using cross-validated predictions of the base estimators using
  656. `cross_val_predict`.
  657. Read more in the :ref:`User Guide <stacking>`.
  658. .. versionadded:: 0.22
  659. Parameters
  660. ----------
  661. estimators : list of (str, estimator)
  662. Base estimators which will be stacked together. Each element of the
  663. list is defined as a tuple of string (i.e. name) and an estimator
  664. instance. An estimator can be set to 'drop' using `set_params`.
  665. final_estimator : estimator, default=None
  666. A regressor which will be used to combine the base estimators.
  667. The default regressor is a :class:`~sklearn.linear_model.RidgeCV`.
  668. cv : int, cross-validation generator, iterable, or "prefit", default=None
  669. Determines the cross-validation splitting strategy used in
  670. `cross_val_predict` to train `final_estimator`. Possible inputs for
  671. cv are:
  672. * None, to use the default 5-fold cross validation,
  673. * integer, to specify the number of folds in a (Stratified) KFold,
  674. * An object to be used as a cross-validation generator,
  675. * An iterable yielding train, test splits.
  676. * "prefit" to assume the `estimators` are prefit, and skip cross validation
  677. For integer/None inputs, if the estimator is a classifier and y is
  678. either binary or multiclass,
  679. :class:`~sklearn.model_selection.StratifiedKFold` is used.
  680. In all other cases, :class:`~sklearn.model_selection.KFold` is used.
  681. These splitters are instantiated with `shuffle=False` so the splits
  682. will be the same across calls.
  683. Refer :ref:`User Guide <cross_validation>` for the various
  684. cross-validation strategies that can be used here.
  685. If "prefit" is passed, it is assumed that all `estimators` have
  686. been fitted already. The `final_estimator_` is trained on the `estimators`
  687. predictions on the full training set and are **not** cross validated
  688. predictions. Please note that if the models have been trained on the same
  689. data to train the stacking model, there is a very high risk of overfitting.
  690. .. versionadded:: 1.1
  691. The 'prefit' option was added in 1.1
  692. .. note::
  693. A larger number of split will provide no benefits if the number
  694. of training samples is large enough. Indeed, the training time
  695. will increase. ``cv`` is not used for model evaluation but for
  696. prediction.
  697. n_jobs : int, default=None
  698. The number of jobs to run in parallel for `fit` of all `estimators`.
  699. `None` means 1 unless in a `joblib.parallel_backend` context. -1 means
  700. using all processors. See Glossary for more details.
  701. passthrough : bool, default=False
  702. When False, only the predictions of estimators will be used as
  703. training data for `final_estimator`. When True, the
  704. `final_estimator` is trained on the predictions as well as the
  705. original training data.
  706. verbose : int, default=0
  707. Verbosity level.
  708. Attributes
  709. ----------
  710. estimators_ : list of estimator
  711. The elements of the `estimators` parameter, having been fitted on the
  712. training data. If an estimator has been set to `'drop'`, it
  713. will not appear in `estimators_`. When `cv="prefit"`, `estimators_`
  714. is set to `estimators` and is not fitted again.
  715. named_estimators_ : :class:`~sklearn.utils.Bunch`
  716. Attribute to access any fitted sub-estimators by name.
  717. n_features_in_ : int
  718. Number of features seen during :term:`fit`. Only defined if the
  719. underlying regressor exposes such an attribute when fit.
  720. .. versionadded:: 0.24
  721. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  722. Names of features seen during :term:`fit`. Only defined if the
  723. underlying estimators expose such an attribute when fit.
  724. .. versionadded:: 1.0
  725. final_estimator_ : estimator
  726. The regressor to stacked the base estimators fitted.
  727. stack_method_ : list of str
  728. The method used by each base estimator.
  729. See Also
  730. --------
  731. StackingClassifier : Stack of estimators with a final classifier.
  732. References
  733. ----------
  734. .. [1] Wolpert, David H. "Stacked generalization." Neural networks 5.2
  735. (1992): 241-259.
  736. Examples
  737. --------
  738. >>> from sklearn.datasets import load_diabetes
  739. >>> from sklearn.linear_model import RidgeCV
  740. >>> from sklearn.svm import LinearSVR
  741. >>> from sklearn.ensemble import RandomForestRegressor
  742. >>> from sklearn.ensemble import StackingRegressor
  743. >>> X, y = load_diabetes(return_X_y=True)
  744. >>> estimators = [
  745. ... ('lr', RidgeCV()),
  746. ... ('svr', LinearSVR(dual="auto", random_state=42))
  747. ... ]
  748. >>> reg = StackingRegressor(
  749. ... estimators=estimators,
  750. ... final_estimator=RandomForestRegressor(n_estimators=10,
  751. ... random_state=42)
  752. ... )
  753. >>> from sklearn.model_selection import train_test_split
  754. >>> X_train, X_test, y_train, y_test = train_test_split(
  755. ... X, y, random_state=42
  756. ... )
  757. >>> reg.fit(X_train, y_train).score(X_test, y_test)
  758. 0.3...
  759. """
  760. def __init__(
  761. self,
  762. estimators,
  763. final_estimator=None,
  764. *,
  765. cv=None,
  766. n_jobs=None,
  767. passthrough=False,
  768. verbose=0,
  769. ):
  770. super().__init__(
  771. estimators=estimators,
  772. final_estimator=final_estimator,
  773. cv=cv,
  774. stack_method="predict",
  775. n_jobs=n_jobs,
  776. passthrough=passthrough,
  777. verbose=verbose,
  778. )
  779. def _validate_final_estimator(self):
  780. self._clone_final_estimator(default=RidgeCV())
  781. if not is_regressor(self.final_estimator_):
  782. raise ValueError(
  783. "'final_estimator' parameter should be a regressor. Got {}".format(
  784. self.final_estimator_
  785. )
  786. )
  787. def fit(self, X, y, sample_weight=None):
  788. """Fit the estimators.
  789. Parameters
  790. ----------
  791. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  792. Training vectors, where `n_samples` is the number of samples and
  793. `n_features` is the number of features.
  794. y : array-like of shape (n_samples,)
  795. Target values.
  796. sample_weight : array-like of shape (n_samples,), default=None
  797. Sample weights. If None, then samples are equally weighted.
  798. Note that this is supported only if all underlying estimators
  799. support sample weights.
  800. Returns
  801. -------
  802. self : object
  803. Returns a fitted instance.
  804. """
  805. y = column_or_1d(y, warn=True)
  806. return super().fit(X, y, sample_weight)
  807. def transform(self, X):
  808. """Return the predictions for X for each estimator.
  809. Parameters
  810. ----------
  811. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  812. Training vectors, where `n_samples` is the number of samples and
  813. `n_features` is the number of features.
  814. Returns
  815. -------
  816. y_preds : ndarray of shape (n_samples, n_estimators)
  817. Prediction outputs for each estimator.
  818. """
  819. return self._transform(X)
  820. def fit_transform(self, X, y, sample_weight=None):
  821. """Fit the estimators and return the predictions for X for each estimator.
  822. Parameters
  823. ----------
  824. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  825. Training vectors, where `n_samples` is the number of samples and
  826. `n_features` is the number of features.
  827. y : array-like of shape (n_samples,)
  828. Target values.
  829. sample_weight : array-like of shape (n_samples,), default=None
  830. Sample weights. If None, then samples are equally weighted.
  831. Note that this is supported only if all underlying estimators
  832. support sample weights.
  833. Returns
  834. -------
  835. y_preds : ndarray of shape (n_samples, n_estimators)
  836. Prediction outputs for each estimator.
  837. """
  838. return super().fit_transform(X, y, sample_weight=sample_weight)
  839. def _sk_visual_block_(self):
  840. # If final_estimator's default changes then this should be
  841. # updated.
  842. if self.final_estimator is None:
  843. final_estimator = RidgeCV()
  844. else:
  845. final_estimator = self.final_estimator
  846. return super()._sk_visual_block_with_final_estimator(final_estimator)