
    -i                        S r SSKrSSKrSSKJrJr  SSKJr  SSKJr  SSK	J
r
  SSKrSSK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  SSKJr  SSKJrJ r J!r!  SSK"J#r#  SSK$J%r%J&r&J'r'J(r(J)r)J*r*  SSK+J,r,  SSK-J.r.  SSK/J0r0J1r1  SSK2J3r3  SSK4J5r5J6r6J7r7J8r8J9r9J:r:  SSK;J<r<J=r=  SS/r>\R~                  " \R                  5      R                  rBS rCS rDS rE  S%S jrFS rGS rHS rI " S  S!\<\S"9rJ " S# S\\J5      rK " S$ S\\J5      rLg)&zBagging meta-estimator.    N)ABCMetaabstractmethod)partial)Integralwarn   )ClassifierMixinRegressorMixin_fit_context)accuracy_scorer2_score)DecisionTreeClassifierDecisionTreeRegressor)Bunch_safe_indexingcheck_random_statecolumn_or_1d)indices_to_mask)
HasMethodsInterval
RealNotInt)get_tags)MetadataRouterMethodMapping_raise_for_params_routing_enabledget_routing_for_objectprocess_routing)available_if)check_classification_targets)Paralleldelayed)sample_without_replacement)_check_method_params_check_sample_weight_estimator_hascheck_is_fittedhas_fit_parametervalidate_data   )BaseEnsemble_partition_estimatorsBaggingClassifierBaggingRegressorc                 P    U(       a  U R                  SX#5      nU$ [        X#U S9nU$ )zDraw randomly sampled indices.r   )random_state)randintr$   )r1   	bootstrapn_population	n_samplesindicess        L/var/www/html/venv/lib/python3.13/site-packages/sklearn/ensemble/_bagging.py_generate_indicesr8   6   s8     &&q,B N	 -,
 N    c                 N    [        U 5      n [        XX55      n[        XXF5      nXx4$ )z)Randomly draw feature and sample indices.)r   r8   )	r1   bootstrap_featuresbootstrap_samples
