
    >[g                     @   d Z ddlZddlmZmZ ddlmZmZ ddlZ	ddl
mZmZmZmZmZ ddlmZmZ ddlmZmZ dd	lmZmZ dd
lmZmZmZmZ ddlmZm Z  ddl!m"Z"m#Z# ddl$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+ ddgZ, G d de+e      Z-d Z. G d de#ee-      Z/ G d de#ee-      Z0y)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                        e Zd ZU dZ eddg      dg eeddd      g eeddd	      gd
gdZe	e
d<   e	 dd e       ddd fd       Zd Z ed      dd       Zed        ZddZed        Z xZS )BaseWeightBoostingzBase 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_paramsr/   r+   c                F    t         |   |||       || _        || _        y )N)r-   r.   r3   )super__init__r/   r+   )selfr-   r.   r3   r/   r+   	__class__s         \/var/www/html/bid-api/venv/lib/python3.12/site-packages/sklearn/ensemble/_weight_boosting.pyr6   zBaseWeightBoosting.__init__I   s2     	%- 	 	
 +(    c           	      *    t        | |ddgddd d      S )NcsrcscTF)accept_sparse	ensure_2dallow_nddtypereset)r   r7   Xs     r9   _check_XzBaseWeightBoosting._check_X\   s(     %.
 	
r:   F)prefer_skip_nested_validationc                    t        | d|       t        | ||ddgdddt        |             \  }}t        ||t        j
                  dd      }||j                         z  }| j                          g | _        t	        j                  | j                  t        j
                  	      | _        t	        j                  | j                  t        j
                  	      | _        t        | j                        }t	        j                   |j"                        j$                  }|d
k(  }t'        | j                        D ]  }t	        j(                  ||d      }d
||<   | j+                  |||||      \  }}}	| | S || j                  |<   |	| j                  |<   |	dk(  r | S t	        j                  |      }
t	        j,                  |
      st/        j0                  d| dd        | S |
dk  r | S || j                  dz
  k  s||
z  } | S )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>   r?   r@   rA   	y_numeric)copyensure_non_negative)rA           )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+   finforA   epsrangeclip_boostisfinitewarningswarn)r7   rD   yrI   r+   epsilonzero_weight_maskiboostestimator_weightestimator_errorsample_weight_sums              r9   r&   zBaseWeightBoosting.fith   s&   2 	'tU-P %."4(	
1 -1bjjt
 	**,, 	  " "$((4+<+<BJJ"O!#):):"**!M *$*;*;<((=../33(C/D--.FGGMMM.1M*+ @D{{1m\@<M+_
 $: 9 /?D##F+-<D""6* !#. + !#} 5;;01))/ 1NN  !   !A% 	 ))A--!22Q /T r:   c                      y)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 )r7   re   rD   rb   rI   r+   s         r9   r^   zBaseWeightBoosting._boost   s    L 	r:   c              #      K   | j                  |      }| j                  |      D ].  }t        |       rt        |||       t	        |||       0 yw)a  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
        rH   N)rE   staged_predictr   r   r   )r7   rD   rb   rI   y_preds        r9   staged_scorezBaseWeightBoosting.staged_score   sQ     . MM!))!,FT"$QmLLq&FF	 -s   AAc                 6   | j                   t        | j                         dk(  rt        d      	 | j                  j	                         }t	        d t        | j                  | j                         D              |z  S # t        $ r}t        d      |d}~ww xY w)au  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   @   K   | ]  \  }}||j                   z    y wN)feature_importances_).0weightclfs      r9   	<genexpr>z:BaseWeightBoosting.feature_importances_.<locals>.<genexpr>-  s'      'U S555'Us   zdUnable to compute feature importances since estimator does not have a feature_importances_ attribute)rU   len
ValueErrorrW   rS   zipAttributeError)r7   normes      r9   rr   z'BaseWeightBoosting.feature_importances_  s    $ #s4+;+;'<'AQ 	**..0D '*4+B+BDDTDT'U  	  	 1 		s   AA> >	BBBrq   )__name__
__module____qualname____doc__r   r   r   r   r0   dict__annotations__r   tupler6   rE   r
   r&   r^   rn   propertyrr   __classcell__r8   s   @r9   r%   r%   ;   s     !%!34d;!(AtFCD"4DCD'(	$D   ) ) )$

 &+^	^@ % %NG> % %r:   r%   )	metaclassc                 :   | j                  |      }t        j                  |t        j                  |j                        j
                  d|       t        j                  |      }|dz
  |d|z  |j                  d      ddt        j                  f   z  z
  z  S )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    r2   axis)	predict_probarQ   r]   rZ   rA   r[   logrS   newaxis)r-   	n_classesrD   proba	log_probas        r9   _samme_probar   <  s     ##A&E
 GGE288EKK(,,d>uIMS9_	1(=am(LLL r:   c                        e Zd ZU dZi ej
                  d edh       e edh            giZee	d<   	 dddddd	 fd
Z
 fdZd Zd Zd Zd Zd Zed        Zd Zd Zd Z xZS )r"   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 seperable
    classification dataset composed of two Gaussian quantiles clusters, please
    refer to :ref:`sphx_glr_auto_examples_ensemble_plot_adaboost_twoclass.py`.
    	algorithmSAMME
deprecatedr0   Nr1   r2   )r.   r/   r   r+   c                :    t         |   ||||       || _        y Nr,   )r5   r6   r   )r7   r-   r.   r/   r   r+   r8   s         r9   r6   zAdaBoostClassifier.__init__  s,     	%'%	 	 	
 #r:   c                    t         |   t        d             | j                  dk7  rt	        j
                  dt               t        | j                  d      s,t        | j                  j                  j                   d      y)	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.rI   z doesn't support sample_weight.N)r5   rT   r   r   r`   ra   FutureWarningr   
