
    -i                     :   S r SSKrSSKJrJr  SSKJrJr  SSKr	SSK
JrJrJrJrJr  SSKJrJr  SSKJrJr  SS	KJrJr  SS
KJrJrJrJr  SSKJrJ r   SSK!J"r"J#r#  SSK$J%r%J&r&J'r'J(r(J)r)  SSK*J+r+  SS/r, " S S\+\S9r-S r. " S S\#\\-5      r/ " S S\#\\-5      r0g)a\  Weight Boosting.

This module contains weight boosting estimators for both classification and
regression.

The module structure is the following:

- The `BaseWeightBoosting` base class implements a common ``fit`` method
  for all the estimators in the module. Regression and classification
  only differ from each other in the loss function that is optimized.

- :class:`~sklearn.ensemble.AdaBoostClassifier` implements adaptive boosting
  (AdaBoost-SAMME) for classification problems.

- :class:`~sklearn.ensemble.AdaBoostRegressor` implements adaptive boosting
  (AdaBoost.R2) for regression problems.
    N)ABCMetaabstractmethod)IntegralReal   )ClassifierMixinRegressorMixin_fit_contextis_classifieris_regressor)accuracy_scorer2_score)DecisionTreeClassifierDecisionTreeRegressor)_safe_indexingcheck_random_state)
HasMethodsHiddenInterval
StrOptions)softmaxstable_cumsum)_raise_for_unsupported_routing_RoutingNotSupportedMixin)_check_sample_weight_num_samplescheck_is_fittedhas_fit_parametervalidate_data   )BaseEnsembleAdaBoostClassifierAdaBoostRegressorc            	          ^  \ rS rSr% Sr\" SS/5      S/\" \SSSS9/\" \S	SS
S9/S/S.r	\
\S'   \ SS\" 5       SSS.U 4S jjj5       rS r\" SS9SS j5       r\S 5       rSS jr\S 5       rU 4S jrSrU =r$ )BaseWeightBoosting;   zsBase class for AdaBoost estimators.

