_weight_boosting.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. """Weight Boosting.
  2. This module contains weight boosting estimators for both classification and
  3. regression.
  4. The module structure is the following:
  5. - The `BaseWeightBoosting` base class implements a common ``fit`` method
  6. for all the estimators in the module. Regression and classification
  7. only differ from each other in the loss function that is optimized.
  8. - :class:`~sklearn.ensemble.AdaBoostClassifier` implements adaptive boosting
  9. (AdaBoost-SAMME) for classification problems.
  10. - :class:`~sklearn.ensemble.AdaBoostRegressor` implements adaptive boosting
  11. (AdaBoost.R2) for regression problems.
  12. """
  13. # Authors: Noel Dawe <noel@dawe.me>
  14. # Gilles Louppe <g.louppe@gmail.com>
  15. # Hamzeh Alsalhi <ha258@cornell.edu>
  16. # Arnaud Joly <arnaud.v.joly@gmail.com>
  17. #
  18. # License: BSD 3 clause
  19. import warnings
  20. from abc import ABCMeta, abstractmethod
  21. from numbers import Integral, Real
  22. import numpy as np
  23. from scipy.special import xlogy
  24. from ..base import (
  25. ClassifierMixin,
  26. RegressorMixin,
  27. _fit_context,
  28. is_classifier,
  29. is_regressor,
  30. )
  31. from ..metrics import accuracy_score, r2_score
  32. from ..tree import DecisionTreeClassifier, DecisionTreeRegressor
  33. from ..utils import _safe_indexing, check_random_state
  34. from ..utils._param_validation import HasMethods, Interval, StrOptions
  35. from ..utils.extmath import softmax, stable_cumsum
  36. from ..utils.validation import (
  37. _check_sample_weight,
  38. _num_samples,
  39. check_is_fitted,
  40. has_fit_parameter,
  41. )
  42. from ._base import BaseEnsemble
  43. __all__ = [
  44. "AdaBoostClassifier",
  45. "AdaBoostRegressor",
  46. ]
  47. class BaseWeightBoosting(BaseEnsemble, metaclass=ABCMeta):
  48. """Base class for AdaBoost estimators.
  49. Warning: This class should not be used directly. Use derived classes
  50. instead.
  51. """
  52. _parameter_constraints: dict = {
  53. "estimator": [HasMethods(["fit", "predict"]), None],
  54. "n_estimators": [Interval(Integral, 1, None, closed="left")],
  55. "learning_rate": [Interval(Real, 0, None, closed="neither")],
  56. "random_state": ["random_state"],
  57. "base_estimator": [
  58. HasMethods(["fit", "predict"]),
  59. StrOptions({"deprecated"}),
  60. None,
  61. ],
  62. }
  63. @abstractmethod
  64. def __init__(
  65. self,
  66. estimator=None,
  67. *,
  68. n_estimators=50,
  69. estimator_params=tuple(),
  70. learning_rate=1.0,
  71. random_state=None,
  72. base_estimator="deprecated",
  73. ):
  74. super().__init__(
  75. estimator=estimator,
  76. n_estimators=n_estimators,
  77. estimator_params=estimator_params,
  78. base_estimator=base_estimator,
  79. )
  80. self.learning_rate = learning_rate
  81. self.random_state = random_state
  82. def _check_X(self, X):
  83. # Only called to validate X in non-fit methods, therefore reset=False
  84. return self._validate_data(
  85. X,
  86. accept_sparse=["csr", "csc"],
  87. ensure_2d=True,
  88. allow_nd=True,
  89. dtype=None,
  90. reset=False,
  91. )
  92. @_fit_context(
  93. # AdaBoost*.estimator is not validated yet
  94. prefer_skip_nested_validation=False
  95. )
  96. def fit(self, X, y, sample_weight=None):
  97. """Build a boosted classifier/regressor from the training set (X, y).
  98. Parameters
  99. ----------
  100. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  101. The training input samples. Sparse matrix can be CSC, CSR, COO,
  102. DOK, or LIL. COO, DOK, and LIL are converted to CSR.
  103. y : array-like of shape (n_samples,)
  104. The target values.
  105. sample_weight : array-like of shape (n_samples,), default=None
  106. Sample weights. If None, the sample weights are initialized to
  107. 1 / n_samples.
  108. Returns
  109. -------
  110. self : object
  111. Fitted estimator.
  112. """
  113. X, y = self._validate_data(
  114. X,
  115. y,
  116. accept_sparse=["csr", "csc"],
  117. ensure_2d=True,
  118. allow_nd=True,
  119. dtype=None,
  120. y_numeric=is_regressor(self),
  121. )
  122. sample_weight = _check_sample_weight(
  123. sample_weight, X, np.float64, copy=True, only_non_negative=True
  124. )
  125. sample_weight /= sample_weight.sum()
  126. # Check parameters
  127. self._validate_estimator()
  128. # Clear any previous fit results
  129. self.estimators_ = []
  130. self.estimator_weights_ = np.zeros(self.n_estimators, dtype=np.float64)
  131. self.estimator_errors_ = np.ones(self.n_estimators, dtype=np.float64)
  132. # Initialization of the random number instance that will be used to
  133. # generate a seed at each iteration
  134. random_state = check_random_state(self.random_state)
  135. epsilon = np.finfo(sample_weight.dtype).eps
  136. zero_weight_mask = sample_weight == 0.0
  137. for iboost in range(self.n_estimators):
  138. # avoid extremely small sample weight, for details see issue #20320
  139. sample_weight = np.clip(sample_weight, a_min=epsilon, a_max=None)
  140. # do not clip sample weights that were exactly zero originally
  141. sample_weight[zero_weight_mask] = 0.0
  142. # Boosting step
  143. sample_weight, estimator_weight, estimator_error = self._boost(
  144. iboost, X, y, sample_weight, random_state
  145. )
  146. # Early termination
  147. if sample_weight is None:
  148. break
  149. self.estimator_weights_[iboost] = estimator_weight
  150. self.estimator_errors_[iboost] = estimator_error
  151. # Stop if error is zero
  152. if estimator_error == 0:
  153. break
  154. sample_weight_sum = np.sum(sample_weight)
  155. if not np.isfinite(sample_weight_sum):
  156. warnings.warn(
  157. (
  158. "Sample weights have reached infinite values,"
  159. f" at iteration {iboost}, causing overflow. "
  160. "Iterations stopped. Try lowering the learning rate."
  161. ),
  162. stacklevel=2,
  163. )
  164. break
  165. # Stop if the sum of sample weights has become non-positive
  166. if sample_weight_sum <= 0:
  167. break
  168. if iboost < self.n_estimators - 1:
  169. # Normalize
  170. sample_weight /= sample_weight_sum
  171. return self
  172. @abstractmethod
  173. def _boost(self, iboost, X, y, sample_weight, random_state):
  174. """Implement a single boost.
  175. Warning: This method needs to be overridden by subclasses.
  176. Parameters
  177. ----------
  178. iboost : int
  179. The index of the current boost iteration.
  180. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  181. The training input samples. Sparse matrix can be CSC, CSR, COO,
  182. DOK, or LIL. COO, DOK, and LIL are converted to CSR.
  183. y : array-like of shape (n_samples,)
  184. The target values (class labels).
  185. sample_weight : array-like of shape (n_samples,)
  186. The current sample weights.
  187. random_state : RandomState
  188. The current random number generator
  189. Returns
  190. -------
  191. sample_weight : array-like of shape (n_samples,) or None
  192. The reweighted sample weights.
  193. If None then boosting has terminated early.
  194. estimator_weight : float
  195. The weight for the current boost.
  196. If None then boosting has terminated early.
  197. error : float
  198. The classification error for the current boost.
  199. If None then boosting has terminated early.
  200. """
  201. pass
  202. def staged_score(self, X, y, sample_weight=None):
  203. """Return staged scores for X, y.
  204. This generator method yields the ensemble score after each iteration of
  205. boosting and therefore allows monitoring, such as to determine the
  206. score on a test set after each boost.
  207. Parameters
  208. ----------
  209. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  210. The training input samples. Sparse matrix can be CSC, CSR, COO,
  211. DOK, or LIL. COO, DOK, and LIL are converted to CSR.
  212. y : array-like of shape (n_samples,)
  213. Labels for X.
  214. sample_weight : array-like of shape (n_samples,), default=None
  215. Sample weights.
  216. Yields
  217. ------
  218. z : float
  219. """
  220. X = self._check_X(X)
  221. for y_pred in self.staged_predict(X):
  222. if is_classifier(self):
  223. yield accuracy_score(y, y_pred, sample_weight=sample_weight)
  224. else:
  225. yield r2_score(y, y_pred, sample_weight=sample_weight)
  226. @property
  227. def feature_importances_(self):
  228. """The impurity-based feature importances.
  229. The higher, the more important the feature.
  230. The importance of a feature is computed as the (normalized)
  231. total reduction of the criterion brought by that feature. It is also
  232. known as the Gini importance.
  233. Warning: impurity-based feature importances can be misleading for
  234. high cardinality features (many unique values). See
  235. :func:`sklearn.inspection.permutation_importance` as an alternative.
  236. Returns
  237. -------
  238. feature_importances_ : ndarray of shape (n_features,)
  239. The feature importances.
  240. """
  241. if self.estimators_ is None or len(self.estimators_) == 0:
  242. raise ValueError(
  243. "Estimator not fitted, call `fit` before `feature_importances_`."
  244. )
  245. try:
  246. norm = self.estimator_weights_.sum()
  247. return (
  248. sum(
  249. weight * clf.feature_importances_
  250. for weight, clf in zip(self.estimator_weights_, self.estimators_)
  251. )
  252. / norm
  253. )
  254. except AttributeError as e:
  255. raise AttributeError(
  256. "Unable to compute feature importances "
  257. "since estimator does not have a "
  258. "feature_importances_ attribute"
  259. ) from e
  260. def _samme_proba(estimator, n_classes, X):
  261. """Calculate algorithm 4, step 2, equation c) of Zhu et al [1].
  262. References
  263. ----------
  264. .. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009.
  265. """
  266. proba = estimator.predict_proba(X)
  267. # Displace zero probabilities so the log is defined.
  268. # Also fix negative elements which may occur with
  269. # negative sample weights.
  270. np.clip(proba, np.finfo(proba.dtype).eps, None, out=proba)
  271. log_proba = np.log(proba)
  272. return (n_classes - 1) * (
  273. log_proba - (1.0 / n_classes) * log_proba.sum(axis=1)[:, np.newaxis]
  274. )
  275. class AdaBoostClassifier(ClassifierMixin, BaseWeightBoosting):
  276. """An AdaBoost classifier.
  277. An AdaBoost [1] classifier is a meta-estimator that begins by fitting a
  278. classifier on the original dataset and then fits additional copies of the
  279. classifier on the same dataset but where the weights of incorrectly
  280. classified instances are adjusted such that subsequent classifiers focus
  281. more on difficult cases.
  282. This class implements the algorithm known as AdaBoost-SAMME [2].
  283. Read more in the :ref:`User Guide <adaboost>`.
  284. .. versionadded:: 0.14
  285. Parameters
  286. ----------
  287. estimator : object, default=None
  288. The base estimator from which the boosted ensemble is built.
  289. Support for sample weighting is required, as well as proper
  290. ``classes_`` and ``n_classes_`` attributes. If ``None``, then
  291. the base estimator is :class:`~sklearn.tree.DecisionTreeClassifier`
  292. initialized with `max_depth=1`.
  293. .. versionadded:: 1.2
  294. `base_estimator` was renamed to `estimator`.
  295. n_estimators : int, default=50
  296. The maximum number of estimators at which boosting is terminated.
  297. In case of perfect fit, the learning procedure is stopped early.
  298. Values must be in the range `[1, inf)`.
  299. learning_rate : float, default=1.0
  300. Weight applied to each classifier at each boosting iteration. A higher
  301. learning rate increases the contribution of each classifier. There is
  302. a trade-off between the `learning_rate` and `n_estimators` parameters.
  303. Values must be in the range `(0.0, inf)`.
  304. algorithm : {'SAMME', 'SAMME.R'}, default='SAMME.R'
  305. If 'SAMME.R' then use the SAMME.R real boosting algorithm.
  306. ``estimator`` must support calculation of class probabilities.
  307. If 'SAMME' then use the SAMME discrete boosting algorithm.
  308. The SAMME.R algorithm typically converges faster than SAMME,
  309. achieving a lower test error with fewer boosting iterations.
  310. random_state : int, RandomState instance or None, default=None
  311. Controls the random seed given at each `estimator` at each
  312. boosting iteration.
  313. Thus, it is only used when `estimator` exposes a `random_state`.
  314. Pass an int for reproducible output across multiple function calls.
  315. See :term:`Glossary <random_state>`.
  316. base_estimator : object, default=None
  317. The base estimator from which the boosted ensemble is built.
  318. Support for sample weighting is required, as well as proper
  319. ``classes_`` and ``n_classes_`` attributes. If ``None``, then
  320. the base estimator is :class:`~sklearn.tree.DecisionTreeClassifier`
  321. initialized with `max_depth=1`.
  322. .. deprecated:: 1.2
  323. `base_estimator` is deprecated and will be removed in 1.4.
  324. Use `estimator` instead.
  325. Attributes
  326. ----------
  327. estimator_ : estimator
  328. The base estimator from which the ensemble is grown.
  329. .. versionadded:: 1.2
  330. `base_estimator_` was renamed to `estimator_`.
  331. base_estimator_ : estimator
  332. The base estimator from which the ensemble is grown.
  333. .. deprecated:: 1.2
  334. `base_estimator_` is deprecated and will be removed in 1.4.
  335. Use `estimator_` instead.
  336. estimators_ : list of classifiers
  337. The collection of fitted sub-estimators.
  338. classes_ : ndarray of shape (n_classes,)
  339. The classes labels.
  340. n_classes_ : int
  341. The number of classes.
  342. estimator_weights_ : ndarray of floats
  343. Weights for each estimator in the boosted ensemble.
  344. estimator_errors_ : ndarray of floats
  345. Classification error for each estimator in the boosted
  346. ensemble.
  347. feature_importances_ : ndarray of shape (n_features,)
  348. The impurity-based feature importances if supported by the
  349. ``estimator`` (when based on decision trees).
  350. Warning: impurity-based feature importances can be misleading for
  351. high cardinality features (many unique values). See
  352. :func:`sklearn.inspection.permutation_importance` as an alternative.
  353. n_features_in_ : int
  354. Number of features seen during :term:`fit`.
  355. .. versionadded:: 0.24
  356. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  357. Names of features seen during :term:`fit`. Defined only when `X`
  358. has feature names that are all strings.
  359. .. versionadded:: 1.0
  360. See Also
  361. --------
  362. AdaBoostRegressor : An AdaBoost regressor that begins by fitting a
  363. regressor on the original dataset and then fits additional copies of
  364. the regressor on the same dataset but where the weights of instances
  365. are adjusted according to the error of the current prediction.
  366. GradientBoostingClassifier : GB builds an additive model in a forward
  367. stage-wise fashion. Regression trees are fit on the negative gradient
  368. of the binomial or multinomial deviance loss function. Binary
  369. classification is a special case where only a single regression tree is
  370. induced.
  371. sklearn.tree.DecisionTreeClassifier : A non-parametric supervised learning
  372. method used for classification.
  373. Creates a model that predicts the value of a target variable by
  374. learning simple decision rules inferred from the data features.
  375. References
  376. ----------
  377. .. [1] Y. Freund, R. Schapire, "A Decision-Theoretic Generalization of
  378. on-Line Learning and an Application to Boosting", 1995.
  379. .. [2] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009.
  380. Examples
  381. --------
  382. >>> from sklearn.ensemble import AdaBoostClassifier
  383. >>> from sklearn.datasets import make_classification
  384. >>> X, y = make_classification(n_samples=1000, n_features=4,
  385. ... n_informative=2, n_redundant=0,
  386. ... random_state=0, shuffle=False)
  387. >>> clf = AdaBoostClassifier(n_estimators=100, random_state=0)
  388. >>> clf.fit(X, y)
  389. AdaBoostClassifier(n_estimators=100, random_state=0)
  390. >>> clf.predict([[0, 0, 0, 0]])
  391. array([1])
  392. >>> clf.score(X, y)
  393. 0.983...
  394. """
  395. _parameter_constraints: dict = {
  396. **BaseWeightBoosting._parameter_constraints,
  397. "algorithm": [StrOptions({"SAMME", "SAMME.R"})],
  398. }
  399. def __init__(
  400. self,
  401. estimator=None,
  402. *,
  403. n_estimators=50,
  404. learning_rate=1.0,
  405. algorithm="SAMME.R",
  406. random_state=None,
  407. base_estimator="deprecated",
  408. ):
  409. super().__init__(
  410. estimator=estimator,
  411. n_estimators=n_estimators,
  412. learning_rate=learning_rate,
  413. random_state=random_state,
  414. base_estimator=base_estimator,
  415. )
  416. self.algorithm = algorithm
  417. def _validate_estimator(self):
  418. """Check the estimator and set the estimator_ attribute."""
  419. super()._validate_estimator(default=DecisionTreeClassifier(max_depth=1))
  420. # SAMME-R requires predict_proba-enabled base estimators
  421. if self.algorithm == "SAMME.R":
  422. if not hasattr(self.estimator_, "predict_proba"):
  423. raise TypeError(
  424. "AdaBoostClassifier with algorithm='SAMME.R' requires "
  425. "that the weak learner supports the calculation of class "
  426. "probabilities with a predict_proba method.\n"
  427. "Please change the base estimator or set "
  428. "algorithm='SAMME' instead."
  429. )
  430. if not has_fit_parameter(self.estimator_, "sample_weight"):
  431. raise ValueError(
  432. f"{self.estimator.__class__.__name__} doesn't support sample_weight."
  433. )
  434. def _boost(self, iboost, X, y, sample_weight, random_state):
  435. """Implement a single boost.
  436. Perform a single boost according to the real multi-class SAMME.R
  437. algorithm or to the discrete SAMME algorithm and return the updated
  438. sample weights.
  439. Parameters
  440. ----------
  441. iboost : int
  442. The index of the current boost iteration.
  443. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  444. The training input samples.
  445. y : array-like of shape (n_samples,)
  446. The target values (class labels).
  447. sample_weight : array-like of shape (n_samples,)
  448. The current sample weights.
  449. random_state : RandomState instance
  450. The RandomState instance used if the base estimator accepts a
  451. `random_state` attribute.
  452. Returns
  453. -------
  454. sample_weight : array-like of shape (n_samples,) or None
  455. The reweighted sample weights.
  456. If None then boosting has terminated early.
  457. estimator_weight : float
  458. The weight for the current boost.
  459. If None then boosting has terminated early.
  460. estimator_error : float
  461. The classification error for the current boost.
  462. If None then boosting has terminated early.
  463. """
  464. if self.algorithm == "SAMME.R":
  465. return self._boost_real(iboost, X, y, sample_weight, random_state)
  466. else: # elif self.algorithm == "SAMME":
  467. return self._boost_discrete(iboost, X, y, sample_weight, random_state)
  468. def _boost_real(self, iboost, X, y, sample_weight, random_state):
  469. """Implement a single boost using the SAMME.R real algorithm."""
  470. estimator = self._make_estimator(random_state=random_state)
  471. estimator.fit(X, y, sample_weight=sample_weight)
  472. y_predict_proba = estimator.predict_proba(X)
  473. if iboost == 0:
  474. self.classes_ = getattr(estimator, "classes_", None)
  475. self.n_classes_ = len(self.classes_)
  476. y_predict = self.classes_.take(np.argmax(y_predict_proba, axis=1), axis=0)
  477. # Instances incorrectly classified
  478. incorrect = y_predict != y
  479. # Error fraction
  480. estimator_error = np.mean(np.average(incorrect, weights=sample_weight, axis=0))
  481. # Stop if classification is perfect
  482. if estimator_error <= 0:
  483. return sample_weight, 1.0, 0.0
  484. # Construct y coding as described in Zhu et al [2]:
  485. #
  486. # y_k = 1 if c == k else -1 / (K - 1)
  487. #
  488. # where K == n_classes_ and c, k in [0, K) are indices along the second
  489. # axis of the y coding with c being the index corresponding to the true
  490. # class label.
  491. n_classes = self.n_classes_
  492. classes = self.classes_
  493. y_codes = np.array([-1.0 / (n_classes - 1), 1.0])
  494. y_coding = y_codes.take(classes == y[:, np.newaxis])
  495. # Displace zero probabilities so the log is defined.
  496. # Also fix negative elements which may occur with
  497. # negative sample weights.
  498. proba = y_predict_proba # alias for readability
  499. np.clip(proba, np.finfo(proba.dtype).eps, None, out=proba)
  500. # Boost weight using multi-class AdaBoost SAMME.R alg
  501. estimator_weight = (
  502. -1.0
  503. * self.learning_rate
  504. * ((n_classes - 1.0) / n_classes)
  505. * xlogy(y_coding, y_predict_proba).sum(axis=1)
  506. )
  507. # Only boost the weights if it will fit again
  508. if not iboost == self.n_estimators - 1:
  509. # Only boost positive weights
  510. sample_weight *= np.exp(
  511. estimator_weight * ((sample_weight > 0) | (estimator_weight < 0))
  512. )
  513. return sample_weight, 1.0, estimator_error
  514. def _boost_discrete(self, iboost, X, y, sample_weight, random_state):
  515. """Implement a single boost using the SAMME discrete algorithm."""
  516. estimator = self._make_estimator(random_state=random_state)
  517. estimator.fit(X, y, sample_weight=sample_weight)
  518. y_predict = estimator.predict(X)
  519. if iboost == 0:
  520. self.classes_ = getattr(estimator, "classes_", None)
  521. self.n_classes_ = len(self.classes_)
  522. # Instances incorrectly classified
  523. incorrect = y_predict != y
  524. # Error fraction
  525. estimator_error = np.mean(np.average(incorrect, weights=sample_weight, axis=0))
  526. # Stop if classification is perfect
  527. if estimator_error <= 0:
  528. return sample_weight, 1.0, 0.0
  529. n_classes = self.n_classes_
  530. # Stop if the error is at least as bad as random guessing
  531. if estimator_error >= 1.0 - (1.0 / n_classes):
  532. self.estimators_.pop(-1)
  533. if len(self.estimators_) == 0:
  534. raise ValueError(
  535. "BaseClassifier in AdaBoostClassifier "
  536. "ensemble is worse than random, ensemble "
  537. "can not be fit."
  538. )
  539. return None, None, None
  540. # Boost weight using multi-class AdaBoost SAMME alg
  541. estimator_weight = self.learning_rate * (
  542. np.log((1.0 - estimator_error) / estimator_error) + np.log(n_classes - 1.0)
  543. )
  544. # Only boost the weights if it will fit again
  545. if not iboost == self.n_estimators - 1:
  546. # Only boost positive weights
  547. sample_weight = np.exp(
  548. np.log(sample_weight)
  549. + estimator_weight * incorrect * (sample_weight > 0)
  550. )
  551. return sample_weight, estimator_weight, estimator_error
  552. def predict(self, X):
  553. """Predict classes for X.
  554. The predicted class of an input sample is computed as the weighted mean
  555. prediction of the classifiers in the ensemble.
  556. Parameters
  557. ----------
  558. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  559. The training input samples. Sparse matrix can be CSC, CSR, COO,
  560. DOK, or LIL. COO, DOK, and LIL are converted to CSR.
  561. Returns
  562. -------
  563. y : ndarray of shape (n_samples,)
  564. The predicted classes.
  565. """
  566. pred = self.decision_function(X)
  567. if self.n_classes_ == 2:
  568. return self.classes_.take(pred > 0, axis=0)
  569. return self.classes_.take(np.argmax(pred, axis=1), axis=0)
  570. def staged_predict(self, X):
  571. """Return staged predictions for X.
  572. The predicted class of an input sample is computed as the weighted mean
  573. prediction of the classifiers in the ensemble.
  574. This generator method yields the ensemble prediction after each
  575. iteration of boosting and therefore allows monitoring, such as to
  576. determine the prediction on a test set after each boost.
  577. Parameters
  578. ----------
  579. X : array-like of shape (n_samples, n_features)
  580. The input samples. Sparse matrix can be CSC, CSR, COO,
  581. DOK, or LIL. COO, DOK, and LIL are converted to CSR.
  582. Yields
  583. ------
  584. y : generator of ndarray of shape (n_samples,)
  585. The predicted classes.
  586. """
  587. X = self._check_X(X)
  588. n_classes = self.n_classes_
  589. classes = self.classes_
  590. if n_classes == 2:
  591. for pred in self.staged_decision_function(X):
  592. yield np.array(classes.take(pred > 0, axis=0))
  593. else:
  594. for pred in self.staged_decision_function(X):
  595. yield np.array(classes.take(np.argmax(pred, axis=1), axis=0))
  596. def decision_function(self, X):
  597. """Compute the decision function of ``X``.
  598. Parameters
  599. ----------
  600. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  601. The training input samples. Sparse matrix can be CSC, CSR, COO,
  602. DOK, or LIL. COO, DOK, and LIL are converted to CSR.
  603. Returns
  604. -------
  605. score : ndarray of shape of (n_samples, k)
  606. The decision function of the input samples. The order of
  607. outputs is the same as that of the :term:`classes_` attribute.
  608. Binary classification is a special cases with ``k == 1``,
  609. otherwise ``k==n_classes``. For binary classification,
  610. values closer to -1 or 1 mean more like the first or second
  611. class in ``classes_``, respectively.
  612. """
  613. check_is_fitted(self)
  614. X = self._check_X(X)
  615. n_classes = self.n_classes_
  616. classes = self.classes_[:, np.newaxis]
  617. if self.algorithm == "SAMME.R":
  618. # The weights are all 1. for SAMME.R
  619. pred = sum(
  620. _samme_proba(estimator, n_classes, X) for estimator in self.estimators_
  621. )
  622. else: # self.algorithm == "SAMME"
  623. pred = sum(
  624. np.where(
  625. (estimator.predict(X) == classes).T,
  626. w,
  627. -1 / (n_classes - 1) * w,
  628. )
  629. for estimator, w in zip(self.estimators_, self.estimator_weights_)
  630. )
  631. pred /= self.estimator_weights_.sum()
  632. if n_classes == 2:
  633. pred[:, 0] *= -1
  634. return pred.sum(axis=1)
  635. return pred
  636. def staged_decision_function(self, X):
  637. """Compute decision function of ``X`` for each boosting iteration.
  638. This method allows monitoring (i.e. determine error on testing set)
  639. after each boosting iteration.
  640. Parameters
  641. ----------
  642. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  643. The training input samples. Sparse matrix can be CSC, CSR, COO,
  644. DOK, or LIL. COO, DOK, and LIL are converted to CSR.
  645. Yields
  646. ------
  647. score : generator of ndarray of shape (n_samples, k)
  648. The decision function of the input samples. The order of
  649. outputs is the same of that of the :term:`classes_` attribute.
  650. Binary classification is a special cases with ``k == 1``,
  651. otherwise ``k==n_classes``. For binary classification,
  652. values closer to -1 or 1 mean more like the first or second
  653. class in ``classes_``, respectively.
  654. """
  655. check_is_fitted(self)
  656. X = self._check_X(X)
  657. n_classes = self.n_classes_
  658. classes = self.classes_[:, np.newaxis]
  659. pred = None
  660. norm = 0.0
  661. for weight, estimator in zip(self.estimator_weights_, self.estimators_):
  662. norm += weight
  663. if self.algorithm == "SAMME.R":
  664. # The weights are all 1. for SAMME.R
  665. current_pred = _samme_proba(estimator, n_classes, X)
  666. else: # elif self.algorithm == "SAMME":
  667. current_pred = np.where(
  668. (estimator.predict(X) == classes).T,
  669. weight,
  670. -1 / (n_classes - 1) * weight,
  671. )
  672. if pred is None:
  673. pred = current_pred
  674. else:
  675. pred += current_pred
  676. if n_classes == 2:
  677. tmp_pred = np.copy(pred)
  678. tmp_pred[:, 0] *= -1
  679. yield (tmp_pred / norm).sum(axis=1)
  680. else:
  681. yield pred / norm
  682. @staticmethod
  683. def _compute_proba_from_decision(decision, n_classes):
  684. """Compute probabilities from the decision function.
  685. This is based eq. (4) of [1] where:
  686. p(y=c|X) = exp((1 / K-1) f_c(X)) / sum_k(exp((1 / K-1) f_k(X)))
  687. = softmax((1 / K-1) * f(X))
  688. References
  689. ----------
  690. .. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost",
  691. 2009.
  692. """
  693. if n_classes == 2:
  694. decision = np.vstack([-decision, decision]).T / 2
  695. else:
  696. decision /= n_classes - 1
  697. return softmax(decision, copy=False)
  698. def predict_proba(self, X):
  699. """Predict class probabilities for X.
  700. The predicted class probabilities of an input sample is computed as
  701. the weighted mean predicted class probabilities of the classifiers
  702. in the ensemble.
  703. Parameters
  704. ----------
  705. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  706. The training input samples. Sparse matrix can be CSC, CSR, COO,
  707. DOK, or LIL. COO, DOK, and LIL are converted to CSR.
  708. Returns
  709. -------
  710. p : ndarray of shape (n_samples, n_classes)
  711. The class probabilities of the input samples. The order of
  712. outputs is the same of that of the :term:`classes_` attribute.
  713. """
  714. check_is_fitted(self)
  715. n_classes = self.n_classes_
  716. if n_classes == 1:
  717. return np.ones((_num_samples(X), 1))
  718. decision = self.decision_function(X)
  719. return self._compute_proba_from_decision(decision, n_classes)
  720. def staged_predict_proba(self, X):
  721. """Predict class probabilities for X.
  722. The predicted class probabilities of an input sample is computed as
  723. the weighted mean predicted class probabilities of the classifiers
  724. in the ensemble.
  725. This generator method yields the ensemble predicted class probabilities
  726. after each iteration of boosting and therefore allows monitoring, such
  727. as to determine the predicted class probabilities on a test set after
  728. each boost.
  729. Parameters
  730. ----------
  731. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  732. The training input samples. Sparse matrix can be CSC, CSR, COO,
  733. DOK, or LIL. COO, DOK, and LIL are converted to CSR.
  734. Yields
  735. ------
  736. p : generator of ndarray of shape (n_samples,)
  737. The class probabilities of the input samples. The order of
  738. outputs is the same of that of the :term:`classes_` attribute.
  739. """
  740. n_classes = self.n_classes_
  741. for decision in self.staged_decision_function(X):
  742. yield self._compute_proba_from_decision(decision, n_classes)
  743. def predict_log_proba(self, X):
  744. """Predict class log-probabilities for X.
  745. The predicted class log-probabilities of an input sample is computed as
  746. the weighted mean predicted class log-probabilities of the classifiers
  747. in the ensemble.
  748. Parameters
  749. ----------
  750. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  751. The training input samples. Sparse matrix can be CSC, CSR, COO,
  752. DOK, or LIL. COO, DOK, and LIL are converted to CSR.
  753. Returns
  754. -------
  755. p : ndarray of shape (n_samples, n_classes)
  756. The class probabilities of the input samples. The order of
  757. outputs is the same of that of the :term:`classes_` attribute.
  758. """
  759. return np.log(self.predict_proba(X))
  760. class AdaBoostRegressor(RegressorMixin, BaseWeightBoosting):
  761. """An AdaBoost regressor.
  762. An AdaBoost [1] regressor is a meta-estimator that begins by fitting a
  763. regressor on the original dataset and then fits additional copies of the
  764. regressor on the same dataset but where the weights of instances are
  765. adjusted according to the error of the current prediction. As such,
  766. subsequent regressors focus more on difficult cases.
  767. This class implements the algorithm known as AdaBoost.R2 [2].
  768. Read more in the :ref:`User Guide <adaboost>`.
  769. .. versionadded:: 0.14
  770. Parameters
  771. ----------
  772. estimator : object, default=None
  773. The base estimator from which the boosted ensemble is built.
  774. If ``None``, then the base estimator is
  775. :class:`~sklearn.tree.DecisionTreeRegressor` initialized with
  776. `max_depth=3`.
  777. .. versionadded:: 1.2
  778. `base_estimator` was renamed to `estimator`.
  779. n_estimators : int, default=50
  780. The maximum number of estimators at which boosting is terminated.
  781. In case of perfect fit, the learning procedure is stopped early.
  782. Values must be in the range `[1, inf)`.
  783. learning_rate : float, default=1.0
  784. Weight applied to each regressor at each boosting iteration. A higher
  785. learning rate increases the contribution of each regressor. There is
  786. a trade-off between the `learning_rate` and `n_estimators` parameters.
  787. Values must be in the range `(0.0, inf)`.
  788. loss : {'linear', 'square', 'exponential'}, default='linear'
  789. The loss function to use when updating the weights after each
  790. boosting iteration.
  791. random_state : int, RandomState instance or None, default=None
  792. Controls the random seed given at each `estimator` at each
  793. boosting iteration.
  794. Thus, it is only used when `estimator` exposes a `random_state`.
  795. In addition, it controls the bootstrap of the weights used to train the
  796. `estimator` at each boosting iteration.
  797. Pass an int for reproducible output across multiple function calls.
  798. See :term:`Glossary <random_state>`.
  799. base_estimator : object, default=None
  800. The base estimator from which the boosted ensemble is built.
  801. If ``None``, then the base estimator is
  802. :class:`~sklearn.tree.DecisionTreeRegressor` initialized with
  803. `max_depth=3`.
  804. .. deprecated:: 1.2
  805. `base_estimator` is deprecated and will be removed in 1.4.
  806. Use `estimator` instead.
  807. Attributes
  808. ----------
  809. estimator_ : estimator
  810. The base estimator from which the ensemble is grown.
  811. .. versionadded:: 1.2
  812. `base_estimator_` was renamed to `estimator_`.
  813. base_estimator_ : estimator
  814. The base estimator from which the ensemble is grown.
  815. .. deprecated:: 1.2
  816. `base_estimator_` is deprecated and will be removed in 1.4.
  817. Use `estimator_` instead.
  818. estimators_ : list of regressors
  819. The collection of fitted sub-estimators.
  820. estimator_weights_ : ndarray of floats
  821. Weights for each estimator in the boosted ensemble.
  822. estimator_errors_ : ndarray of floats
  823. Regression error for each estimator in the boosted ensemble.
  824. feature_importances_ : ndarray of shape (n_features,)
  825. The impurity-based feature importances if supported by the
  826. ``estimator`` (when based on decision trees).
  827. Warning: impurity-based feature importances can be misleading for
  828. high cardinality features (many unique values). See
  829. :func:`sklearn.inspection.permutation_importance` as an alternative.
  830. n_features_in_ : int
  831. Number of features seen during :term:`fit`.
  832. .. versionadded:: 0.24
  833. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  834. Names of features seen during :term:`fit`. Defined only when `X`
  835. has feature names that are all strings.
  836. .. versionadded:: 1.0
  837. See Also
  838. --------
  839. AdaBoostClassifier : An AdaBoost classifier.
  840. GradientBoostingRegressor : Gradient Boosting Classification Tree.
  841. sklearn.tree.DecisionTreeRegressor : A decision tree regressor.
  842. References
  843. ----------
  844. .. [1] Y. Freund, R. Schapire, "A Decision-Theoretic Generalization of
  845. on-Line Learning and an Application to Boosting", 1995.
  846. .. [2] H. Drucker, "Improving Regressors using Boosting Techniques", 1997.
  847. Examples
  848. --------
  849. >>> from sklearn.ensemble import AdaBoostRegressor
  850. >>> from sklearn.datasets import make_regression
  851. >>> X, y = make_regression(n_features=4, n_informative=2,
  852. ... random_state=0, shuffle=False)
  853. >>> regr = AdaBoostRegressor(random_state=0, n_estimators=100)
  854. >>> regr.fit(X, y)
  855. AdaBoostRegressor(n_estimators=100, random_state=0)
  856. >>> regr.predict([[0, 0, 0, 0]])
  857. array([4.7972...])
  858. >>> regr.score(X, y)
  859. 0.9771...
  860. """
  861. _parameter_constraints: dict = {
  862. **BaseWeightBoosting._parameter_constraints,
  863. "loss": [StrOptions({"linear", "square", "exponential"})],
  864. }
  865. def __init__(
  866. self,
  867. estimator=None,
  868. *,
  869. n_estimators=50,
  870. learning_rate=1.0,
  871. loss="linear",
  872. random_state=None,
  873. base_estimator="deprecated",
  874. ):
  875. super().__init__(
  876. estimator=estimator,
  877. n_estimators=n_estimators,
  878. learning_rate=learning_rate,
  879. random_state=random_state,
  880. base_estimator=base_estimator,
  881. )
  882. self.loss = loss
  883. self.random_state = random_state
  884. def _validate_estimator(self):
  885. """Check the estimator and set the estimator_ attribute."""
  886. super()._validate_estimator(default=DecisionTreeRegressor(max_depth=3))
  887. def _boost(self, iboost, X, y, sample_weight, random_state):
  888. """Implement a single boost for regression
  889. Perform a single boost according to the AdaBoost.R2 algorithm and
  890. return the updated sample weights.
  891. Parameters
  892. ----------
  893. iboost : int
  894. The index of the current boost iteration.
  895. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  896. The training input samples.
  897. y : array-like of shape (n_samples,)
  898. The target values (class labels in classification, real numbers in
  899. regression).
  900. sample_weight : array-like of shape (n_samples,)
  901. The current sample weights.
  902. random_state : RandomState
  903. The RandomState instance used if the base estimator accepts a
  904. `random_state` attribute.
  905. Controls also the bootstrap of the weights used to train the weak
  906. learner.
  907. replacement.
  908. Returns
  909. -------
  910. sample_weight : array-like of shape (n_samples,) or None
  911. The reweighted sample weights.
  912. If None then boosting has terminated early.
  913. estimator_weight : float
  914. The weight for the current boost.
  915. If None then boosting has terminated early.
  916. estimator_error : float
  917. The regression error for the current boost.
  918. If None then boosting has terminated early.
  919. """
  920. estimator = self._make_estimator(random_state=random_state)
  921. # Weighted sampling of the training set with replacement
  922. bootstrap_idx = random_state.choice(
  923. np.arange(_num_samples(X)),
  924. size=_num_samples(X),
  925. replace=True,
  926. p=sample_weight,
  927. )
  928. # Fit on the bootstrapped sample and obtain a prediction
  929. # for all samples in the training set
  930. X_ = _safe_indexing(X, bootstrap_idx)
  931. y_ = _safe_indexing(y, bootstrap_idx)
  932. estimator.fit(X_, y_)
  933. y_predict = estimator.predict(X)
  934. error_vect = np.abs(y_predict - y)
  935. sample_mask = sample_weight > 0
  936. masked_sample_weight = sample_weight[sample_mask]
  937. masked_error_vector = error_vect[sample_mask]
  938. error_max = masked_error_vector.max()
  939. if error_max != 0:
  940. masked_error_vector /= error_max
  941. if self.loss == "square":
  942. masked_error_vector **= 2
  943. elif self.loss == "exponential":
  944. masked_error_vector = 1.0 - np.exp(-masked_error_vector)
  945. # Calculate the average loss
  946. estimator_error = (masked_sample_weight * masked_error_vector).sum()
  947. if estimator_error <= 0:
  948. # Stop if fit is perfect
  949. return sample_weight, 1.0, 0.0
  950. elif estimator_error >= 0.5:
  951. # Discard current estimator only if it isn't the only one
  952. if len(self.estimators_) > 1:
  953. self.estimators_.pop(-1)
  954. return None, None, None
  955. beta = estimator_error / (1.0 - estimator_error)
  956. # Boost weight using AdaBoost.R2 alg
  957. estimator_weight = self.learning_rate * np.log(1.0 / beta)
  958. if not iboost == self.n_estimators - 1:
  959. sample_weight[sample_mask] *= np.power(
  960. beta, (1.0 - masked_error_vector) * self.learning_rate
  961. )
  962. return sample_weight, estimator_weight, estimator_error
  963. def _get_median_predict(self, X, limit):
  964. # Evaluate predictions of all estimators
  965. predictions = np.array([est.predict(X) for est in self.estimators_[:limit]]).T
  966. # Sort the predictions
  967. sorted_idx = np.argsort(predictions, axis=1)
  968. # Find index of median prediction for each sample
  969. weight_cdf = stable_cumsum(self.estimator_weights_[sorted_idx], axis=1)
  970. median_or_above = weight_cdf >= 0.5 * weight_cdf[:, -1][:, np.newaxis]
  971. median_idx = median_or_above.argmax(axis=1)
  972. median_estimators = sorted_idx[np.arange(_num_samples(X)), median_idx]
  973. # Return median predictions
  974. return predictions[np.arange(_num_samples(X)), median_estimators]
  975. def predict(self, X):
  976. """Predict regression value for X.
  977. The predicted regression value of an input sample is computed
  978. as the weighted median prediction of the regressors in the ensemble.
  979. Parameters
  980. ----------
  981. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  982. The training input samples. Sparse matrix can be CSC, CSR, COO,
  983. DOK, or LIL. COO, DOK, and LIL are converted to CSR.
  984. Returns
  985. -------
  986. y : ndarray of shape (n_samples,)
  987. The predicted regression values.
  988. """
  989. check_is_fitted(self)
  990. X = self._check_X(X)
  991. return self._get_median_predict(X, len(self.estimators_))
  992. def staged_predict(self, X):
  993. """Return staged predictions for X.
  994. The predicted regression value of an input sample is computed
  995. as the weighted median prediction of the regressors in the ensemble.
  996. This generator method yields the ensemble prediction after each
  997. iteration of boosting and therefore allows monitoring, such as to
  998. determine the prediction on a test set after each boost.
  999. Parameters
  1000. ----------
  1001. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  1002. The training input samples.
  1003. Yields
  1004. ------
  1005. y : generator of ndarray of shape (n_samples,)
  1006. The predicted regression values.
  1007. """
  1008. check_is_fitted(self)
  1009. X = self._check_X(X)
  1010. for i, _ in enumerate(self.estimators_, 1):
  1011. yield self._get_median_predict(X, limit=i)