estimator_rx   r-   r8   r}   r7   r8   s    r9   rT   z&AdaBoostClassifier._validate_estimator  sx    #,BQ,O#P>>\)MM5 !/B>>++4455TU  Cr:   c                 
   | j                  |      }|j                  |||       |j                  |      }|dk(  r,t        |dd      | _        t        | j                        | _        ||k7  }t        j                  t        j                  ||d            }	|	dk  r|ddfS | j                  }
|	dd|
z  z
  k\  r?| j                  j                  d	       t        | j                        dk(  rt        d
      y| j                  t        j                  d|	z
  |	z        t        j                  |
dz
        z   z  }|| j                  dz
  k(  s4t        j                   t        j                  |      ||z  |dkD  z  z         }|||	fS )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+   rH   r   classes_N)weightsr   r2   rM   z\BaseClassifier in AdaBoostClassifier ensemble is worse than random, ensemble can not be fit.NNNr    )_make_estimatorr&   r'   getattrr   rw   
n_classes_rQ   meanaveragerU   poprx   r/   r   r.   exp)r7   re   rD   rb   rI   r+   r-   	y_predict	incorrectrg   r   rf   s               r9   r^   zAdaBoostClassifier._boost  s   L ((l(C	a-8%%a(	Q;#Iz4@DM!$--0DO N	 ''"**YTU"VW a #s**OO	 cS9_55  $4##$) & 
 $  --FFC/)_<=ySV@WW

 **Q..FF}%"Y.-!2CDEM
 .??r:   c                     | j                  |      }| j                  dk(  r | j                  j                  |dkD  d      S | j                  j                  t	        j
                  |d      d      S )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   takerQ   argmax)r7   rD   preds      r9   r'   zAdaBoostClassifier.predictc  sc    " %%a(??a==%%dQhQ%77}}!!"))Dq"9!BBr:   c           	   #     K   | j                  |      }| j                  }| j                  }|dk(  rB| j                  |      D ]-  }t	        j
                  |j                  |dkD  d             / y| j                  |      D ]?  }t	        j
                  |j                  t	        j                  |d      d             A yw)a  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)rE   r   r   staged_decision_functionrQ   arrayr   r   )r7   rD   r   classesr   s        r9   rl   z!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                    t        |        | j                        | j                  | j                  ddt        j
                  f   dk(  r&t	        j                  j                  d   df      S t        fdt        | j                  | j                        D              }|| j                  j                         z  }dk(  r#|dddfxx   dz  cc<   |j                  d      S |S )	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      K   | ]C  \  }}t        j                  |j                        k(  j                  |d dz
  z  |z         E yw)r   r    N)rQ   wherer'   T)rs   r-   wrD   r   r   s      r9   rv   z7AdaBoostClassifier.decision_function.<locals>.<genexpr>  sY      
 !O	1 HH""1%033i!m$q(
 !Os   A	Ar   r   r   )r   rE   r   r   rQ   r   