Warning: This class should not be used directly. Use derived classes
instead.
fitpredictNr    left)closedr   neitherrandom_state	estimatorn_estimatorslearning_rater,   _parameter_constraints2         ?)r/   estimator_paramsr0   r,   c                <   > [         TU ]  UUUS9  X@l        XPl        g )N)r.   r/   r4   )super__init__r0   r,   )selfr.   r/   r4   r0   r,   	__class__s         T/var/www/html/venv/lib/python3.13/site-packages/sklearn/ensemble/_weight_boosting.pyr7   BaseWeightBoosting.__init__I   s.     	%- 	 	
 +(    c           
      $    [        U USS/SSS SS9$ )NcsrcscTF)accept_sparse	ensure_2dallow_nddtypereset)r   r8   Xs     r:   _check_XBaseWeightBoosting._check_X\   s(     %.
 	
r<   F)prefer_skip_nested_validationc                    [        U SUS9  [        U UUSS/SSS[        U 5      S9u  p[        X1[        R
                  SSS9nX3R                  5       -  nU R                  5         / U l        [        R                  " U R                  [        R
                  S	9U l        [        R                  " U R                  [        R
                  S	9U l        [        U R                  5      n[        R                   " UR"                  5      R$                  nUS
:H  n['        U R                  5       H  n[        R(                  " X5SS9nS
X6'   U R+                  XqX#U5      u  p8n	Uc    U $ XR                  U'   XR                  U'   U	S:X  a    U $ [        R                  " U5      n
[        R,                  " U
5      (       d  [.        R0                  " SU S3SS9    U $ U
S::  a    U $ XpR                  S-
  :  d  M  X:-  nM     U $ )a   Build a boosted classifier/regressor from the training set (X, y).

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrix can be CSC, CSR, COO,
    DOK, or LIL. COO, DOK, and LIL are converted to CSR.

y : array-like of shape (n_samples,)
    The target values.

sample_weight : array-like of shape (n_samples,), default=None
    Sample weights. If None, the sample weights are initialized to
    1 / n_samples.

Returns
-------
self : object
    Fitted estimator.
r'   sample_weightr>   r?   TN)r@   rA   rB   rC   	y_numeric)rC   copyensure_non_negative)rC           )a_mina_maxr   z:Sample weights have reached infinite values, at iteration zG, causing overflow. Iterations stopped. Try lowering the learning rate.r   )
stacklevelr    )r   r   r   r   npfloat64sum_validate_estimatorestimators_zerosr/   estimator_weights_onesestimator_errors_r   r,   finforC   epsrangeclip_boostisfinitewarningswarn)r8   rF   yrL   r,   epsilonzero_weight_maskiboostestimator_weightestimator_errorsample_weight_sums              r:   r'   BaseWeightBoosting.fith   s   2 	'tU-P %."4(	
 -BJJTt
 	**,, 	  " "$((4+<+<BJJ"O!#):):"**!M *$*;*;<((=../33(C/D--.FGGMMM.1M+ @D{{1\@<M_
 $: 9 /?##F+-<""6* !#. + !#} 5;;011))/ 1NN  !   !A% 	 ))A--2Q /T r<   c                     g)a  Implement a single boost.

Warning: This method needs to be overridden by subclasses.

Parameters
----------
iboost : int
    The index of the current boost iteration.

X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrix can be CSC, CSR, COO,
    DOK, or LIL. COO, DOK, and LIL are converted to CSR.

y : array-like of shape (n_samples,)
    The target values (class labels).

sample_weight : array-like of shape (n_samples,)
    The current sample weights.

random_state : RandomState
    The current random number generator

Returns
-------
sample_weight : array-like of shape (n_samples,) or None
    The reweighted sample weights.
    If None then boosting has terminated early.

estimator_weight : float
    The weight for the current boost.
    If None then boosting has terminated early.

error : float
    The classification error for the current boost.
    If None then boosting has terminated early.
N )r8   rh   rF   re   rL   r,   s         r:   ra   BaseWeightBoosting._boost   s    L 	r<   c              #      #    U R                  U5      nU R                  U5       H-  n[        U 5      (       a  [        X$US9v   M!  [	        X$US9v   M/     g7f)aK  Return staged scores for X, y.

This generator method yields the ensemble score after each iteration of
boosting and therefore allows monitoring, such as to determine the
score on a test set after each boost.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrix can be CSC, CSR, COO,
    DOK, or LIL. COO, DOK, and LIL are converted to CSR.

y : array-like of shape (n_samples,)
    Labels for X.

sample_weight : array-like of shape (n_samples,), default=None
    Sample weights.

Yields
------
z : float
rK   N)rG   staged_predictr   r   r   )r8   rF   re   rL   y_preds        r:   staged_scoreBaseWeightBoosting.staged_score   sO     . MM!))!,FT""$QmLLqFF	 -s   AAc                 <   U R                   b  [        U R                   5      S:X  a  [        S5      e U R                  R	                  5       n[	        S [        U R                  U R                   5       5       5      U-  $ ! [         a  n[        S5      UeSnAff = f)a  The impurity-based feature importances.

The higher, the more important the feature.
The importance of a feature is computed as the (normalized)
total reduction of the criterion brought by that feature.  It is also
known as the Gini importance.

Warning: impurity-based feature importances can be misleading for
high cardinality features (many unique values). See
:func:`sklearn.inspection.permutation_importance` as an alternative.

Returns
-------
feature_importances_ : ndarray of shape (n_features,)
    The feature importances.
Nr   z?Estimator not fitted, call `fit` before `feature_importances_`.c              3   B   #    U  H  u  pXR                   -  v   M     g 7fN)feature_importances_).0weightclfs      r:   	<genexpr>:BaseWeightBoosting.feature_importances_.<locals>.<genexpr>-  s"      'U 555'Us   zdUnable to compute feature importances since estimator does not have a feature_importances_ attribute)rX   len
ValueErrorrZ   rV   zipAttributeError)r8   normes      r:   rx   'BaseWeightBoosting.feature_importances_  s    $ #s4+;+;'<'AQ 	**..0D '*4+B+BDDTDT'U  	  	 1 		s   AB   
B
BBc                 F   > [         TU ]  5       nSUR                  l        U$ )NT)r6   __sklearn_tags__
input_tagssparse)r8   tagsr9   s     r:   r   #BaseWeightBoosting.__sklearn_tags__;  s!    w')!%r<   )r\   rZ   rX   r0   r,   rw   )__name__
__module____qualname____firstlineno____doc__r   r   r   r   r1   dict__annotations__r   tupler7   rG   r
   r'   ra   rs   propertyrx   r   __static_attributes____classcell__r9   s   @r:   r%   r%   ;   s     !%!34d;!(AtFCD"4DCD'(	$D   ) ) ) )$

 &+^	^@ % %NG> % %N r<   r%   )	metaclassc                 4   U R                  U5      n[        R                  " U[        R                  " UR                  5      R
                  SUS9  [        R                  " U5      nUS-
  USU-  UR                  SS9SS2[        R                  4   -  -
  -  $ )zCalculate algorithm 4, step 2, equation c) of Zhu et al [1].

References
----------
.. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009.

N)outr    r3   axis)	predict_probarT   r`   r]   rC   r^   logrV   newaxis)r.   	n_classesrF   proba	log_probas        r:   _samme_probar   A  s     ##A&E
 GGE288EKK(,,d>uIMS9_	1(=am(LLL r<   c                      ^  \ rS rSr% Sr0 \R                  ES\" S15      \" \" S15      5      /0Er\	\
S'    SSS	SSS
.U 4S jjjrU 4S jrS rS rS rS rS r\S 5       rS rS rS rSrU =r$ )r"   iV  a  An AdaBoost classifier.

An AdaBoost [1]_ classifier is a meta-estimator that begins by fitting a
classifier on the original dataset and then fits additional copies of the
classifier on the same dataset but where the weights of incorrectly
classified instances are adjusted such that subsequent classifiers focus
more on difficult cases.

This class implements the algorithm based on [2]_.

Read more in the :ref:`User Guide <adaboost>`.

.. versionadded:: 0.14

Parameters
----------
estimator : object, default=None
    The base estimator from which the boosted ensemble is built.
    Support for sample weighting is required, as well as proper
    ``classes_`` and ``n_classes_`` attributes. If ``None``, then
    the base estimator is :class:`~sklearn.tree.DecisionTreeClassifier`
    initialized with `max_depth=1`.

    .. versionadded:: 1.2
       `base_estimator` was renamed to `estimator`.

n_estimators : int, default=50
    The maximum number of estimators at which boosting is terminated.
    In case of perfect fit, the learning procedure is stopped early.
    Values must be in the range `[1, inf)`.

learning_rate : float, default=1.0
    Weight applied to each classifier at each boosting iteration. A higher
    learning rate increases the contribution of each classifier. There is
    a trade-off between the `learning_rate` and `n_estimators` parameters.
    Values must be in the range `(0.0, inf)`.

algorithm : {'SAMME'}, default='SAMME'
    Use the SAMME discrete boosting algorithm.

    .. deprecated:: 1.6
        `algorithm` is deprecated and will be removed in version 1.8. This
        estimator only implements the 'SAMME' algorithm.

random_state : int, RandomState instance or None, default=None
    Controls the random seed given at each `estimator` at each
    boosting iteration.
    Thus, it is only used when `estimator` exposes a `random_state`.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

Attributes
----------
estimator_ : estimator
    The base estimator from which the ensemble is grown.

    .. versionadded:: 1.2
       `base_estimator_` was renamed to `estimator_`.

estimators_ : list of classifiers
    The collection of fitted sub-estimators.

classes_ : ndarray of shape (n_classes,)
    The classes labels.

n_classes_ : int
    The number of classes.

estimator_weights_ : ndarray of floats
    Weights for each estimator in the boosted ensemble.

estimator_errors_ : ndarray of floats
    Classification error for each estimator in the boosted
    ensemble.

feature_importances_ : ndarray of shape (n_features,)
    The impurity-based feature importances if supported by the
    ``estimator`` (when based on decision trees).

    Warning: impurity-based feature importances can be misleading for
    high cardinality features (many unique values). See
    :func:`sklearn.inspection.permutation_importance` as an alternative.

n_features_in_ : int
    Number of features seen during :term:`fit`.

    .. versionadded:: 0.24

feature_names_in_ : ndarray of shape (`n_features_in_`,)
    Names of features seen during :term:`fit`. Defined only when `X`
    has feature names that are all strings.

    .. versionadded:: 1.0

See Also
--------
AdaBoostRegressor : An AdaBoost regressor that begins by fitting a
    regressor on the original dataset and then fits additional copies of
    the regressor on the same dataset but where the weights of instances
    are adjusted according to the error of the current prediction.

GradientBoostingClassifier : GB builds an additive model in a forward
    stage-wise fashion. Regression trees are fit on the negative gradient
    of the binomial or multinomial deviance loss function. Binary
    classification is a special case where only a single regression tree is
    induced.

sklearn.tree.DecisionTreeClassifier : A non-parametric supervised learning
    method used for classification.
    Creates a model that predicts the value of a target variable by
    learning simple decision rules inferred from the data features.

References
----------
.. [1] Y. Freund, R. Schapire, "A Decision-Theoretic Generalization of
       on-Line Learning and an Application to Boosting", 1995.

.. [2] :doi:`J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class adaboost."
       Statistics and its Interface 2.3 (2009): 349-360.
       <10.4310/SII.2009.v2.n3.a8>`

Examples
--------
>>> from sklearn.ensemble import AdaBoostClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=1000, n_features=4,
...                            n_informative=2, n_redundant=0,
...                            random_state=0, shuffle=False)
>>> clf = AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.fit(X, y)
AdaBoostClassifier(n_estimators=100, random_state=0)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
>>> clf.score(X, y)
0.96

For a detailed example of using AdaBoost to fit a sequence of DecisionTrees
as weaklearners, please refer to
:ref:`sphx_glr_auto_examples_ensemble_plot_adaboost_multiclass.py`.

For a detailed example of using AdaBoost to fit a non-linearly separable
classification dataset composed of two Gaussian quantiles clusters, please
refer to :ref:`sphx_glr_auto_examples_ensemble_plot_adaboost_twoclass.py`.
	algorithmSAMME
deprecatedr1   Nr2   r3   )r/   r0   r   r,   c                2   > [         TU ]  UUUUS9  X@l        g Nr-   )r6   r7   r   )r8   r.   r/   r0   r   r,   r9   s         r:   r7   AdaBoostClassifier.__init__  s*     	%'%	 	 	
 #r<   c                   > [         TU ]  [        SS9S9  U R                  S:w  a  [        R
                  " S[        5        [        U R                  S5      (       d,  [        U R                  R                  R                   S35      eg)	5Check the estimator and set the estimator_ attribute.r    	max_depthdefaultr   zdThe parameter 'algorithm' is deprecated in 1.6 and has no effect. It will be removed in version 1.8.rL   z doesn't support sample_weight.N)r6   rW   r   r   rc   rd   FutureWarningr   
estimator_r   r.   r9   r   r8   r9   s    r:   rW   &AdaBoostClassifier._validate_estimator  s{    #,BQ,O#P>>\)MM5 !/BB>>++4455TU  Cr<   c                    U R                  US9nUR                  X#US9  UR                  U5      nUS:X  a,  [        USS5      U l        [        U R                  5      U l        Xs:g  n[        R                  " [        R                  " XSS95      n	U	S::  a  USS4$ U R                  n
U	SSU
-  -
  :  a@  U R                  R                  S	5        [        U R                  5      S:X  a  [        S
5      egU R                  [        R                  " SU	-
  U	-  5      [        R                  " U
S-
  5      -   -  nXR                  S-
  :X  d5  [        R                   " [        R                  " U5      X-  US:  -  -   5      nXKU	4$ )a  Implement a single boost.

Perform a single boost according to the discrete SAMME algorithm and return the
updated sample weights.

Parameters
----------
iboost : int
    The index of the current boost iteration.

X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples.

y : array-like of shape (n_samples,)
    The target values (class labels).

sample_weight : array-like of shape (n_samples,)
    The current sample weights.

random_state : RandomState instance
    The RandomState instance used if the base estimator accepts a
    `random_state` attribute.

Returns
-------
sample_weight : array-like of shape (n_samples,) or None
    The reweighted sample weights.
    If None then boosting has terminated early.

estimator_weight : float
    The weight for the current boost.
    If None then boosting has terminated early.

estimator_error : float
    The classification error for the current boost.
    If None then boosting has terminated early.
r,   rK   r   classes_N)weightsr   r3   rP   z\BaseClassifier in AdaBoostClassifier ensemble is worse than random, ensemble can not be fit.NNNr    )_make_estimatorr'   r(   getattrr   r~   
n_classes_rT   meanaveragerX   popr   r0   r   r/   exp)r8   rh   rF   re   rL   r,   r.   	y_predict	incorrectrj   r   ri   s               r:   ra   AdaBoostClassifier._boost  s   L ((l(C	a-8%%a(	Q;#Iz4@DM!$--0DO N	 ''"**YTU"VW a #s**OO	 cS9_55  $4##$) & 
 $  --FFC/)_<=ySV@WW

 **Q..FF}%".-!2CDEM
 ??r<   c                     U R                  U5      nU R                  S:X  a  U R                  R                  US:  SS9$ U R                  R                  [        R
                  " USS9SS9$ )a  Predict classes for X.

The predicted class of an input sample is computed as the weighted mean
prediction of the classifiers in the ensemble.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrix can be CSC, CSR, COO,
    DOK, or LIL. COO, DOK, and LIL are converted to CSR.

Returns
-------
y : ndarray of shape (n_samples,)
    The predicted classes.
r   r   r   r    )decision_functionr   r   takerT   argmax)r8   rF   preds      r:   r(   AdaBoostClassifier.predicth  sc    " %%a(??a==%%dQhQ%77}}!!"))Dq"9!BBr<   c           
   #     #    U R                  U5      nU R                  nU R                  nUS:X  aB  U R                  U5       H,  n[        R
                  " UR                  US:  SS95      v   M.     gU R                  U5       H<  n[        R
                  " UR                  [        R                  " USS9SS95      v   M>     g7f)ai  Return staged predictions for X.

The predicted class of an input sample is computed as the weighted mean
prediction of the classifiers in the ensemble.

This generator method yields the ensemble prediction after each
iteration of boosting and therefore allows monitoring, such as to
determine the prediction on a test set after each boost.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    The input samples. Sparse matrix can be CSC, CSR, COO,
    DOK, or LIL. COO, DOK, and LIL are converted to CSR.

Yields
------
y : generator of ndarray of shape (n_samples,)
    The predicted classes.
r   r   r   r    N)rG   r   r   staged_decision_functionrT   arrayr   r   )r8   rF   r   classesr   s        r:   rq   !AdaBoostClassifier.staged_predict  s     * MM!OO	-->55a8hhw||D1H1|=>> 9 55a8hhw||BIId,C!|LMM 9s   CCc                   ^^^ [        U 5        U R                  T5      mU R                  mU R                  SS2[        R
                  4   mTS:X  a$  [        R                  " TTR                  S   S4S9$ [        UUU4S j[        U R                  U R                  5       5       5      nX R                  R                  5       -  nTS:X  a   USS2S4==   S-  ss'   UR                  SS9$ U$ )	a  Compute the decision function of ``X``.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrix can be CSC, CSR, COO,
    DOK, or LIL. COO, DOK, and LIL are converted to CSR.

Returns
-------
score : ndarray of shape of (n_samples, k)
    The decision function of the input samples. The order of
    outputs is the same as that of the :term:`classes_` attribute.
    Binary classification is a special cases with ``k == 1``,
    otherwise ``k==n_classes``. For binary classification,
    values closer to -1 or 1 mean more like the first or second
    class in ``classes_``, respectively.
Nr    r   )shapec              3      >#    U  HD  u  p[         R                  " UR                  T5      T:H  R                  US TS-
  -  U-  5      v   MF     g7f)r   r    N)rT   wherer(   T)ry   r.   wrF   r   r   s      r:   r|   7AdaBoostClassifier.decision_function.<locals>.<genexpr>  s[      
 !O	 HH""1%033i!m$q( 
 !Os   AAr   r   r   )r   rG   r   r   rT   r   
zeros_liker   rV   r   rX   rZ   )r8   rF   r   r   r   s    ` @@r:   r   $AdaBoostClassifier.decision_function  s    & 	MM!OO	--2::.>==1771:q/:: 
 !$D$4$4d6M6M N
 
 	''++-->AJ"J888##r<   c              #     #    [        U 5        U R                  U5      nU R                  nU R                  SS2[        R
                  4   nSnSn[        U R                  U R                  5       H  u  pgXV-  n[        R                  " UR                  U5      U:H  R                  USUS-
  -  U-  5      nUc  UnOXH-  nUS:X  a<  [        R                  " U5      n	U	SS2S4==   S-  ss'   X-  R                  SS9v   M  XE-  v   M     g7f)a  Compute decision function of ``X`` for each boosting iteration.

This method allows monitoring (i.e. determine error on testing set)
after each boosting iteration.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrix can be CSC, CSR, COO,
    DOK, or LIL. COO, DOK, and LIL are converted to CSR.

Yields
------
score : generator of ndarray of shape (n_samples, k)
    The decision function of the input samples. The order of
    outputs is the same of that of the :term:`classes_` attribute.
    Binary classification is a special cases with ``k == 1``,
    otherwise ``k==n_classes``. For binary classification,
    values closer to -1 or 1 mean more like the first or second
    class in ``classes_``, respectively.
NrP   r   r    r   r   r   )r   rG   r   r   rT   r   r   rZ   rX   r   r(   r   rN   rV   )
r8   rF   r   r   r   r   rz   r.   current_predtmp_preds
             r:   r   +AdaBoostClassifier.staged_decision_function  s    , 	MM!OO	--2::.!$T%<%<d>N>N!OFND88""1%033i!m$v-L |#$A~774=A"$+++33k!' "Ps   DDc                 ~    US:X  a'  [         R                  " U * U /5      R                  S-  n OXS-
  -  n [        U SS9$ )a.  Compute probabilities from the decision function.

This is based eq. (15) of [1] where:
    p(y=c|X) = exp((1 / K-1) f_c(X)) / sum_k(exp((1 / K-1) f_k(X)))
             = softmax((1 / K-1) * f(X))

References
----------
.. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost",
       2009.
r   r    F)rN   )rT   vstackr   r   )decisionr   s     r:   _compute_proba_from_decision/AdaBoostClassifier._compute_proba_from_decision   sD     >yy8)X!6799A=HA%Hxe,,r<   c                     [        U 5        U R                  nUS:X  a!  [        R                  " [	        U5      S45      $ U R                  U5      nU R                  X25      $ )aP  Predict class probabilities for X.

The predicted class probabilities of an input sample is computed as
the weighted mean predicted class probabilities of the classifiers
in the ensemble.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrix can be CSC, CSR, COO,
    DOK, or LIL. COO, DOK, and LIL are converted to CSR.

Returns
-------
p : ndarray of shape (n_samples, n_classes)
    The class probabilities of the input samples. The order of
    outputs is the same of that of the :term:`classes_` attribute.
r    )r   r   rT   r[   r   r   r   r8   rF   r   r   s       r:   r    AdaBoostClassifier.predict_proba  sU    & 	OO	>77LOQ/00))!,00EEr<   c              #   z   #    U R                   nU R                  U5       H  nU R                  X25      v   M     g7f)a3  Predict class probabilities for X.

The predicted class probabilities of an input sample is computed as
the weighted mean predicted class probabilities of the classifiers
in the ensemble.

This generator method yields the ensemble predicted class probabilities
after each iteration of boosting and therefore allows monitoring, such
as to determine the predicted class probabilities on a test set after
each boost.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrix can be CSC, CSR, COO,
    DOK, or LIL. COO, DOK, and LIL are converted to CSR.

Yields
------
p : generator of ndarray of shape (n_samples,)
    The class probabilities of the input samples. The order of
    outputs is the same of that of the :term:`classes_` attribute.
N)r   r   r   r   s       r:   staged_predict_proba'AdaBoostClassifier.staged_predict_proba/  s6     2 OO	55a8H33HHH 9s   9;c                 L    [         R                  " U R                  U5      5      $ )a\  Predict class log-probabilities for X.

The predicted class log-probabilities of an input sample is computed as
the weighted mean predicted class log-probabilities of the classifiers
in the ensemble.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrix can be CSC, CSR, COO,
    DOK, or LIL. COO, DOK, and LIL are converted to CSR.

Returns
-------
p : ndarray of shape (n_samples, n_classes)
    The class probabilities of the input samples. The order of
    outputs is the same of that of the :term:`classes_` attribute.
)rT   r   r   rE   s     r:   predict_log_proba$AdaBoostClassifier.predict_log_probaM  s    & vvd((+,,r<   )r   r   r   rw   )r   r   r   r   r   r%   r1   r   r   r   r   r7   rW   ra   r(   rq   r   r   staticmethodr   r   r   r   r   r   r   s   @r:   r"   r"   V  s    Od$

3
3$j'+VJ~4N-OP$D  # # #$ T@lC0 ND)V1"f - -$F8I<- -r<   c                      ^  \ rS rSr% Sr0 \R                  ES\" 1 Sk5      /0Er\\	S'    SSSS	SS
.U 4S jjjr
U 4S jrS rS rS rS rSrU =r$ )r#   ic  aG  An AdaBoost regressor.

An AdaBoost [1] regressor is a meta-estimator that begins by fitting a
regressor on the original dataset and then fits additional copies of the
regressor on the same dataset but where the weights of instances are
adjusted according to the error of the current prediction. As such,
subsequent regressors focus more on difficult cases.

This class implements the algorithm known as AdaBoost.R2 [2].

Read more in the :ref:`User Guide <adaboost>`.

.. versionadded:: 0.14

Parameters
----------
estimator : object, default=None
    The base estimator from which the boosted ensemble is built.
    If ``None``, then the base estimator is
    :class:`~sklearn.tree.DecisionTreeRegressor` initialized with
    `max_depth=3`.

    .. versionadded:: 1.2
       `base_estimator` was renamed to `estimator`.

n_estimators : int, default=50
    The maximum number of estimators at which boosting is terminated.
    In case of perfect fit, the learning procedure is stopped early.
    Values must be in the range `[1, inf)`.

learning_rate : float, default=1.0
    Weight applied to each regressor at each boosting iteration. A higher
    learning rate increases the contribution of each regressor. There is
    a trade-off between the `learning_rate` and `n_estimators` parameters.
    Values must be in the range `(0.0, inf)`.

loss : {'linear', 'square', 'exponential'}, default='linear'
    The loss function to use when updating the weights after each
    boosting iteration.

random_state : int, RandomState instance or None, default=None
    Controls the random seed given at each `estimator` at each
    boosting iteration.
    Thus, it is only used when `estimator` exposes a `random_state`.
    In addition, it controls the bootstrap of the weights used to train the
    `estimator` at each boosting iteration.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

Attributes
----------
estimator_ : estimator
    The base estimator from which the ensemble is grown.

    .. versionadded:: 1.2
       `base_estimator_` was renamed to `estimator_`.

estimators_ : list of regressors
    The collection of fitted sub-estimators.

estimator_weights_ : ndarray of floats
    Weights for each estimator in the boosted ensemble.

estimator_errors_ : ndarray of floats
    Regression error for each estimator in the boosted ensemble.

feature_importances_ : ndarray of shape (n_features,)
    The impurity-based feature importances if supported by the
    ``estimator`` (when based on decision trees).

    Warning: impurity-based feature importances can be misleading for
    high cardinality features (many unique values). See
    :func:`sklearn.inspection.permutation_importance` as an alternative.

n_features_in_ : int
    Number of features seen during :term:`fit`.

    .. versionadded:: 0.24

feature_names_in_ : ndarray of shape (`n_features_in_`,)
    Names of features seen during :term:`fit`. Defined only when `X`
    has feature names that are all strings.

    .. versionadded:: 1.0

See Also
--------
AdaBoostClassifier : An AdaBoost classifier.
GradientBoostingRegressor : Gradient Boosting Classification Tree.
sklearn.tree.DecisionTreeRegressor : A decision tree regressor.

References
----------
.. [1] Y. Freund, R. Schapire, "A Decision-Theoretic Generalization of
       on-Line Learning and an Application to Boosting", 1995.

.. [2] H. Drucker, "Improving Regressors using Boosting Techniques", 1997.

Examples
--------
>>> from sklearn.ensemble import AdaBoostRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_features=4, n_informative=2,
...                        random_state=0, shuffle=False)
>>> regr = AdaBoostRegressor(random_state=0, n_estimators=100)
>>> regr.fit(X, y)
AdaBoostRegressor(n_estimators=100, random_state=0)
>>> regr.predict([[0, 0, 0, 0]])
array([4.7972])
>>> regr.score(X, y)
0.9771

For a detailed example of utilizing :class:`~sklearn.ensemble.AdaBoostRegressor`
to fit a sequence of decision trees as weak learners, please refer to
:ref:`sphx_glr_auto_examples_ensemble_plot_adaboost_regression.py`.
loss>   linearsquareexponentialr1   Nr2   r3   r   )r/   r0   r   r,   c                >   > [         TU ]  UUUUS9  X@l        XPl        g r   )r6   r7   r   r,   )r8   r.   r/   r0   r   r,   r9   s         r:   r7   AdaBoostRegressor.__init__  s0     	%'%	 	 	
 	(r<   c                 .   > [         TU ]  [        SS9S9  g)r      r   r   N)r6   rW   r   r   s    r:   rW   %AdaBoostRegressor._validate_estimator  s    #,AA,N#Or<   c                    U R                  US9nUR                  [        R                  " [	        U5      5      [	        U5      SUS9n[        X'5      n[        X75      n	UR                  X5        UR                  U5      n
