
    >[g                        d Z ddlZddlZddlmZmZ ddlmZ ddlmZ ddl	m
Z
 ddlZddl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 ddlmZ ddlmZm Z m!Z! ddl"m#Z# ddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<m=Z=m>Z> ddgZ? ej                  ej                        j                  ZCd ZDd ZEd ZFd ZGd ZHd ZId ZJ G d  d!e=e"      ZK G d# deeK      ZL G d$ deeK      ZMy)%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_deprecate_positional_args_estimator_hascheck_is_fittedhas_fit_parametervalidate_data   )BaseEnsemble_partition_estimatorsBaggingClassifierBaggingRegressorc                 P    |r| j                  d||      }|S t        |||       }|S )zDraw randomly sampled indices.r   )random_state)randintr$   )r2   	bootstrapn_population	n_samplesindicess        T/var/www/html/bid-api/venv/lib/python3.12/site-packages/sklearn/ensemble/_bagging.py_generate_indicesr9   8   s<     &&q,	B N	 -),
 N    c                 X    t        |       } t        | |||      }t        | |||      }||fS )z)Randomly draw feature and sample indices.)r   r9   )	r2   bootstrap_featuresbootstrap_samples
n_featuresr6   max_featuresmax_samplesfeature_indicessample_indicess	            r8   _generate_bagging_indicesrC   E   sG     &l3L ((*lO ''KN N**r:   c	           
      z   |j                   \  }	}
|j                  }|j                  }|j                  }|j                  }t        |j                  d      }|xs ||
k7  }g }g }t        |j                  d      }t               s|s|j                  d      t        d      t        |       D ]  }|dkD  rt        d|dz   | |fz         ||   }|j                  d|      }|rt        |j                  |	      }n|j                  }t        ||||
|	||      \  }}|j!                         }t               r(t#        |j                        }|j%                  d
d      }n|}|rxt'        |j)                  dd      |      j!                         }|rt+        j,                  ||	      }||z  }nt/        ||	       }d||<   ||d<   |r	|dd|f   n|}  || |fi | n;t1        ||      }!t1        ||      } t3        |||      }|r	| dd|f   }  || |!fi | |j5                  |       |j5                  |        ||fS )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)appendr2   )rE   fitrF   )	minlengthr   )paramsr7   )shape_max_features_max_samplesr4   r<   r*   
estimator_r   get
ValueErrorrangeprint_make_estimatorr   rH   rC   copyr   consumesr&   popnpbincountr   r   r%   rG   )"n_estimatorsensembleXyseedstotal_n_estimatorsverboserE   
fit_paramsr6   r>   r?   r@   r4   r<   has_check_inputrequires_feature_indexing
estimatorsestimators_featuressupport_sample_weightir2   	estimatorestimator_fitfeaturesr7   fit_params_request_or_routerconsumes_sample_weightcurr_sample_weightsample_countsnot_indices_maskX_y_s"                                     r8   _parallel_build_estimatorsrs   ]   s    GGIz))L''K""I!44'(;(;]KO 2 Plj6P 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 ***r:   c                    |j                   d   }t        j                  ||f      }t        | |      D ]  \  }}t	        |d      ru|j                  |dd|f         }|t        |j                        k(  r||z  }H|dd|j                  fxx   |ddt        t        |j                              f   z  cc<   |j                  |dd|f         }	t        |      D ]  }
||
|	|
   fxx   dz  cc<     |S )zBPrivate function used to compute (proba-)predictions within a job.r   predict_probaNr,   )
rL   rX   zerosziphasattrru   lenclasses_rR   predict)rd   re   r\   	n_classesr6   probarh   rj   proba_estimatorpredictionsrg   s              r8   _parallel_predict_probar      s    
IHHi+,E":/BC	89o.'55a8nEOC	 2 233( a+++,uS!3!34551 , $++AakN;K9%aQ'(A-( &!  D& Lr:   c                    |j                   d   }t        j                  ||f      }|j                  t        j                          t        j
                  |t              }t        | |      D ]  \  }}|j                  |dd|f         }	|t        |j                        k(  rt        j                  ||	      }Mt        j                  |dd|j                  f   |	ddt        t        |j                              f         |dd|j                  f<   t        j                  ||j                        }