zeros_liker   rS   ry   rU   rW   )r7   rD   r   r   r   s    ` @@r9   r   z$AdaBoostClassifier.decision_function  s    & 	MM!OO	--2::.>==1771:q/:: 
 !$D$4$4d6M6M N
 
 	''++-->AJ"J888##r:   c              #      K   t        |        | j                  |      }| j                  }| j                  ddt        j
                  f   }d}d}t        | j                  | j                        D ]  \  }}||z  }t	        j                  |j                  |      |k(  j                  |d|dz
  z  |z        }||}n||z  }|dk(  r>t	        j                  |      }	|	dddfxx   dz  cc<   |	|z  j                  d       ||z    yw)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.
        NrM   r   r    r   r   r   )r   rE   r   r   rQ   r   ry   rW   rU   r   r'   r   rK   rS   )
r7   rD   r   r   r   r{   rt   r-   current_predtmp_preds
             r9   r   z+AdaBoostClassifier.staged_decision_function  s    , 	MM!OO	--2::.!$T%<%<d>N>N!OFIFND88""1%033i!m$v-L |#$A~774=A"$$+++33Tk!' "Ps   DDc                     |dk(  r&t        j                  |  | g      j                  dz  } n| |dz
  z  } t        | d      S )an  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)rK   )rQ   vstackr   r   )decisionr   s     r9   _compute_proba_from_decisionz/AdaBoostClassifier._compute_proba_from_decision  sF     >yy8)X!6799A=H	A%Hxe,,r:   c                     t        |        | j                  }|dk(  r t        j                  t	        |      df      S | j                  |      }| j                  ||      S )a  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   rQ   rX   r   r   r   r7   rD   r   r   s       r9   r   z AdaBoostClassifier.predict_proba  sW    & 	OO	>77LOQ/00))!,009EEr:   c              #   x   K   | j                   }| j                  |      D ]  }| j                  ||        yw)a  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       r9   staged_predict_probaz'AdaBoostClassifier.staged_predict_proba*  s9     2 OO	55a8H33HiHH 9s   8:c                 J    t        j                  | j                  |            S )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.
        )rQ   r   r   rC   s     r9   predict_log_probaz$AdaBoostClassifier.predict_log_probaH  s    & vvd((+,,r:   rq   )r}   r~   r   r   r%   r0   r   r   r   r   r6   rT   r^   r'   rl   r   r   staticmethodr   r   r   r   r   r   s   @r9   r"   r"   Q  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                        e Zd ZU dZi ej
                  d eh d      giZeed<   	 dddddd	 fd
Z	 fdZ
d Zd Zd Zd Z xZS )r#   a  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exponentialr0   Nr1   r2   r   )r.   r/   r   r+   c                H    t         |   ||||       || _        || _        y r   )r5   r6   r   r+   )r7   r-   r.   r/   r   r+   r8   s         r9   r6   zAdaBoostRegressor.__init__  s4     	%'%	 	 	
 	(r:   c                 :    t         |   t        d             y)r      r   r   N)r5   rT   r   r   s    r9   rT   z%AdaBoostRegressor._validate_estimator  s    #,AA,N#Or:   c                    | j                  |      }|j                  t        j                  t	        |            t	        |      d|      }t        ||      }t        ||      }	|j                  ||	       |j                  |      }
t        j                  |
|z
        }|dkD  }||   }||   }|j                         }|dk7  r||z  }| j                  dk(  r|dz  }n(| j                  dk(  rdt        j                  |       z
  }||z  j                         }|dk  r|dd	fS |d
k\  r4t        | j                        dkD  r| j                  j                  d       y|d|z
  z  }| j                   t        j"                  d|z        z  }|| j$                  dz
  k(  s1||xx   t        j&                  |d|z
  | j                   z        z  cc<   |||fS )aW  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   r2   rM         ?r    r   r   )r   choicerQ   aranger   r   r&   r'   absmaxr   r   rS   rw   rU   r   r/   r   r.   power)r7   re   rD   rb   rI   r+   r-   bootstrap_idxX_y_r   
error_vectsample_maskmasked_sample_weightmasked_error_vector	error_maxrg   betarf   s                      r9   r^   zAdaBoostRegressor._boost  s   R ((l(C	 %++IIl1o&a	 , 
 A}-A}-b"%%a(	VVIM*
#a',[9(5'++-	>9,99 A%YY-'"%0C/C(D"D 02EEJJLa #s**#4##$q(  $$R(##"78  --sTz0BB**Q..+&"((s00D4F4FF+ & .??r:   c                    t        j                  | j                  d | D cg c]  }|j                  |       c}      j                  }t        j
                  |d      }t        | j                  |   d      }|d|d d df   d d t         j                  f   z  k\  }|j                  d      }|t        j                  t        |            |f   }	|t        j                  t        |            |	f   S c c}w )Nr    r   r   r   )rQ   r   rU   r'   r   argsortr   rW   r   r   r   r   )
r7   rD   limitestpredictions
sorted_idx
weight_cdfmedian_or_above
median_idxmedian_estimatorss
             r9   _get_median_predictz%AdaBoostRegressor._get_median_predictQ  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   C7c                     t        |        | j                  |      }| j                  |t        | j                              S )a1  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   rE   r   rw   rU   rC   s     r9   r'   zAdaBoostRegressor.predictb  s8    " 	MM!''3t/?/?+@AAr:   c              #      K   t        |        | j                  |      }t        | j                  d      D ]  \  }}| j	                  ||        yw)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   rE   	enumeraterU   r   )r7   rD   i_s       r9   rl   z AdaBoostRegressor.staged_predictx  sO     ( 	MM!d..2DAq**1A*66 3s   AArq   )r}   r~   r   r   r%   r0   r   r   r   r6   rT   r^   r   r'   rl   r   r   s   @r9   r#   r#   ^  sv    sj$

3
3$?@A$D  ) )&P_@BJ"B,7r:   )1r   r`   abcr   r   numbersr   r   numpyrQ   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#   rj   r:   r9   <module>r     s   *  ' "   / @ 6 N N 2    ~ ~B*J-0BJ-Zr71>CU r7r:   