[        R                  " X-
  5      nUS:  nXL   nX   nUR                  5       nUS:w  a  X-  nU R                  S:X  a  US-  nO*U R                  S:X  a  S[        R                  " U* 5      -
  nX-  R                  5       nUS::  a  USS	4$ US
:  a5  [        U R                  5      S:  a  U R                  R                  S5        gUSU-
  -  nU R                   [        R"                  " SU-  5      -  nXR$                  S-
  :X  d1  XL==   [        R&                  " USU-
  U R                   -  5      -  ss'   UUU4$ )ag  Implement a single boost for regression

Perform a single boost according to the AdaBoost.R2 algorithm and
return the updated sample weights.

Parameters
----------
iboost : int
    The index of the current boost iteration.

X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples.

y : array-like of shape (n_samples,)
    The target values (class labels in classification, real numbers in
    regression).

sample_weight : array-like of shape (n_samples,)
    The current sample weights.

random_state : RandomState
    The RandomState instance used if the base estimator accepts a
    `random_state` attribute.
    Controls also the bootstrap of the weights used to train the weak
    learner.

Returns
-------
sample_weight : array-like of shape (n_samples,) or None
    The reweighted sample weights.
    If None then boosting has terminated early.

estimator_weight : float
    The weight for the current boost.
    If None then boosting has terminated early.

estimator_error : float
    The regression error for the current boost.
    If None then boosting has terminated early.
r   T)sizereplacepr   r   r   r   r3   rP         ?r    r   r   )r   choicerT   aranger   r   r'   r(   absmaxr   r   rV   r~   rX   r   r0   r   r/   power)r8   rh   rF   re   rL   r,   r.   bootstrap_idxX_y_r   
error_vectsample_maskmasked_sample_weightmasked_error_vector	error_maxrj   betari   s                      r:   ra   AdaBoostRegressor._boost  s   R ((l(C	 %++IIl1o&a	 , 
 A-A-b%%a(	VVIM*
#a',9(5'++-	>,99 A%YY-'"%0C/C(D"D 0EJJLa #s**#4##$q(  $$R(##"78  --sTz0BB**Q..&"((s00D4F4FF+ & .??r<   c                    [         R                  " U R                  S U  Vs/ s H  o3R                  U5      PM     sn5      R                  n[         R
                  " USS9n[        U R                  U   SS9nUSUS S 2S4   S S 2[         R                  4   -  :  nUR                  SS9nU[         R                  " [        U5      5      U4   n	U[         R                  " [        U5      5      U	4   $ s  snf )Nr    r   r   r   )rT   r   rX   r(   r   argsortr   rZ   r   r   r   r   )
r8   rF   limitestpredictions
sorted_idx
weight_cdfmedian_or_above
median_idxmedian_estimatorss
             r:   _get_median_predict%AdaBoostRegressor._get_median_predictV  s    hh$:J:J6E:RS:R3A:RSTVV ZZ!4
 #4#:#::#FQO
$jB.?2::.N(NN$+++3
&ryya'A:'MN 299\!_57HHII  Ts   C4c                     [        U 5        U R                  U5      nU R                  U[        U R                  5      5      $ )a  Predict regression value for X.

The predicted regression value of an input sample is computed
as the weighted median prediction of the regressors in the ensemble.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrix can be CSC, CSR, COO,
    DOK, or LIL. COO, DOK, and LIL are converted to CSR.

Returns
-------
y : ndarray of shape (n_samples,)
    The predicted regression values.
)r   rG   r  r~   rX   rE   s     r:   r(   AdaBoostRegressor.predictg  s8    " 	MM!''3t/?/?+@AAr<   c              #      #    [        U 5        U R                  U5      n[        U R                  S5       H  u  p#U R	                  XS9v   M     g7f)a<  Return staged predictions for X.

The predicted regression value of an input sample is computed
as the weighted median prediction of the regressors in the ensemble.

This generator method yields the ensemble prediction after each
iteration of boosting and therefore allows monitoring, such as to
determine the prediction on a test set after each boost.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples.

Yields
------
y : generator of ndarray of shape (n_samples,)
    The predicted regression values.
r    )r  N)r   rG   	enumeraterX   r  )r8   rF   i_s       r:   rq    AdaBoostRegressor.staged_predict}  sJ     ( 	MM!d..2DA**1*66 3s   AA)r   r,   rw   )r   r   r   r   r   r%   r1   r   r   r   r7   rW   ra   r  r(   rq   r   r   r   s   @r:   r#   r#   c  s    sj$

3
3$?@A$D  ) ) )&P_@BJ"B,7 7r<   )1r   rc   abcr   r   numbersr   r   numpyrT   baser   r	   r
   r   r   metricsr   r   treer   r   utilsr   r   utils._param_validationr   r   r   r   utils.extmathr   r   utils.metadata_routingr   r   utils.validationr   r   r   r   r   _baser!   __all__r%   r   r"   r#   rn   r<   r:   <module>r)     s   *  ' "   / @ 6 N N 2    C CL*J-0BJ-Zr71>CU r7r<   