t        j                  |dd|
f   t        j                         |dd|
f<    |S )z@Private function used to compute log probabilities within a job.r   dtypeN)rL   rX   emptyfillinfarangeintrw   predict_log_probary   rz   	logaddexprR   	setdiff1d)rd   re   r\   r|   r6   	log_probaall_classesrh   rj   log_proba_estimatormissings              r8   _parallel_predict_log_probar      s1   
I)Y/0INNBFF7))IS1K":/BC	8'99!AxK.II..//Y0CDI 02||!Y///0#AuS1C1C-D'E$EF0Ia+++,
 ll;	0B0BCG$&LL1g:1F$PIaj!  D r:   c                 @    t        fdt        | |      D              S )z8Private function used to compute decisions within a job.c              3   T   K   | ]  \  }}|j                  d d |f          ! y wN)decision_function.0rh   rj   r\   s      r8   	<genexpr>z._parallel_decision_function.<locals>.<genexpr>  s1      #GIx 	##AakN3#G   %(sumrw   rd   re   r\   s     `r8   _parallel_decision_functionr     %     #&z3F#G  r:   c                 @    t        fdt        | |      D              S )z:Private function used to compute predictions within a job.c              3   T   K   | ]  \  }}|j                  d d |f          ! y wr   )r{   r   s      r8   r   z/_parallel_predict_regression.<locals>.<genexpr>  s1      #GIx 	!AxK.)#Gr   r   r   s     `r8   _parallel_predict_regressionr   	  r   r:   c                       e Zd ZU dZ eddg      dg eeddd      g eeddd       eeddd	      g eeddd       eeddd	      gd
gd
gd
gd
gdegdgdgdZe	e
d<   e	 	 d"dddddddddd	 fd       Z ed       ed      ddd              Zd Z	 	 	 d#dZed        Zd Zd Zed        Zd Zed         Z fd!Z xZS )$BaseBaggingzBase class for Bagging meta-estimator.

    Warning: This class should not be used directly. Use derived classes
    instead.
    rH   r{   Nr,   left)closedr   rightbooleanr2   r`   rh   rZ   r@   r?   r4   r<   	oob_score
warm_startn_jobsr2   r`   _parameter_constraints      ?TF	r@   r?   r4   r<   r   r   r   r2   r`   c       	             t         |   ||       || _        || _        || _        || _        || _        || _        |	| _        |
| _	        || _
        y )N)rh   rZ   )super__init__r@   r?   r4   r<   r   r   r   r2   r`   selfrh   rZ   r@   r?   r4   r<   r   r   r   r2   r`   	__class__s               r8   r   zBaseBagging.__init__,  sb      	% 	 	
 '(""4"$(r:   z1.7)version)prefer_skip_nested_validationrI   c          	          t        || d       t        | ||ddgddd      \  }}|t        ||d      }||d	<    | j                  ||fd
| j                  i|S )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.
        rH   csrcscNFT)accept_sparser   ensure_all_finitemulti_outputr   rF   r@   )r   r+   r&   _fitr@   )r   r\   r]   rF   ra   s        r8   rH   zBaseBagging.fitM  s}    N 	*dE2  %.#
1 $0NM*7J'tyyAJ4+;+;JzJJr:   c                     i S r    r   s    r8   _parallel_argszBaseBagging._parallel_args  s    	r:   c                 z    t         j                        }j                  d   }| _         j	                         j                   j                                t               rt         dfi |n;t               t        |      _
        d|v r|d   j                  j                  d<   || j                  _        | j                  }n5t        |t         j"                        st%        |j                  d   z        }|j                  d   kD  rt'        d      | _        t         j*                  t         j"                        r j*                  }	n<t         j*                  t,              r"t%         j*                   j.                  z        }		 j.                  kD  rt'        d      t1        dt%        |	            }	|	 _         j4                  s j6                  rt'        d       j8                  r j6                  rt'        d	      t;         d
      r j8                  r ` j8                  rt;         d      sg  _        g  _          jB                  tE         j>                        z
  }