n_featuresr5   max_featuresmax_samplesfeature_indicessample_indicess	            r7   _generate_bagging_indicesrB   C   s;     &l3L (*O 'N **r9   c	           
         UR                   u  pUR                  nUR                  nUR                  nUR                  n[        UR                  S5      nU=(       d    X:g  n/ n/ n[        UR                  S5      n[        5       (       d$  U(       d  UR                  S5      b  [        S5      e[        U 5       GH  nUS:  a  [        SUS-   X4-  5        UU   nUR                  SUS9nU(       a  [        UR                  US	9nOUR                  n[        UUUU
U	UU5      u  nnUR!                  5       n[        5       (       a(  [#        UR                  5      nUR%                  S
S5      nOUnU(       a  ['        UR)                  SS5      U5      R!                  5       nU(       a  [*        R,                  " UU	S9nUU-  nO[/        UU	5      ) nSUU'   UUS'   U(       a	  USS2U4   OUn U" U U40 UD6  O=[1        UU5      n![1        UU5      n [3        UUUS9nU(       a	  U SS2U4   n U" U U!40 UD6  UR5                  U5        UR5                  U5        GM     UU4$ )zBPrivate function used to build a batch of estimators within a job.check_inputsample_weightNz`The base estimator doesn't support sample weight, but sample_weight is passed to the fit method.r+   z?Building estimator %d of %d for this parallel run (total %d)...F)appendr1   )rD   fit)rE   )	minlengthr   )paramsr6   )shape_max_features_max_samplesr3   r;   r)   
estimator_r   get
ValueErrorrangeprint_make_estimatorr   rG   rB   copyr   consumesr&   popnpbincountr   r   r%   rF   )"n_estimatorsensembleXyseedstotal_n_estimatorsverboserD   
fit_paramsr5   r=   r>   r?   r3   r;   has_check_inputrequires_feature_indexing
estimatorsestimators_featuressupport_sample_weightir1   	estimatorestimator_fitfeaturesr6   fit_params_request_or_routerconsumes_sample_weightcurr_sample_weightsample_countsnot_indices_maskX_y_s"                                     r7   _parallel_build_estimatorsrq   [   s    GGI))L''K""I!44'(;(;]KO 2 Pl6P J .h.A.A?S!jnn_&E&Q(
 	

 < Q;Qq5,;<
 Qx,,E,U	#IMM{KM%MMM 6
' !oo'  6x7J7J K%6%?%?)&" &;"!!56"df   "Gy I"m3"$3GY$G#G 78"#34+=K(#<1h;!B"a/;/  7+B7+B.qgVK(8_"b0K0)$""8,O !R ***r9   c                 *   UR                   S   n[        R                  " Xc45      n[        X5       H  u  p[	        US5      (       a  UR
                  " USS2U	4   40 U=(       d    0 D6n
U[        UR                  5      :X  a  Xz-  nMX  USS2UR                  4==   U
SS2[        [        UR                  5      5      4   -  ss'   M  UR                  " USS2U	4   40 U=(       d    0 D6n[        U5       H  nX|X   4==   S-  ss'   M     M     U$ )zBPrivate function used to compute (proba-)predictions within a job.r   predict_probaNr+   )
rJ   rV   zerosziphasattrrs   lenclasses_rP   predict)rb   rc   rZ   	n_classespredict_paramspredict_proba_paramsr5   probarf   rh   proba_estimatorpredictionsre   s                r7   _parallel_predict_probar      s    
IHHi+,E":C	9o..'55!X+#1#7RO C	 2 233( a+++,uS!3!34551 , $++!X+#7#=2K 9%'(A-( &)  D. Lr9   c                    UR                   S   n[        R                  " XS45      nUR                  [        R                  * 5        [        R
                  " U[        S9n[        X5       GH  u  pUR                  " USS2U	4   40 UD6n
U[        UR                  5      :X  a  [        R                  " Xj5      nMQ  [        R                  " USS2UR                  4   U
SS2[        [        UR                  5      5      4   5      USS2UR                  4'   [        R                  " XxR                  5      n[        R                  " USS2U4   [        R                  * 5      USS2U4'   GM     U$ )z@Private function used to compute log probabilities within a job.r   )dtypeN)rJ   rV   emptyfillinfarangeintru   predict_log_probarw   rx   	logaddexprP   	setdiff1d)rb   rc   rZ   rz   rI   r5   	log_probaall_classesrf   rh   log_proba_estimatormissings               r7   _parallel_predict_log_probar      s*   
I)/0INNBFF7))IS1K":C	'99!AxK.SFSI..//YDI 02||!Y///0#AuS1C1C-D'E$EF0Ia+++,
 ll;0B0BCG$&LL1g:1F$PIaj!  D r9   c                 D   ^^ [        UU4S j[        X5       5       5      $ )z8Private function used to compute decisions within a job.c              3   \   >#    U  H!  u  pUR                   " TS S 2U4   40 TD6v   M#     g 7fNdecision_function.0rf   rh   rZ   rI   s      r7   	<genexpr>._parallel_decision_function.<locals>.<genexpr>  s3      #GI 	##AakN=f=#G   ),sumru   rb   rc   rZ   rI   s     ``r7   _parallel_decision_functionr   
  "     #&z#G  r9   c                 D   ^^ [        UU4S j[        X5       5       5      $ )z:Private function used to compute predictions within a job.c              3   \   >#    U  H!  u  pUR                   " TS S 2U4   40 TD6v   M#     g 7fr   ry   r   s      r7   r   /_parallel_predict_regression.<locals>.<genexpr>  s3      #GI 	!AxK.3F3#Gr   r   r   s     ``r7   _parallel_predict_regressionr     r   r9   c                   t  ^  \ rS rSr% Sr\" SS/5      S/\" \SSSS9/\" \SSSS9\" \S	SS
S9/\" \SSSS9\" \S	SS
S9/S/S/S/S/S\/S/S/S.r	\
\S'   \  S!SSSSSSSSS	S.	U 4S jjj5       r\" SS9S"S j5       rS r    S#S jr\S 5       rS rS r\S 5       rS r\S 5       rU 4S jrS rU =r$ )$BaseBaggingi  zvBase class for Bagging meta-estimator.

Warning: This class should not be used directly. Use derived classes
instead.
rG   ry   Nr+   left)closedr   rightbooleanr1   r^   rf   rX   r?   r>   r3   r;   	oob_score
warm_startn_jobsr1   r^   _parameter_constraints      ?TF	r?   r>   r3   r;   r   r   r   r1   r^   c       	            > [         TU ]  UUS9  X0l        X@l        XPl        X`l        Xpl        Xl        Xl        Xl	        Xl
        g )N)rf   rX   )super__init__r?   r>   r3   r;   r   r   r   r1   r^   selfrf   rX   r?   r>   r3   r;   r   r   r   r1   r^   	__class__s               r7   r   BaseBagging.__init__5  sP      	% 	 	
 '(""4"$(r9   )prefer_skip_nested_validationc           
          [        X@S5        [        U UUSS/SSSS9u  pU R                  " UU4U R                  US.UD6$ )	a  Build a Bagging ensemble of estimators from the training set (X, y).

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrices are accepted only if
    they are supported by the base estimator.

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,), default=None
    Sample weights. If None, then samples are equally weighted.
    Note that this is supported only if the base estimator supports
    sample weighting.
**fit_params : dict
    Parameters to pass to the underlying estimators.

    .. versionadded:: 1.5

        Only available if `enable_metadata_routing=True`,
        which can be set by using
        ``sklearn.set_config(enable_metadata_routing=True)``.
        See :ref:`Metadata Routing User Guide <metadata_routing>` for
        more details.

Returns
-------
self : object
    Fitted estimator.
rG   csrcscNFT)accept_sparser   ensure_all_finitemulti_output)r?   rE   )r   r*   _fitr?   )r   rZ   r[   rE   r_   s        r7   rG   BaseBagging.fitS  sl    J 	*E2  %.#
 yy
 (('	

 
 	
r9   c                     0 $ r    r   s    r7   _parallel_argsBaseBagging._parallel_args  s    	r9   c                 	  ^ ^^^^^^^^ [        T R                  5      nTR                  S   n	U	T l        T R	                  T5      mT R                  T R                  5       5        Ub  XgS'   [        5       (       a  [        T S40 UD6mO:[        5       m[        US9Tl
        SU;   a  US   TR                  R                  S'   Ub  UT R                  l        Uc  T R                  nO:[        U[         R"                  5      (       d  [%        UTR                  S   -  5      nUTR                  S   :  a  ['        S5      eUT l        [        T R*                  [         R"                  5      (       a  T R*                  n
OA[        T R*                  [,        5      (       a"  [%        T R*                  T R.                  -  5      n
W
T R.                  :  a  ['        S5      e[1        S[%        U
5      5      n
U
T l        T R4                  (       d  T R6                  (       a  ['        S5      eT R8                  (       a  T R6                  (       a  ['        S	5      e[;        T S
5      (       a  T R8                  (       a  T ?T R8                  (       a  [;        T S5      (       d  / T l        / T l         T RB                  [E        T R>                  5      -
  nUS:  a-  ['        ST RB                  [E        T R>                  5      4-  5      eUS:X  a  [G        S5        T $ [I        UT RJ                  5      u  nmm[M        T5      mT R8                  (       a@  [E        T R>                  5      S:  a'  URO                  [P        [E        T R>                  5      S9  URO                  [P        US9mTT l)        [U        SUT RV                  S.T RY                  5       D6" UUUUUU UUU4	S j[[        U5       5       5      nT =R>                  []        [^        R`                  Rc                  S U 5       5      5      -  sl        T =R@                  []        [^        R`                  Rc                  S U 5       5      5      -  sl         T R6                  (       a  T Re                  TT5        T $ )a2  Build a Bagging ensemble of estimators from the training
   set (X, y).

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrices are accepted only if
    they are supported by the base estimator.

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

max_samples : int or float, default=None
    Argument to use instead of self.max_samples.

max_depth : int, default=None
    Override value used when constructing base estimator. Only
    supported if the base estimator has a max_depth parameter.

check_input : bool, default=True
    Override value used when fitting base estimator. Only supported
    if the base estimator has a check_input parameter for fit function.
    If the meta-estimator already checks the input, set this value to
    False to prevent redundant input validation.

sample_weight : array-like of shape (n_samples,), default=None
    Sample weights. If None, then samples are equally weighted.
    Note that this is supported only if the base estimator supports
    sample weighting.

**fit_params : dict, default=None
    Parameters to pass to the :term:`fit` method of the underlying
    estimator.

Returns
-------
self : object
    Fitted estimator.
r   rE   rG   )rG   z max_samples must be <= n_samplesz"max_features must be <= n_featuresr+   z6Out of bag estimation only available if bootstrap=Truez6Out of bag estimate only available if warm_start=False
oob_score_estimators_zTn_estimators=%d must be larger or equal to len(estimators_)=%d when warm_start==TruezJWarm-start fitting without increasing n_estimators does not fit new trees.)sizer   r^   c              3      >	#    U  HM  n[        [        5      " TU   TTT
TTU   TUS -       T	TR                  TTR                  R                  S9	v   MO     g7f)r+   )r^   rD   r_   N)r#   rq   r^   rf   rG   )r   re   rZ   rD   rX   routed_paramsr\   r   startsr]   r[   s     r7   r   #BaseBagging._fit.<locals>.<genexpr>%  si      

 # ./QfQi&Q-0"'(2266
 #s   AAc              3   *   #    U  H	  oS    v   M     g7f)r   Nr   r   ts     r7   r   r   6       )D1A$   c              3   *   #    U  H	  oS    v   M     g7f)r+   Nr   r   s     r7   r   r   9  r   r   r   )3r   r1   rJ   
_n_samples_validate_y_validate_estimator_get_estimatorr   r   r   rf   rG   rM   	max_depthr?   
isinstancenumbersr   r   rO   rL   r>   floatn_features_in_maxrK   r3   r   r   rv   r   r   estimators_features_rX   rw   r   r-   r   r   r2   MAX_INT_seedsr"   r^   r   rP   list	itertoolschainfrom_iterable_set_oob_score)r   rZ   r[   r?   r   rD   rE   r_   r1   r5   r>   n_more_estimatorsr   all_resultsrX   r   r\   r   r]   s   ```  `        @@@@@r7   r   BaseBagging._fit  s   d *$*;*;< GGAJ	#Q 	  !4!4!67$*7'+D%F:FM!GM&+
&;M#*,?I#@''++O<  (1DOO% **KK)9)9::kAGGAJ67K#?@@ ( d'')9)9::,,L))511t0043F3FFGL$---ABB1c,/0 * ~~$..UVV??t~~UVV4&&4??gdM&B&B!D(*D% --D4D4D0EEq <$$c$*:*:&;<=  !#! K (=t{{(
$f !. ??s4#3#34q8  s43C3C/D E$$W3D$E 
4<<
373F3F3H


 

 6]


$ 	DOO)))D)DD
 	
 	!!TOO)))D)DD&
 	
! >>1%r9   c                     g)z+Calculate out of bag predictions and score.Nr   )r   rZ   r[   s      r7   r   BaseBagging._set_oob_scoreA      r9   c                 r    [        UR                  5      S:X  d  UR                  S   S:X  a
  [        USS9$ U$ )Nr+   Tr   )rw   rJ   r   r   r[   s     r7   r   BaseBagging._validate_yE  s2    qww<1
a--r9   c           
   #      #    U R                    HW  n[        UU R                  U R                  U R                  U R
                  U R                  U R                  5      u  p#X#4v   MY     g 7fr   )r   rB   r;   r3   r   r   rK   rL   )r   seedr@   rA   s       r7   _get_estimators_indices#BaseBagging._get_estimators_indicesJ  sc     KKD /H''##""!!/+O "11  s   A)A+c                 X    U R                  5        VVs/ s H  u  pUPM	     snn$ s  snnf )a  
The subset of drawn samples for each base estimator.

Returns a dynamically generated list of indices identifying
the samples used for fitting each member of the ensemble, i.e.,
the in-bag samples.

Note: the list is re-created at each call to the property in order
to reduce the object memory footprint by not storing the sampling
data. Thus fetching the property may be slower than expected.
)r   )r   _rA   s      r7   estimators_samples_BaseBagging.estimators_samples_[  s*     9=8T8T8VW8V#418VWWWs   &c                 d   [        U R                  R                  S9n[        5       nUR	                  SSS9R	                  SSS9  [        U R                  5       S5      (       a  UR	                  SSS9R	                  SSS9  OUR	                  SSS9R	                  SSS9  [        U R                  5       S5      (       a  UR	                  SSS9  O@[        U R                  5       S5      (       a  UR	                  SSS9  OUR	                  SSS9  UR	                  U R                  5       US9  U$ )	a"  Get metadata routing of this object.

Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.

.. versionadded:: 1.5

Returns
-------
routing : MetadataRouter
    A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
    routing information.
)ownerrG   )callercalleer   rs   ry   r   )rf   method_mapping)r   r   __name__r   addrv   r   )r   routerr   s      r7   get_metadata_routing BaseBagging.get_metadata_routingj  sB     dnn&=&=>&%6::&/B 	; 	
 4&&(/::"")O"LPP*? Q  "")I"FJJ*9 K  4&&(*=>>&9BUV t**,o>>""*=o"V ""*=i"P

T002>
Rr9   c                     g)z"Resolve which estimator to return.Nr   r   s    r7   r   BaseBagging._get_estimator  r   r9   c                   > [         TU ]  5       n[        U R                  5       5      R                  R
                  UR                  l        [        U R                  5       5      R                  R                  UR                  l        U$ r   )r   __sklearn_tags__r   r   
input_tagssparse	allow_nan)r   tagsr   s     r7   r  BaseBagging.__sklearn_tags__  sa    w')!)$*=*=*?!@!K!K!R!R$,T-@-@-B$C$N$N$X$X!r9   )rK   rL   r   r   r3   r;   r   r   r>   r?   r   r   r1   r^   r   N
   r   )NNTN)r   
__module____qualname____firstlineno____doc__r   r   r   r   r   dict__annotations__r   r   r   rG   r   r   r   r   r   propertyr   r   r   r  __static_attributes____classcell__r   s   @r7   r   r     s{    !%!34d;!(AtFCDXq$v6ZAg6

 Xq$v6ZAg6
  [(k[ k"'(;#$D (  
    : &+4
	4
l ob : :
2" X X8t 1 1 r9   r   )	metaclassc                      ^  \ rS rSrSr  SSSSSSSSSSS.	U 4S	 jjjrS
 rS rS rS r	S r
S r\" \" SSS95      S 5       rSrU =r$ )r.   i  a  A Bagging classifier.

A Bagging classifier is an ensemble meta-estimator that fits base
classifiers each on random subsets of the original dataset and then
aggregate their individual predictions (either by voting or by averaging)
to form a final prediction. Such a meta-estimator can typically be used as
a way to reduce the variance of a black-box estimator (e.g., a decision
tree), by introducing randomization into its construction procedure and
then making an ensemble out of it.

This algorithm encompasses several works from the literature. When random
subsets of the dataset are drawn as random subsets of the samples, then
this algorithm is known as Pasting [1]_. If samples are drawn with
replacement, then the method is known as Bagging [2]_. When random subsets
of the dataset are drawn as random subsets of the features, then the method
is known as Random Subspaces [3]_. Finally, when base estimators are built
on subsets of both samples and features, then the method is known as
Random Patches [4]_.

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

.. versionadded:: 0.15

Parameters
----------
estimator : object, default=None
    The base estimator to fit on random subsets of the dataset.
    If None, then the base estimator is a
    :class:`~sklearn.tree.DecisionTreeClassifier`.

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

n_estimators : int, default=10
    The number of base estimators in the ensemble.

max_samples : int or float, default=1.0
    The number of samples to draw from X to train each base estimator (with
    replacement by default, see `bootstrap` for more details).

    - If int, then draw `max_samples` samples.
    - If float, then draw `max_samples * X.shape[0]` samples.

max_features : int or float, default=1.0
    The number of features to draw from X to train each base estimator (
    without replacement by default, see `bootstrap_features` for more
    details).

    - If int, then draw `max_features` features.
    - If float, then draw `max(1, int(max_features * n_features_in_))` features.

bootstrap : bool, default=True
    Whether samples are drawn with replacement. If False, sampling
    without replacement is performed.

bootstrap_features : bool, default=False
    Whether features are drawn with replacement.

oob_score : bool, default=False
    Whether to use out-of-bag samples to estimate
    the generalization error. Only available if bootstrap=True.

warm_start : bool, default=False
    When set to True, reuse the solution of the previous call to fit
    and add more estimators to the ensemble, otherwise, just fit
    a whole new ensemble. See :term:`the Glossary <warm_start>`.

    .. versionadded:: 0.17
       *warm_start* constructor parameter.

n_jobs : int, default=None
    The number of jobs to run in parallel for both :meth:`fit` and
    :meth:`predict`. ``None`` means 1 unless in a
    :obj:`joblib.parallel_backend` context. ``-1`` means using all
    processors. See :term:`Glossary <n_jobs>` for more details.

random_state : int, RandomState instance or None, default=None
    Controls the random resampling of the original dataset
    (sample wise and feature wise).
    If the base estimator accepts a `random_state` attribute, a different
    seed is generated for each instance in the ensemble.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

verbose : int, default=0
    Controls the verbosity when fitting and predicting.

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

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

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

estimators_ : list of estimators
    The collection of fitted base estimators.

estimators_samples_ : list of arrays
    The subset of drawn samples (i.e., the in-bag samples) for each base
    estimator. Each subset is defined by an array of the indices selected.

estimators_features_ : list of arrays
    The subset of drawn features for each base estimator.

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

n_classes_ : int or list
    The number of classes.

oob_score_ : float
    Score of the training dataset obtained using an out-of-bag estimate.
    This attribute exists only when ``oob_score`` is True.

oob_decision_function_ : ndarray of shape (n_samples, n_classes)
    Decision function computed with out-of-bag estimate on the training
    set. If n_estimators is small it might be possible that a data point
    was never left out during the bootstrap. In this case,
    `oob_decision_function_` might contain NaN. This attribute exists
    only when ``oob_score`` is True.

See Also
--------
BaggingRegressor : A Bagging regressor.

References
----------

.. [1] L. Breiman, "Pasting small votes for classification in large
       databases and on-line", Machine Learning, 36(1), 85-103, 1999.

.. [2] L. Breiman, "Bagging predictors", Machine Learning, 24(2), 123-140,
       1996.

.. [3] T. Ho, "The random subspace method for constructing decision
       forests", Pattern Analysis and Machine Intelligence, 20(8), 832-844,
       1998.

.. [4] G. Louppe and P. Geurts, "Ensembles on Random Patches", Machine
       Learning and Knowledge Discovery in Databases, 346-361, 2012.

Examples
--------
>>> from sklearn.svm import SVC
>>> from sklearn.ensemble import BaggingClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=100, n_features=4,
...                            n_informative=2, n_redundant=0,
...                            random_state=0, shuffle=False)
>>> clf = BaggingClassifier(estimator=SVC(),
...                         n_estimators=10, random_state=0).fit(X, y)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
Nr   TFr   r   c       	         4   > [         TU ]  UUUUUUUUU	U
US9  g Nr   r   r   r   s               r7   r   BaggingClassifier.__init__W  8     	%#%1!% 	 	
r9   c                 H    U R                   c
  [        5       $ U R                   $ zEResolve which estimator to return (default is DecisionTreeClassifier))rf   r   r   s    r7   r    BaggingClassifier._get_estimatort  s    >>!)++~~r9   c           
         UR                   S   nU R                  n[        R                  " X445      n[	        U R
                  U R                  U R                  5       H  u  pgn[        Xs5      ) n	[        US5      (       a.  XYS S 24==   UR                  XS S 24   S S 2U4   5      -  ss'   MQ  UR                  XS S 24   S S 2U4   5      n
Sn[        U5       H#  nX   (       d  M  X\X   4==   S-  ss'   US-  nM%     M     UR                  SS9S:H  R                  5       (       a  [        S5        XUR                  SS9S S 2[        R                   4   -  n[#        U[        R$                  " USS95      nXl        Xl        g )Nr   rs   r+   axis{Some inputs do not have OOB scores. This probably means too few estimators were used to compute any reliable oob estimates.)rJ   
n_classes_rV   rt   ru   r   r   r   r   rv   rs   ry   rP   r   anyr   newaxisr   argmaxoob_decision_function_r   )r   rZ   r[   r5   r%  r   rf   samplesrh   maskpjre   oob_decision_functionr   s                  r7   r    BaggingClassifier._set_oob_scorez  so   GGAJ	__
hh	67,/d668Q8Q-
(I $G77Dy/22!G$	(?(?QwZH-) $
 %%qqz1h;&?@y)Aww#qtG,1,Q *-
( OOO#q(--//9 !,oo1o.Eam.T T"1bii!&DE	&;##r9   c                     [        USS9n[        U5        [        R                  " USS9u  U l        n[        U R                  5      U l        U$ )NTr   )return_inverse)r   r!   rV   uniquerx   rw   r%  r   s     r7   r   BaggingClassifier._validate_y  sB    &$Q'99Qt<qdmm,r9   c                     [        X S5        U R                  " U40 UD6nU R                  R                  [        R
                  " USS9SS9$ )au  Predict class for X.

The predicted class of an input sample is computed as the class with
the highest mean predicted probability. If base estimators do not
implement a ``predict_proba`` method, then it resorts to voting.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrices are accepted only if
    they are supported by the base estimator.

**params : dict
    Parameters routed to the `predict_proba` (if available) or the `predict`
    method (otherwise) of the sub-estimators via the metadata routing API.

    .. versionadded:: 1.7

        Only available if
        `sklearn.set_config(enable_metadata_routing=True)` is set. See
        :ref:`Metadata Routing User Guide <metadata_routing>` for more
        details.

Returns
-------
y : ndarray of shape (n_samples,)
    The predicted classes.
ry   r+   r"  r   )r   rs   rx   takerV   r(  )r   rZ   rI   predicted_probabilitiys       r7   ry   BaggingClassifier.predict  sK    : 	&	2!%!3!3A!@!@}}!!299-C!#LTU!VVr9   c           	        ^ ^^^ [        UT S5        [        T 5        [        T TSS/SSSS9m[        5       (       a  [	        T S40 UD6mO [        5       m[        [        5       S9Tl        [        T R                  T R                  5      u  p4m[        S
UT R                  S.T R                  5       D6" UUU U4S	 j[        U5       5       5      n[        U5      T R                  -  nU$ )a  Predict class probabilities for X.

The predicted class probabilities of an input sample is computed as
the mean predicted class probabilities of the base estimators in the
ensemble. If base estimators do not implement a ``predict_proba``
method, then it resorts to voting and the predicted class probabilities
of an input sample represents the proportion of estimators predicting
each class.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrices are accepted only if
    they are supported by the base estimator.

**params : dict
    Parameters routed to the `predict_proba` (if available) or the `predict`
    method (otherwise) of the sub-estimators via the metadata routing API.

    .. versionadded:: 1.7

        Only available if
        `sklearn.set_config(enable_metadata_routing=True)` is set. See
        :ref:`Metadata Routing User Guide <metadata_routing>` for more
        details.

Returns
-------
p : ndarray of shape (n_samples, n_classes)
    The class probabilities of the input samples. The order of the
    classes corresponds to that in the attribute :term:`classes_`.
rs   r   r   NFr   r   r   reset)rs   r   c              3   (  >#    U  H  n[        [        5      " TR                  TU   TUS -       TR                  TU   TUS -       TTR                  TR
                  R                  SS5      TR
                  R                  SS5      S9v   M     g7f)r+   ry   Nrs   )r{   r|   )r#   r   r   r   r%  rf   rN   r   re   rZ   r   r   r   s     r7   r   2BaggingClassifier.predict_proba.<locals>.<genexpr>  s      


 # +,  VAE];))&)fQUmD,66::9dK%2%<%<%@%@RV%W #s   BBr   )r   r(   r*   r   r   r   rf   r-   rX   r   r"   r^   r   rP   r   )	r   rZ   rI   r   r   	all_probar}   r   r   s	   ``     @@r7   rs   BaggingClassifier.predict_proba  s    B 	&$8 %.#
 +D/LVLM!GM&+%'&BM# 2$2C2CT[[Q6 
4<<
373F3F3H



 6]



	 I!2!22r9   c           	        ^ ^^^	 [        UT S5        [        T 5        [        T R                  S5      (       a  [	        T TSS/SSSS9m[        5       (       a  [        T S40 UD6mO [        5       m[        [        5       S9Tl        [        T R                  T R                  5      u  p4m	[        UT R                  S9" UUU U	4S	 j[        U5       5       5      nUS
   n[        S[        U5      5       H  n[         R"                  " XeU   5      nM     U[         R$                  " T R                  5      -  nU$ [         R$                  " T R&                  " T40 UD65      nU$ )aN  Predict class log-probabilities for X.

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrices are accepted only if
    they are supported by the base estimator.

**params : dict
    Parameters routed to the `predict_log_proba`, the `predict_proba` or the
    `proba` method of the sub-estimators via the metadata routing API. The
    routing is tried in the mentioned order depending on whether this method is
    available on the sub-estimator.

    .. versionadded:: 1.7

        Only available if
        `sklearn.set_config(enable_metadata_routing=True)` is set. See
        :ref:`Metadata Routing User Guide <metadata_routing>` for more
        details.

Returns
-------
p : ndarray of shape (n_samples, n_classes)
    The class log-probabilities of the input samples. The order of the
    classes corresponds to that in the attribute :term:`classes_`.
r   r   r   NFr9  )r   r   c           	   3      >#    U  Hf  n[        [        5      " TR                  TU   TUS -       TR                  TU   TUS -       TTR                  TR
                  R                  S9v   Mh     g7fr+   )rI   N)r#   r   r   r   r%  rf   r   r<  s     r7   r   6BaggingClassifier.predict_log_proba.<locals>.<genexpr>M  sy      	J 'A 34$$VAYA?--fQi&Q-HOO(22DD 's   A.A1r   r+   )r   r(   rv   rM   r*   r   r   r   rf   r-   rX   r   r"   r^   rP   rw   rV   r   logrs   )
r   rZ   rI   r   r   all_log_probar   r-  r   r   s
   ``      @@r7   r   #BaggingClassifier.predict_log_proba  sE   @ 	&$(;<4??$788$en"'A  !! /6I TV T %*/%'*J' !6d6G6G UFv$FDLLI 	J v	J 	M &a(I1c-01LL!4DE	 2  1 122I
  t11!>v>?Ir9   r   )r   rf   )	delegatesc           	        ^ ^^^ [        UT S5        [        T 5        [        T TSS/SSSS9m[        5       (       a  [	        T S40 UD6mO [        5       m[        [        5       S9Tl        [        T R                  T R                  5      u  p4m[        UT R                  S9" UUU U4S	 j[        U5       5       5      n[        U5      T R                  -  nU$ )
a  Average of the decision functions of the base classifiers.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrices are accepted only if
    they are supported by the base estimator.

**params : dict
    Parameters routed to the `decision_function` method of the sub-estimators
    via the metadata routing API.

    .. versionadded:: 1.7

        Only available if
        `sklearn.set_config(enable_metadata_routing=True)` is set. See
        :ref:`Metadata Routing User Guide <metadata_routing>` for more
        details.

Returns
-------
score : ndarray of shape (n_samples, k)
    The decision function of the input samples. The columns correspond
    to the classes in sorted order, as they appear in the attribute
    ``classes_``. Regression and binary classification are special
    cases with ``k == 1``, otherwise ``k==n_classes``.
r   r   r   NFr9  r   r   c           	   3      >#    U  H[  n[        [        5      " TR                  TU   TUS -       TR                  TU   TUS -       TTR                  R
                  S9v   M]     g7frB  )r#   r   r   r   rf   r   r<  s     r7   r   6BaggingClassifier.decision_function.<locals>.<genexpr>  sr      F
 # /0  VAE];))&)fQUmD$..@@	 #   A#A&r   r(   r*   r   r   r   rf   r-   rX   r   r"   r^   rP   r   )	r   rZ   rI   r   r   all_decisions	decisionsr   r   s	   ``     @@r7   r   #BaggingClassifier.decision_functione  s    > 	&$(;<  %.#
 +D2EPPM!GM&+eg&FM# 2$2C2CT[[Q6 E F
 6]F
 
 &):)::	r9   )rx   r%  r)  r   r  )r   r  r  r  r  r   r   r   r   ry   rs   r   r    r'   r   r  r  r  s   @r7   r.   r.     s    eR 

  
 
:%$N WDHTN` *6RS@@r9   c                   ^   ^  \ rS rSrSr  SSSSSSSSSSS.	U 4S	 jjjrS
 rS rS rSr	U =r
$ )r/   i  a  A Bagging regressor.

A Bagging regressor is an ensemble meta-estimator that fits base
regressors each on random subsets of the original dataset and then
aggregate their individual predictions (either by voting or by averaging)
to form a final prediction. Such a meta-estimator can typically be used as
a way to reduce the variance of a black-box estimator (e.g., a decision
tree), by introducing randomization into its construction procedure and
then making an ensemble out of it.

This algorithm encompasses several works from the literature. When random
subsets of the dataset are drawn as random subsets of the samples, then
this algorithm is known as Pasting [1]_. If samples are drawn with
replacement, then the method is known as Bagging [2]_. When random subsets
of the dataset are drawn as random subsets of the features, then the method
is known as Random Subspaces [3]_. Finally, when base estimators are built
on subsets of both samples and features, then the method is known as
Random Patches [4]_.

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

.. versionadded:: 0.15

Parameters
----------
estimator : object, default=None
    The base estimator to fit on random subsets of the dataset.
    If None, then the base estimator is a
    :class:`~sklearn.tree.DecisionTreeRegressor`.

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

n_estimators : int, default=10
    The number of base estimators in the ensemble.

max_samples : int or float, default=1.0
    The number of samples to draw from X to train each base estimator (with
    replacement by default, see `bootstrap` for more details).

    - If int, then draw `max_samples` samples.
    - If float, then draw `max_samples * X.shape[0]` samples.

max_features : int or float, default=1.0
    The number of features to draw from X to train each base estimator (
    without replacement by default, see `bootstrap_features` for more
    details).

    - If int, then draw `max_features` features.
    - If float, then draw `max(1, int(max_features * n_features_in_))` features.

bootstrap : bool, default=True
    Whether samples are drawn with replacement. If False, sampling
    without replacement is performed.

bootstrap_features : bool, default=False
    Whether features are drawn with replacement.

oob_score : bool, default=False
    Whether to use out-of-bag samples to estimate
    the generalization error. Only available if bootstrap=True.

warm_start : bool, default=False
    When set to True, reuse the solution of the previous call to fit
    and add more estimators to the ensemble, otherwise, just fit
    a whole new ensemble. See :term:`the Glossary <warm_start>`.

n_jobs : int, default=None
    The number of jobs to run in parallel for both :meth:`fit` and
    :meth:`predict`. ``None`` means 1 unless in a
    :obj:`joblib.parallel_backend` context. ``-1`` means using all
    processors. See :term:`Glossary <n_jobs>` for more details.

random_state : int, RandomState instance or None, default=None
    Controls the random resampling of the original dataset
    (sample wise and feature wise).
    If the base estimator accepts a `random_state` attribute, a different
    seed is generated for each instance in the ensemble.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

verbose : int, default=0
    Controls the verbosity when fitting and predicting.

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

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

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

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

estimators_samples_ : list of arrays
    The subset of drawn samples (i.e., the in-bag samples) for each base
    estimator. Each subset is defined by an array of the indices selected.

estimators_features_ : list of arrays
    The subset of drawn features for each base estimator.

oob_score_ : float
    Score of the training dataset obtained using an out-of-bag estimate.
    This attribute exists only when ``oob_score`` is True.

oob_prediction_ : ndarray of shape (n_samples,)
    Prediction computed with out-of-bag estimate on the training
    set. If n_estimators is small it might be possible that a data point
    was never left out during the bootstrap. In this case,
    `oob_prediction_` might contain NaN. This attribute exists only
    when ``oob_score`` is True.

See Also
--------
BaggingClassifier : A Bagging classifier.

References
----------

.. [1] L. Breiman, "Pasting small votes for classification in large
       databases and on-line", Machine Learning, 36(1), 85-103, 1999.

.. [2] L. Breiman, "Bagging predictors", Machine Learning, 24(2), 123-140,
       1996.

.. [3] T. Ho, "The random subspace method for constructing decision
       forests", Pattern Analysis and Machine Intelligence, 20(8), 832-844,
       1998.

.. [4] G. Louppe and P. Geurts, "Ensembles on Random Patches", Machine
       Learning and Knowledge Discovery in Databases, 346-361, 2012.

Examples
--------
>>> from sklearn.svm import SVR
>>> from sklearn.ensemble import BaggingRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_samples=100, n_features=4,
...                        n_informative=2, n_targets=1,
...                        random_state=0, shuffle=False)
>>> regr = BaggingRegressor(estimator=SVR(),
...                         n_estimators=10, random_state=0).fit(X, y)
>>> regr.predict([[0, 0, 0, 0]])
array([-2.8720])
Nr   TFr   r   c       	         4   > [         TU ]  UUUUUUUUU	U
US9  g r  r  r   s               r7   r   BaggingRegressor.__init__J  r  r9   c           	        ^ ^^^ [        UT S5        [        T 5        [        T TSS/SSSS9m[        5       (       a  [	        T S40 UD6mO [        5       m[        [        5       S9Tl        [        T R                  T R                  5      u  p4m[        UT R                  S9" UUU U4S	 j[        U5       5       5      n[        U5      T R                  -  nU$ )
a  Predict regression target for X.

The predicted regression target of an input sample is computed as the
mean predicted regression targets of the estimators in the ensemble.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Sparse matrices are accepted only if
    they are supported by the base estimator.

**params : dict
    Parameters routed to the `predict` method of the sub-estimators via the
    metadata routing API.

    .. versionadded:: 1.7

        Only available if
        `sklearn.set_config(enable_metadata_routing=True)` is set. See
        :ref:`Metadata Routing User Guide <metadata_routing>` for more
        details.

Returns
-------
y : ndarray of shape (n_samples,)
    The predicted values.
ry   r   r   NFr9  r   r   c           	   3      >#    U  H[  n[        [        5      " TR                  TU   TUS -       TR                  TU   TUS -       TTR                  R
                  S9v   M]     g7frB  )r#   r   r   r   rf   ry   r<  s     r7   r   +BaggingRegressor.predict.<locals>.<genexpr>  sr      B
 # 01  VAE];))&)fQUmD$..66	 #rK  rL  )	r   rZ   rI   r   r   	all_y_haty_hatr   r   s	   ``     @@r7   ry   BaggingRegressor.predictg  s    8 	&$	2 %.#
 +D)FvFM!GM&+EG&<M# 2$2C2CT[[Q6FDLLA B
 6]B
 
	 I!2!22r9   c           
         UR                   S   n[        R                  " U45      n[        R                  " U45      n[        U R                  U R
                  U R                  5       HF  u  pgn[        Xs5      ) n	XI==   UR                  XS S 24   S S 2U4   5      -  ss'   XY==   S-  ss'   MH     US:H  R                  5       (       a  [        S5        SXUS:H  '   XE-  nX@l        [        X$5      U l        g )Nr   r+   r$  )rJ   rV   rt   ru   r   r   r   r   ry   r&  r   oob_prediction_r   r   )
r   rZ   r[   r5   r   n_predictionsrf   r*  rh   r+  s
             r7   r   BaggingRegressor._set_oob_score  s    GGAJ	hh	|,).,/d668Q8Q-
(I $G77D!2!2AAgJ83L!MM1$-
 Q##%%9
 12M1,-$*"12r9   c                 H    U R                   c
  [        5       $ U R                   $ r  )rf   r   r   s    r7   r   BaggingRegressor._get_estimator  s    >>!(**~~r9   )rZ  r   r  )r   r  r  r  r  r   ry   r   r   r  r  r  s   @r7   r/   r/     sS    \@ 

  
 
:?B38 r9   )NN)Mr  r   r   abcr   r   	functoolsr   r   warningsr   numpyrV   baser
   r   r   metricsr   r   treer   r   utilsr   r   r   r   utils._maskr   utils._param_validationr   r   r   utils._tagsr   utils.metadata_routingr   r   r   r   r   r   utils.metaestimatorsr    utils.multiclassr!   utils.parallelr"   r#   utils.randomr$   utils.validationr%   r&   r'   r(   r)   r*   _baser,   r-   __all__iinfoint32r   r   r8   rB   rq   r   r   r   r   r   r.   r/   r   r9   r7   <module>rt     s    
   '     @ @ . @  * F F "  0 ; . 5  7 2
3
((288

 
 
+0m+j #L2R,' Rjy yx]~{ ]r9   