|
dk  r-t'        d jB                  tE         j>                        fz        |
dk(  rtG        d        S tI        |
 jJ                        \  }tM               j8                  rBtE         j>                        dkD  r*|jO                  tP        tE         j>                               |jO                  tP        |
       _)         tU        d| jV                  d jY                          f	dt[        |      D              } xj>                  t]        t^        j`                  jc                  d |D                    z  c_         xj@                  t]        t^        j`                  jc                  d |D                    z  c_          j6                  r je                          S )a0  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.

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

        Returns
        -------
        self : object
            Fitted estimator.
        r   rH   )rH   rF   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      	K   | ]O  } t        t              |   
|   |d z       	j                  j                  j                  	       Q yw)r,   )r`   rE   ra   N)r#   rs   r`   rh   rH   )r   rg   r\   rE   rZ   routed_paramsr^   r   startsr_   r]   s     r8   r   z#BaseBagging._fit.<locals>.<genexpr>  sq      

 # 0G./QfQi&Q-0"'(2266
 
 #s   AAc              3   &   K   | ]	  }|d      yw)r   Nr   r   ts     r8   r   z#BaseBagging._fit.<locals>.<genexpr>'       )D1!A$   c              3   &   K   | ]	  }|d      ywr,   Nr   r   s     r8   r   z#BaseBagging._fit.<locals>.<genexpr>*  r   r   r   )3r   r2   rL   
_n_samples_validate_y_validate_estimator_get_estimatorr   r   r   rh   rH   rO   	max_depthr@   
isinstancenumbersr   r   rQ   rN   r?   floatn_features_in_maxrM   r4   r   r   rx   r   r   estimators_features_rZ   ry   r   r.   r   r   r3   MAX_INT_seedsr"   r`   r   rR   list	itertoolschainfrom_iterable_set_oob_score)r   r\   r]   r@   r   rE   ra   r2   r6   r?   n_more_estimatorsr   all_resultsrZ   r   r^   r   r_   s   ```  `       @@@@@r8   r   zBaseBagging._fit  s   X *$*;*;< GGAJ	#Q 	  !4!4!67+D%F:FM!GM&+
&;M#*,?I#@''++O<  (1DOO% **KK)9)9:kAGGAJ67K#?@@ ( d'')9)9:,,L))51t0043F3FFGL$---ABB1c,/0 * ~~$..UVV??t~~UVV4&4??gdM&B!D(*D% --D4D4D0EEq <$$c$*:*:&;<=  !#! K (=t{{(
$f !. ??s4#3#34q8  s43C3C/D E$$W3D$E
h 
4<<
373F3F3H


 

 6]


$ 	DOO)))D)DD
 	
 	!!TOO)))D)DD&
 	
! >>1%r:   c                      y)z+Calculate out of bag predictions and score.Nr   )r   r\   r]   s      r8   r   zBaseBagging._set_oob_score2      r:   c                 t    t        |j                        dk(  s|j                  d   dk(  rt        |d      S |S )Nr,   Tr   )ry   rL   r   r   r]   s     r8   r   zBaseBagging._validate_y6  s2    qww<1
a--r:   c           
   #      K   | j                   D ]X  }t        || j                  | j                  | j                  | j
                  | j                  | j                        \  }}||f Z y wr   )r   rC   r<   r4   r   r   rM   rN   )r   seedrA   rB   s       r8   _get_estimators_indicesz#BaseBagging._get_estimators_indices;  sh     KKD /H''##""!!/+O^ ">11  s   A)A+c                 T    | j                         D cg c]  \  }}|	 c}}S c c}}w )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   _rB   s      r8   estimators_samples_zBaseBagging.estimators_samples_L  s,     9=8T8T8VW8V#41n8VWWWs   $c                     t        | j                  j                        }|j                  | j	                         t               j                  dd             |S )aj  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.
        )ownerrH   )calleecaller)rh   method_mapping)r   r   __name__addr   r   )r   routers     r8   get_metadata_routingz BaseBagging.get_metadata_routing[  sQ      dnn&=&=>

))+(?..eE.J 	 	
 r:   c                      y)z"Resolve which estimator to return.Nr   r   s    r8   r   zBaseBagging._get_estimatorp  r   r:   c                     t         |          }t        | j                               j                  j
                  |j                  _        |S r   )r   __sklearn_tags__r   r   
input_tags	allow_nan)r   tagsr   s     r8   r   zBaseBagging.__sklearn_tags__t  s;    w')$,T-@-@-B$C$N$N$X$X!r:   N
   )NNT)r   
__module____qualname____doc__r   r   r   r   r   dict__annotations__r   r   r'   r   rH   r   r   r   r   r   propertyr   r   r   r   __classcell__r   s   @r8   r   r     s    !%!34d;!(AtFCDXq$v6ZAg6

 Xq$v6ZAg6
  [(k[ k"'(;#$D (  
   @  .&+ *. 3K	 /
3Kj fP : :
2" X X* 1 1 r:   r   )	metaclassc                        e Zd ZdZ	 	 ddddddddddd	 fdZd	 Zd
 Zd Zd Zd Z	d Z
 e edd            d        Z xZS )r/   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       	         :    t         |   |||||||||	|
|       y Nr   r   r   r   s               r8   r   zBaggingClassifier.__init__"  8     	%#%1!% 	 	
r:   c                 F    | j                   
t               S | j                   S zEResolve which estimator to return (default is DecisionTreeClassifier))rh   r   r   s    r8   r   z BaggingClassifier._get_estimator?  s    >>!)++~~r:   c           
      
   |j                   d   }| j                  }t        j                  ||f      }t	        | j
                  | j                  | j                        D ]  \  }}}t        ||       }	t        |d      r/||	d d fxx   |j                  ||	d d f   d d |f         z  cc<   O|j                  ||	d d f   d d |f         }
d}t        |      D ]  }|	|   s	|||
|   fxx   dz  cc<   |dz  }!  |j                  d      dk(  j                         rt        d       ||j                  d      d d t        j                   f   z  }t#        |t        j$                  |d            }|| _        || _        y )Nr   ru   r,   axis{Some inputs do not have OOB scores. This probably means too few estimators were used to compute any reliable oob estimates.)rL   
n_classes_rX   rv   rw   r   r   r   r   rx   ru   r{   rR   r   anyr   newaxisr   argmaxoob_decision_function_r   )r   r\   r]   r6   r  r   rh   samplesrj   maskpjrg   oob_decision_functionr   s                  r8   r   z BaggingClassifier._set_oob_scoreE  s   GGAJ	__
hh	:67,/d668Q8Q-
(Iw $GY77Dy/2D!G$	(?(?tQwZH-) $
 %%qqz1h;&?@y)AAw#AqtG,1,Q *-
( OOO#q(--/9 !,koo1o.Eam.T T"1bii!&DE	&;##r:   c                     t        |d      }t        |       t        j                  |d      \  | _        }t        | j                        | _        |S )NTr   )return_inverse)r   r!   rX   uniquerz   ry   r  r   s     r8   r   zBaggingClassifier._validate_yl  sB    &$Q'99Qt<qdmm,r:   c                     | j                  |      }| j                  j                  t        j                  |d      d      S )a_  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.

        Returns
        -------
        y : ndarray of shape (n_samples,)
            The predicted classes.
        r,   r  r   )ru   rz   takerX   r  )r   r\   predicted_probabilitiys      r8   r{   zBaggingClassifier.predictt  s<    $ "&!3!3A!6}}!!299-C!#LTU!VVr:   c                 @    t                t         ddgddd      t         j                   j                        \  }} t        d| j                  d j                          fdt        |      D              }t        |       j                  z  }|S )	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.

        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_`.
        r   r   NFr   r   r   resetr   c           	   3      K   | ]R  } t        t              j                  |   |d z       j                  |   |d z       j                         T ywr   )r#   r   r   r   r  r   rg   r\   r   r   s     r8   r   z2BaggingClassifier.predict_proba.<locals>.<genexpr>  sl      

 # -G+,  VAE];))&)fQUmD	 #   AAr   )
r)   r+   r.   rZ   r   r"   r`   r   rR   r   )r   r\   r   r   	all_probar}   r   s   ``    @r8   ru   zBaggingClassifier.predict_proba  s    , 	 %.#
 2$2C2CT[[Q6
H 
4<<
373F3F3H


 6]



	 I!2!22r:   c                     t                t         j                  d      rt         ddgddd      t	         j
                   j                        \  }} t        | j                         fdt        |      D              }|d	   }t        d
t        |            D ]  }t        j                  |||         } |t        j                   j
                        z  }|S t        j                   j                              }|S )a  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.

        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   NFr$  r   c           	   3      K   | ]R  } t        t              j                  |   |d z       j                  |   |d z       j                         T ywr   )r#   r   r   r   r  r'  s     r8   r   z6BaggingClassifier.predict_log_proba.<locals>.<genexpr>  sm      J 'A 534$$VAYA?--fQi&Q-HOO	 'r(  r   r,   )r)   rx   rO   r+   r.   rZ   r   r"   r`   rR   ry   rX   r   logru   )r   r\   r   r   all_log_probar   r  r   s   ``     @r8   r   z#BaggingClassifier.predict_log_proba  s   & 	4??$78$en"'A !6d6G6G UFAvIHFDLLI J vJ M &a(I1c-01LLM!4DE	 2  1 122I
  t11!45Ir:   r   )r   rh   )	delegatesc                 "    t                t         ddgddd      t         j                   j                        \  }} t        | j                         fdt        |      D              }t        |       j                  z  }|S )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.

        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   NFr$  r   c           	   3      K   | ]G  } t        t              j                  |   |d z       j                  |   |d z              I ywr   )r#   r   r   r   r'  s     r8   r   z6BaggingClassifier.decision_function.<locals>.<genexpr>  sf      F
 # 1G/0  VAE];))&)fQUmD
 #   AA	r)   r+   r.   rZ   r   r"   r`   rR   r   )r   r\   r   r   all_decisions	decisionsr   s   ``    @r8   r   z#BaggingClassifier.decision_function  s    ( 	  %.#
 2$2C2CT[[Q6EE F
 6]F
 
 &):)::	r:   r   )r   r   r   r  r   r   r   r   r{   ru   r   r    r(   r   r  r  s   @r8   r/   r/   z  s    eR 

  
:%$NW*3j7r *6RS,,r:   c                   P     e Zd ZdZ	 	 ddddddddddd	 fdZd	 Zd
 Zd Z xZS )r0   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       	         :    t         |   |||||||||	|
|       y r
  r  r   s               r8   r   zBaggingRegressor.__init__  r  r:   c                 "    t                t         ddgddd      t         j                   j                        \  }} t        | j                         fdt        |      D              }t        |       j                  z  }|S )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.

        Returns
        -------
        y : ndarray of shape (n_samples,)
            The predicted values.
        r   r   NFr$  r   c           	   3      K   | ]G  } t        t              j                  |   |d z       j                  |   |d z              I ywr   )r#   r   r   r   r'  s     r8   r   z+BaggingRegressor.predict.<locals>.<genexpr>  sf      B
 # 2G01  VAE];))&)fQUmD
 #r1  r2  )r   r\   r   r   	all_y_haty_hatr   s   ``    @r8   r{   zBaggingRegressor.predict  s    " 	 %.#
 2$2C2CT[[Q6AHFDLLA B
 6]B
 
	 I!2!22r:   c           
         |j                   d   }t        j                  |f      }t        j                  |f      }t        | j                  | j
                  | j                        D ]J  \  }}}t        ||       }	||	xx   |j                  ||	d d f   d d |f         z  cc<   ||	xx   dz  cc<   L |dk(  j                         rt        d       d||dk(  <   ||z  }|| _        t        ||      | _        y )Nr   r,   r  )rL   rX   rv   rw   r   r   r   r   r{   r  r   oob_prediction_r   r   )
r   r\   r]   r6   r   n_predictionsrh   r  rj   r  s
             r8   r   zBaggingRegressor._set_oob_score  s    GGAJ	hh	|,).,/d668Q8Q-
(Iw $GY77D!2!2AdAgJ83L!MM$1$-
 Q##%9
 12M-1,-}$*"1k2r:   c                 F    | j                   
t               S | j                   S r  )rh   r   r   s    r8   r   zBaggingRegressor._get_estimator.  s    >>!(**~~r:   r   )	r   r   r   r  r   r{   r   r   r  r  s   @r8   r0   r0   )  sI    \@ 

  
:+Z38r:   )Nr  r   r   abcr   r   	functoolsr   r   warningsr   numpyrX   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*   r+   _baser-   r.   __all__iinfoint32r   r   r9   rC   rs   r   r   r   r   r   r/   r0   r   r:   r8   <module>rT     s       '     @ @ . @  * F F "  0 ; . 5   7 2
3
"((288

 
 
+0m+`62f,' fRl l^I~{ Ir:   