
    -i                       S r SSKrSSKJrJr  SSKJrJr  SSKJ	r	J
r
Jr  SSKrSSK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Jr  SSKJr  SSK J!r!J"r"J#r#J$r$J%r%  SSK&J'r'J(r(  SSK)J*r*J+r+  SSK,J-r-J.r.J/r/  SSK0J1r1  SSK2J3r3J4r4  SSK5J6r6J7r7  SSK8J9r9J:r:J;r;J<r<J=r=  SSK>J?r?J@r@  / SQrA\R                  " \R                  5      R                  rES rFS rGS rH    S.S jrI " S S\\?\S9rJS rK " S  S!\\J\S9rL " S" S#\\J\S9rM " S$ S%\L5      rN " S& S'\M5      rO " S( S)\L5      rP " S* S+\M5      rQ " S, S-\\J5      rRg)/a2  
Forest of trees-based ensemble methods.

Those methods include random forests and extremely randomized trees.

The module structure is the following:

- The ``BaseForest`` base class implements a common ``fit`` method for all
  the estimators in the module. The ``fit`` method of the base ``Forest``
  class calls the ``fit`` method of each sub-estimator on random samples
  (with replacement, a.k.a. bootstrap) of the training set.

  The init of the sub-estimator is further delegated to the
  ``BaseEnsemble`` constructor.

- The ``ForestClassifier`` and ``ForestRegressor`` base classes further
  implement the prediction logic by computing an average of the predicted
  outcomes of the sub-estimators.

- The ``RandomForestClassifier`` and ``RandomForestRegressor`` derived
  classes provide the user with concrete implementations of
  the forest ensemble method using classical, deterministic
  ``DecisionTreeClassifier`` and ``DecisionTreeRegressor`` as
  sub-estimator implementations.

- The ``ExtraTreesClassifier`` and ``ExtraTreesRegressor`` derived
  classes provide the user with concrete implementations of the
  forest ensemble method using the extremely randomized trees
  ``ExtraTreeClassifier`` and ``ExtraTreeRegressor`` as
  sub-estimator implementations.

Single and multi-output problems are both handled.
    N)ABCMetaabstractmethod)IntegralReal)catch_warningssimplefilterwarn)hstack)issparse   )ClassifierMixinMultiOutputMixinRegressorMixinTransformerMixin_fit_contextis_classifier)DataConversionWarning)accuracy_scorer2_score)OneHotEncoder)BaseDecisionTreeDecisionTreeClassifierDecisionTreeRegressorExtraTreeClassifierExtraTreeRegressor)DOUBLEDTYPE)check_random_statecompute_sample_weight)Interval
RealNotInt
StrOptions)get_tags)check_classification_targetstype_of_target)Paralleldelayed)_check_feature_names_in_check_sample_weight_num_samplescheck_is_fittedvalidate_data   )BaseEnsemble_partition_estimators)ExtraTreesClassifierExtraTreesRegressorRandomForestClassifierRandomForestRegressorRandomTreesEmbeddingc                     Uc  U $ [        U[        5      (       a#  X:  a  Sn[        UR                  X5      5      eU$ [        U[        5      (       a  [        [        X-  5      S5      $ g)a6  
Get the number of samples in a bootstrap sample.

Parameters
----------
n_samples : int
    Number of samples in the dataset.
max_samples : int or float
    The maximum number of samples to draw from the total available:
        - if float, this indicates a fraction of the total and should be
          the interval `(0.0, 1.0]`;
        - if int, this indicates the exact number of samples;
        - if None, this indicates the total number of samples.

Returns
-------
n_samples_bootstrap : int
    The total number of samples to draw for the bootstrap sample.
Nz6`max_samples` must be <= n_samples={} but got value {}r-   )
isinstancer   
ValueErrorformatr   maxround)	n_samplesmax_samplesmsgs      K/var/www/html/venv/lib/python3.13/site-packages/sklearn/ensemble/_forest.py_get_n_samples_bootstrapr?   [   si    ( +x(("JCSZZ	?@@+t$$501155 %    c                 Z    [        U 5      nUR                  SX[        R                  S9nU$ )z9
Private function used to _parallel_build_trees function.r   dtype)r   randintnpint32)random_stater;   n_samples_bootstraprandom_instancesample_indicess        r>   _generate_sample_indicesrK   |   s6     )6O$,,	9 - N r@   c                     [        XU5      n[        R                  " X1S9nUS:H  n[        R                  " U5      nXe   nU$ )z9
Private function used to forest._set_oob_score function.	minlengthr   )rK   rE   bincountarange)rG   r;   rH   rJ   sample_countsunsampled_maskindices_rangeunsampled_indicess           r>   _generate_unsampled_indicesrU      sK     .!4N KKDM"a'NIIi(M%5r@   c                 6   US:  a  [        SUS-   U4-  5        U(       a  UR                  S   nUc%  [        R                  " U4[        R                  S9nOUR                  5       n[        U R                  X5      n[        R                  " XS9nX-  nUS:X  a1  [        5          [        S[        5        U[        S	X=S
9-  nSSS5        OUS:X  a  U[        SX=S
9-  nU R                  UUUSU
S9  U $ U R                  UUUSU
S9  U $ ! , (       d  f       N8= f)z8
Private function used to fit a single tree in parallel.r-   zbuilding tree %d of %dr   NrB   rM   	subsampleignoreauto)indicesbalanced_subsamplebalancedF)sample_weightcheck_inputmissing_values_in_feature_mask)printshaperE   onesfloat64copyrK   rG   rO   r   r   DeprecationWarningr   _fit)tree	bootstrapXyr]   tree_idxn_treesverboseclass_weightrH   r_   r;   curr_sample_weightrZ   rQ   s                  r>   _parallel_build_treesrp      s7    {&(Q,)@@AGGAJ	 !#)RZZ!H!.!3!3!5*y
 GA+;&!X'9:"&;FA&WW" "! 11"7
A"WW		,+I 	 	
  K 			'+I 	 	
 K- "!s   &D


Dc                   B  ^  \ rS rSr% Sr\" \SSSS9/S/S\/\S/S/S	/S/S\" \S
SSS9\" \SSSS9/S.r	\
\S'   \ S!\" 5       SSSSSSSSS.	U 4S jjj5       rS rS r\" SS9S"S j5       r\S"S j5       rS rS rS r\S 5       rS r\S 5       rU 4S jrS rU =r$ )#
BaseForest   zq
Base class for forests of trees.

Warning: This class should not be used directly. Use derived classes
instead.
r-   NleftclosedbooleanrG   rm                 ?right)n_estimatorsrh   	oob_scoren_jobsrG   rm   
warm_startr<   _parameter_constraintsFr   	estimator_paramsrh   r|   r}   rG   rm   r~   rn   r<   c       	            > [         TU ]  UUUS9  X@l        XPl        X`l        Xpl        Xl        Xl        Xl        Xl	        g )N)	estimatorr{   r   )
super__init__rh   r|   r}   rG   rm   r~   rn   r<   selfr   r{   r   rh   r|   r}   rG   rm   r~   rn   r<   	__class__s               r>   r   BaseForest.__init__   sM      	%- 	 	
 #"($(&r@   c                    ^ U R                  T5      m[        U R                  U R                  SS9" U4S jU R                   5       5      n[
        R                  " U5      R                  $ )a  
Apply trees in the forest to X, return leaf indices.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The input samples. Internally, its dtype will be converted to
    ``dtype=np.float32``. If a sparse matrix is provided, it will be
    converted into a sparse ``csr_matrix``.

Returns
-------
X_leaves : ndarray of shape (n_samples, n_estimators)
    For each datapoint x in X and for each tree in the forest,
    return the index of the leaf x ends up in.
threadsr}   rm   preferc              3   X   >#    U  H  n[        UR                  5      " TS S9v   M!     g7fFr^   N)r'   apply.0rg   ri   s     r>   	<genexpr>#BaseForest.apply.<locals>.<genexpr>  s#     	Q@P'$**
aU
3@P   '*)_validate_X_predictr&   r}   rm   estimators_rE   arrayT)r   ri   resultss    ` r>   r   BaseForest.apply  s^    " $$Q';;LL
 
R@P@P	Q	R xx """r@   c                   ^ U R                  T5      m[        U R                  U R                  SS9" U4S jU R                   5       5      nS/nUR                  U Vs/ s H  oDR                  S   PM     sn5        [        R                  " U5      R                  5       n[        U5      R                  5       U4$ s  snf )a  
Return the decision path in the forest.

.. versionadded:: 0.18

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The input samples. Internally, its dtype will be converted to
    ``dtype=np.float32``. If a sparse matrix is provided, it will be
    converted into a sparse ``csr_matrix``.

Returns
-------
indicator : sparse matrix of shape (n_samples, n_nodes)
    Return a node indicator matrix where non zero elements indicates
    that the samples goes through the nodes. The matrix is of CSR
    format.

n_nodes_ptr : ndarray of shape (n_estimators + 1,)
    The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]]
    gives the indicator value for the i-th estimator.
r   r   c              3   X   >#    U  H  n[        UR                  5      " TS S9v   M!     g7fr   )r'   decision_pathr   s     r>   r   +BaseForest.decision_path.<locals>.<genexpr><  s*      

( D&&'u=(r   r   r-   )r   r&   r}   rm   r   extendra   rE   r   cumsumsparse_hstacktocsr)r   ri   
indicatorsn_nodesin_nodes_ptrs    `    r>   r   BaseForest.decision_path  s    0 $$Q';;LL


((

	

 #J7Jq
J78hhw'..0Z(..0+== 8s   B<Tprefer_skip_nested_validationc           
      "
  ^ ^^^^
^^ [        T5      (       a  [        S5      e[        T TTSS[        SS9u  mm[	        T R
                  5      " T R                  S9nUR                  TT R                  R                  S9m
Tb  [        TT5      m[        T5      (       a  TR                  5         [        R                  " T5      mTR                  S	:X  a"  TR                  S
   S
:X  a  [!        S["        S	S9  TR                  S
:X  a  [        R$                  " TS5      mT R                  S:X  aN  [        R&                  " TS:  5      (       a  [        S5      e[        R(                  " T5      S::  a  [        S5      eTR                  u  T l        T l        T R/                  T5      u  mn[1        TSS5      [2        :w  d  TR4                  R6                  (       d  [        R8                  " T[2        S9mUb  Tb  TU-  mOUmT R:                  (       d  T R<                  b  [        S5      eT R:                  (       a"  [?        TR                  S   T R<                  S9mOSmTT l         T RC                  5         T R:                  (       d  T RD                  (       a  [        S5      e[G        T RH                  5      nT RJ                  (       a  [M        T S5      (       d  / T l'        T RP                  [S        T RN                  5      -
  nUS:  a-  [        ST RP                  [S        T RN                  5      4-  5      eUS:X  a  [!        S5        OT RJ                  (       a@  [S        T RN                  5      S:  a'  URU                  [V        [S        T RN                  5      S9  [Y        U5       Vs/ s H  nT R[                  SUS9PM     snm[]        T R^                  T R`                  SS9" UU
UUU UU4S j[c        T5       5       5      mT RN                  Re                  T5        T RD                  (       a  US:  d  [M        T S5      (       d~  [g        T5      n	U	S :X  d  [i        T 5      (       a  U	S!:X  a  [        S"U	 S#35      e[k        T RD                  5      (       a  T Rm                  TTT RD                  S$9  OT Rm                  TT5        [M        T S%5      (       a8  T R,                  S
:X  a(  T Rn                  S   T l7        T Rp                  S   T l8        T $ s  snf )&a  
Build a forest of trees from the training set (X, y).

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The training input samples. Internally, its dtype will be converted
    to ``dtype=np.float32``. If a sparse matrix is provided, it will be
    converted into a sparse ``csc_matrix``.

y : array-like of shape (n_samples,) or (n_samples, n_outputs)
    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. Splits
    that would create child nodes with net zero or negative weight are
    ignored while searching for a split in each node. In the case of
    classification, splits are also ignored if they would result in any
    single class carrying a negative weight in either child node.

Returns
-------
self : object
    Fitted estimator.
z3sparse multilabel-indicator for y is not supported.TcscF)multi_outputaccept_sparserC   ensure_all_finite	criterion)estimator_nameNr   r-   zA column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().)
stacklevel)r-   poissonr   zLSome value(s) of y are negative which is not allowed for Poisson regression.zLSum of y is not strictly positive which is necessary for Poisson regression.rC   rB   zl`max_sample` cannot be set if `bootstrap=False`. Either switch to `bootstrap=True` or set `max_sample=None`.)r;   r<   z6Out of bag estimation only available if bootstrap=Truer   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)appendrG   r   r   c              3      >#    U  HK  u  p[        [        5      " UTR                  TT	TU[        T5      TR                  TR
                  TTS 9v   MM     g7f))rm   rn   rH   r_   N)r'   rp   rh   lenrm   rn   )
r   r   tri   r_   rH   r]   r   treesrj   s
      r>   r   !BaseForest.fit.<locals>.<genexpr>  s\       -DA -.NN!J LL!%!2!2(;3Q -s   AA
oob_score_unknownzmulticlass-multioutputz@The type of target cannot be used to compute OOB estimates. Got zv while only the following are supported: continuous, continuous-multioutput, binary, multiclass, multilabel-indicator.)scoring_functionclasses_)9r   r7   r,   r   typer   r   '_compute_missing_values_in_feature_maskr   __name__r)   sort_indicesrE   
atleast_1dndimra   r	   r   reshapeanysum
_n_samples
n_outputs__validate_y_class_weightgetattrr   flags
contiguousascontiguousarrayrh   r<   r?   _n_samples_bootstrap_validate_estimatorr|   r   rG   r~   hasattrr   r{   r   rD   MAX_INTrange_make_estimatorr&   r}   rm   	enumerater   r%   r   callable_set_oob_score_and_attributes
n_classes_r   )r   ri   rj   r]   r   expanded_class_weightrG   n_more_estimatorsr   y_typer_   rH   r   s   ````      @@@r>   fitBaseForest.fitG  s   : A;;RSS#
1 (4>>B	==$.."9"9 >  	' $0BMA;; NNMM!66Q;1771:?? & 66Q; 

1g&A>>Y&vva!e}} :  vvayA~ ; 
 ,-77(#'#@#@#C  1gt$.agg6H6H$$Qf5A ,( -0E E 5~~$"2"2">% 
 ^^":''!*$2B2B# #'$7!  "~~$..UVV)$*;*;<gdM&B&B!D --D4D4D0EEq <$$c$*:*:&;<=  !#!
 3t'7'7#81#< $$W3t7G7G3H$I 011A $$E$M1E {{   &e,	E, ##E*>>!|)D)D#A&F"d##2J(J !&&,X .88  ''22q4>> 3  221a8 4$$A)="ooa0DO MM!,DMCs   %Tc                     g)a  Compute and set the OOB score and attributes.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    The data matrix.
y : ndarray of shape (n_samples, n_outputs)
    The target matrix.
scoring_function : callable, default=None
    Scoring function for OOB score. Default depends on whether
    this is a regression (R2 score) or classification problem
    (accuracy score).
N r   ri   rj   r   s       r>   r   (BaseForest._set_oob_score_and_attributes  s    r@   c                    [        U5      (       a  UR                  5       nUR                  S   nU R                  n[	        U 5      (       a#  [        U S5      (       a  X0R                  S   U4nOUSU4n[        R                  " U[        R                  S9n[        R                  " X44[        R                  S9n[        UU R                  5      nU R                   HP  n	[        U	R                  UU5      n
U R!                  XU
SS24   5      nXjS4==   U-  ss'   XzSS24==   S-  ss'   MR     [#        U5       HG  nUS:H  R%                  5       (       a  ['        S[(        5        SXwS:H  '   USU4==   USU/4   -  ss'   MI     U$ )	aS  Compute and set the OOB score.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    The data matrix.
y : ndarray of shape (n_samples, n_outputs)
    The target matrix.

Returns
-------
oob_pred : ndarray of shape (n_samples, n_classes, n_outputs) or                 (n_samples, 1, n_outputs)
    The OOB predictions.
r   r   r-   )ra   rC   rB   N.zvSome inputs do not have OOB scores. This probably means too few trees were used to compute any reliable OOB estimates.)r   r   ra   r   r   r   r   rE   zerosrc   int64r?   r<   r   rU   rG   _get_oob_predictionsr   r   r	   UserWarning)r   ri   rj   r;   	n_outputsoob_pred_shapeoob_pred
n_oob_predrH   r   rT   y_predks                r>   _compute_oob_predictions#BaseForest._compute_oob_predictions.  s   " A;;	AGGAJ	OO	74#>#> ();YGN
 (I6N88.

CXXy4BHHE
6
 ))I ;&&#! ..y<Mq<P:QRF+,6,!+,1, * y!Aa$$&&%   /0
?+S!V
38 44 " r@   c                 
    US 4$ Nr   )r   rj   s     r>   r   #BaseForest._validate_y_class_weightp  s    $wr@   c           	      f   [        U 5        U R                  S   R                  U5      (       a  SnOSn[        U U[        SSUS9n[        U5      (       a[  UR                  R                  [        R                  :w  d(  UR                  R                  [        R                  :w  a  [        S5      eU$ )z@
Validate X whenever one tries to predict, apply, predict_proba.r   z	allow-nanTcsrF)rC   r   resetr   z3No support for np.int64 index based sparse matrices)r+   r   _support_missing_valuesr,   r   r   rZ   rC   rE   intcindptrr7   )r   ri   r   s      r>   r   BaseForest._validate_X_predictt  s     	A66q99 + $/
 A;;AIIOOrww6!((..BGG:SRSSr@   c                 P   [        U 5        [        U R                  SS9" S U R                   5       5      nU(       d-  [        R
                  " U R                  [        R                  S9$ [        R                  " US[        R                  S9nU[        R                  " U5      -  $ )a  
The impurity-based feature importances.

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

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

Returns
-------
feature_importances_ : ndarray of shape (n_features,)
    The values of this array sum to 1, unless all trees are single node
    trees consisting of only the root node, in which case it will be an
    array of zeros.
r   )r}   r   c              3      #    U  H7  nUR                   R                  S :  d  M  [        [        5      " US5      v   M9     g7f)r-   feature_importances_N)tree_
node_countr'   r   )r   rg   s     r>   r   2BaseForest.feature_importances_.<locals>.<genexpr>  s<      I
(zz$$q( ;GGT#9::(s
   AArB   r   )axisrC   )
r+   r&   r}   r   rE   r   n_features_in_rc   meanr   )r   all_importancess     r>   r   BaseForest.feature_importances_  s    * 	"$++iH I
((I
 
 88D//rzzBB''/L!888r@   c              #     #    U R                    Hs  nU R                  (       d1  [        R                  " U R                  [        R
                  S9v   ME  UR                  n[        X R                  U R                  5      v   Mu     g 7f)NrB   )	r   rh   rE   rP   r   rF   rG   rK   r   )r   rg   seeds      r>   _get_estimators_indices"BaseForest._get_estimators_indices  s`     $$D>>iirxx@@
 (( ///4+D+D  %s   BBc                 L    U R                  5        Vs/ s H  oPM     sn$ s  s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   rJ   s     r>   estimators_samples_BaseForest.estimators_samples_  s'     6:5Q5Q5ST5S>5STTTs   !c                    > [         TU ]  5       n[        U R                  5      " U R                  S9n[        U5      R                  R                  UR                  l        U$ )Nr   )r   __sklearn_tags__r   r   r   r#   
input_tags	allow_nan)r   tagsr   r   s      r>   r  BaseForest.__sklearn_tags__  sK    w') (4>>B	$,Y$7$B$B$L$L!r@   )r   r   rh   rn   r   r   r<   r   r}   r   r|   rG   rm   r~   d   r   )r   
__module____qualname____firstlineno____doc__r    r   r   r!   r   dict__annotations__r   tupler   r   r   r   r   r   r   r   r   propertyr   r
  r  r  __static_attributes____classcell__r   s   @r>   rr   rr      s;    "(AtFCD[*T"'(; kZc':Xq$v6
$D   '
 ' ' '<#4&>P 5T 6Tl  @D*  9  9D  U U r@   rr   )	metaclassc                     U " USS9nU   [        U5      S:X  a  US==   U-  ss'   O)[        [        U5      5       H  nX%==   XE   -  ss'   M     SSS5        g! , (       d  f       g= f)z
This is a utility function for joblib's Parallel.

It can't go locally in ForestClassifier or ForestRegressor, because joblib
complains that it cannot pickle it when placed there.
Fr   r-   r   N)r   r   )predictri   outlock
predictionr   s         r>   _accumulate_predictionr(    sV     .J	s8q=Fj F3s8_*-' %	 
s   AA
A(c                      ^  \ rS rSrSr\ S\" 5       SSSSSSSSS.	U 4S jjj5       r\S 5       r	SU 4S	 jjr
S
 rS rS rS rU 4S jrSrU =r$ )ForestClassifieri  z
Base class for forest of trees-based classifiers.

Warning: This class should not be used directly. Use derived classes
instead.
FNr   r   c       	         4   > [         TU ]  UUUUUUUUU	U
US9  g )Nr   r{   r   rh   r|   r}   rG   rm   r~   rn   r<   r   r   r   s               r>   r   ForestClassifier.__init__  s8      	%-%!%# 	 	
r@   c                     U R                  USS9n[        R                  " U5      nUR                  S:X  a  US[        R                  4   nU$ [        R
                  " USSS9nU$ )aJ  Compute the OOB predictions for an individual tree.

Parameters
----------
tree : DecisionTreeClassifier object
    A single decision tree classifier.
X : ndarray of shape (n_samples, n_features)
    The OOB samples.

Returns
-------
y_pred : ndarray of shape (n_samples, n_classes, n_outputs)
    The OOB associated predictions.
Fr   r   .r      )r  start)predict_probarE   asarrayr   newaxisrollaxisrg   ri   r   s      r>   r   %ForestClassifier._get_oob_predictions	  se      ##A5#9F#;;!CO,F  [[aq9Fr@   c                   > [         TU ]  X5      U l        U R                  R                  S   S:X  a  U R                  R	                  SS9U l        Uc  [
        nU" U[        R                  " U R                  SS95      U l        g)a9  Compute and set the OOB score and attributes.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    The data matrix.
y : ndarray of shape (n_samples, n_outputs)
    The target matrix.
scoring_function : callable, default=None
    Scoring function for OOB score. Defaults to `accuracy_score`.
r   r-   r  N)	r   r   oob_decision_function_ra   squeezer   rE   argmaxr   r   ri   rj   r   r   s       r>   r   .ForestClassifier._set_oob_score_and_attributes%  s{     ',g&Fq&L#&&,,R0A5*.*E*E*M*MSU*M*VD'#-*ryy441=
r@   c                 ~   [        U5        [        R                  " U5      nS nU R                  b  [        R                  " U5      n/ U l        / U l        [        R                  " UR                  [        S9n[        U R                  5       Hk  n[        R                  " US S 2U4   SS9u  odS S 2U4'   U R                  R                  U5        U R
                  R                  UR                  S   5        Mm     UnU R                  b  Sn[        U R                  [        5      (       aD  U R                  U;  a  [        SU R                  -  5      eU R                   (       a  [#        S5        U R                  S:w  d  U R$                  (       d+  U R                  S:X  a  S	nOU R                  n['        UW5      nX4$ )
NrB   T)return_inverser   )r\   r[   zVValid presets for class_weight include "balanced" and "balanced_subsample".Given "%s".a  class_weight presets "balanced" or "balanced_subsample" are not recommended for warm_start if the fitted data differs from the full dataset. In order to use "balanced" weights, use compute_class_weight ("balanced", classes, y). In place of y you can use a large enough sample of the full training set target to properly estimate the class frequency distributions. Pass the resulting weights as the class_weight parameter.r[   r\   )r$   rE   rd   rn   r   r   r   ra   intr   r   uniquer   r6   strr7   r~   r	   rh   r   )	r   rj   r   
y_originaly_store_unique_indicesr   	classes_kvalid_presetsrn   s	            r>   r   )ForestClassifier._validate_y_class_weight=  s}   $Q'GGAJ $(J!#!''!=t'A68ii!Q$73Iad3 MM  +OO""9??1#56 ( #(>M$++S11$$M9$&(,(9(9: 
 ??	2   $88$$(<<#-L#'#4#4L(=lJ(W%''r@   c                    U R                  U5      nU R                  S:X  a-  U R                  R                  [        R
                  " USS9SS9$ US   R                  S   nU R                  S   R                  n[        R                  " X0R                  4US9n[        U R                  5       H<  nU R                  U   R                  [        R
                  " X&   SS9SS9USS2U4'   M>     U$ )aa  
Predict class for X.

The predicted class of an input sample is a vote by the trees in
the forest, weighted by their probability estimates. That is,
the predicted class is the one with highest mean probability
estimate across the trees.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The input samples. Internally, its dtype will be converted to
    ``dtype=np.float32``. If a sparse matrix is provided, it will be
    converted into a sparse ``csr_matrix``.

Returns
-------
y : ndarray of shape (n_samples,) or (n_samples, n_outputs)
    The predicted classes.
r-   r9  r   rB   N)
r2  r   r   takerE   r<  ra   rC   emptyr   )r   ri   probar;   
class_typepredictionsr   s          r>   r$  ForestClassifier.predictr  s    * ""1%??a==%%biiA&>Q%GG aq)Iq)//J((I#?zRK4??+$(MM!$4$9$9IIehQ/a %: %AqD! ,
 r@   c                 L  ^^^ [        U 5        U R                  T5      m[        U R                  U R                  5      u  n  n[
        R                  " U R                  5       Vs/ s H5  n[
        R                  " TR                  S   U4[
        R                  S9PM7     snm[        R                  " 5       m[        X R                  SS9" UUU4S jU R                   5       5        T H  nU[!        U R                  5      -  nM     [!        T5      S:X  a  TS   $ T$ s  snf )a  
Predict class probabilities for X.

The predicted class probabilities of an input sample are computed as
the mean predicted class probabilities of the trees in the forest.
The class probability of a single tree is the fraction of samples of
the same class in a leaf.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The input samples. Internally, its dtype will be converted to
    ``dtype=np.float32``. If a sparse matrix is provided, it will be
    converted into a sparse ``csr_matrix``.

Returns
-------
p : ndarray of shape (n_samples, n_classes), or a list of such arrays
    The class probabilities of the input samples. The order of the
    classes corresponds to that in the attribute :term:`classes_`.
r   rB   	sharedmemr}   rm   requirec              3   h   >#    U  H'  n[        [        5      " UR                  TTT5      v   M)     g 7fr   )r'   r(  r2  )r   eri   	all_probar&  s     r>   r   1ForestClassifier.predict_proba.<locals>.<genexpr>  s1      K
% *+AOOQ	4PP%s   /2r-   )r+   r   r/   r{   r}   rE   r   r   r   ra   rc   	threadingLockr&   rm   r   r   )r   ri   r}   _jrL  rV  r&  s    `    @@r>   r2  ForestClassifier.predict_proba  s    , 	$$Q' -T->->L1
 ]]4??3
3 HHaggaj!_BJJ73
	 ~~kJ K
%%K
 	

 ES))**E  y>QQ<!
s   &<D!c                     U R                  U5      nU R                  S:X  a  [        R                  " U5      $ [	        U R                  5       H  n[        R                  " X#   5      X#'   M     U$ )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 trees in the
forest.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The input samples. Internally, its dtype will be converted to
    ``dtype=np.float32``. If a sparse matrix is provided, it will be
    converted into a sparse ``csr_matrix``.

Returns
-------
p : ndarray of shape (n_samples, n_classes), or a list of such arrays
    The class probabilities of the input samples. The order of the
    classes corresponds to that in the attribute :term:`classes_`.
r-   )r2  r   rE   logr   )r   ri   rL  r   s       r>   predict_log_proba"ForestClassifier.predict_log_proba  s\    * ""1%??a66%=  4??+66%(+ , Lr@   c                 h   > [         TU ]  5       nSUR                  l        SUR                  l        U$ NT)r   r  classifier_tagsmulti_labelr  sparser   r  r   s     r>   r  !ForestClassifier.__sklearn_tags__  s/    w')+/(!%r@   )r   r   r:  r   r  r   )r   r  r  r  r  r   r  r   staticmethodr   r   r   r$  r2  r_  r  r  r   r!  s   @r>   r*  r*    s      

 
 
 
:  6
03(j%N.`@ r@   r*  c                      ^  \ rS rSrSr\ S\" 5       SSSSSSSS.U 4S jjj5       rS r\	S	 5       r
SU 4S
 jjrS rU 4S jrSrU =r$ )ForestRegressori  z
Base class for forest of trees-based regressors.

Warning: This class should not be used directly. Use derived classes
instead.
FNr   )r   rh   r|   r}   rG   rm   r~   r<   c                2   > [         TU ]  UUUUUUUUU	U
S9
  g )N)	r{   r   rh   r|   r}   rG   rm   r~   r<   r-  )r   r   r{   r   rh   r|   r}   rG   rm   r~   r<   r   s              r>   r   ForestRegressor.__init__  s5     	%-%!# 	 	
r@   c                 @  ^^^ [        U 5        U R                  T5      m[        U R                  U R                  5      u  n  nU R
                  S:  a=  [        R                  " TR                  S   U R
                  4[        R                  S9mO0[        R                  " TR                  S   [        R                  S9m[        R                  " 5       m[        X R                  SS9" UUU4S jU R                   5       5        T[        U R                  5      -  mT$ )a  
Predict regression target for X.

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

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The input samples. Internally, its dtype will be converted to
    ``dtype=np.float32``. If a sparse matrix is provided, it will be
    converted into a sparse ``csr_matrix``.

Returns
-------
y : ndarray of shape (n_samples,) or (n_samples, n_outputs)
    The predicted values.
r-   r   rB   rQ  rR  c              3   j   >#    U  H(  n[        [        5      " UR                  TT/T5      v   M*     g 7fr   )r'   r(  r$  )r   rU  ri   r&  y_hats     r>   r   *ForestRegressor.predict.<locals>.<genexpr>6  s3      K
% *+AIIq5'4HH%s   03)r+   r   r/   r{   r}   r   rE   r   ra   rc   rX  rY  r&   rm   r   r   )r   ri   r}   rZ  r&  ro  s    `  @@r>   r$  ForestRegressor.predict  s    & 	$$Q' -T->->L1 ??QHHaggaj$//:"**MEHHaggaj<E ~~kJ K
%%K
 	

 	T%%&&r@   c                     U R                  USS9nUR                  S:X  a(  USS2[        R                  [        R                  4   nU$ USS2[        R                  SS24   nU$ )a@  Compute the OOB predictions for an individual tree.

Parameters
----------
tree : DecisionTreeRegressor object
    A single decision tree regressor.
X : ndarray of shape (n_samples, n_features)
    The OOB samples.

Returns
-------
y_pred : ndarray of shape (n_samples, 1, n_outputs)
    The OOB associated predictions.
Fr   r-   N)r$  r   rE   r4  r6  s      r>   r   $ForestRegressor._get_oob_predictions?  s^      aU3;;!Arzz2::56F  Arzz1,-Fr@   c                    > [         TU ]  X5      R                  SS9U l        U R                  R                  S   S:X  a  U R                  R                  SS9U l        Uc  [
        nU" X R                  5      U l        g)a3  Compute and set the OOB score and attributes.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    The data matrix.
y : ndarray of shape (n_samples, n_outputs)
    The target matrix.
scoring_function : callable, default=None
    Scoring function for OOB score. Defaults to `r2_score`.
r-   r9  r   N)r   r   r;  oob_prediction_ra   r   r   r=  s       r>   r   -ForestRegressor._set_oob_score_and_attributesX  sy      %w?EMMSTMU%%b)Q.#'#7#7#?#?R#?#HD #'*1.B.BCr@   c                 r   [         R                  " U[        SS9n[         R                  " U[         R                  SS9n[         R                  " UR
                  S   [         R                  SS9nU R                   H  nUR                  R                  XU5        M!     U[        U R                  5      -  nU$ )a  Fast partial dependence computation.

Parameters
----------
grid : ndarray of shape (n_samples, n_target_features), dtype=DTYPE
    The grid points on which the partial dependence should be
    evaluated.
target_features : ndarray of shape (n_target_features), dtype=np.intp
    The set of target features for which the partial dependence
    should be evaluated.

Returns
-------
averaged_predictions : ndarray of shape (n_samples,)
    The value of the partial dependence function on each grid point.
C)rC   orderr   )ra   rC   ry  )rE   r3  r   intpr   ra   rc   r   r   compute_partial_dependencer   )r   gridtarget_featuresaveraged_predictionsrg   s        r>   %_compute_partial_dependence_recursion5ForestRegressor._compute_partial_dependence_recursionn  s    " zz$e37**_BGG3O!xx**Q-rzz 
 $$D JJ11'; % 	D$4$4 55##r@   c                 F   > [         TU ]  5       nSUR                  l        U$ rb  r   r  r  re  rf  s     r>   r   ForestRegressor.__sklearn_tags__  !    w')!%r@   )ru  r   r  r   )r   r  r  r  r  r   r  r   r$  rh  r   r   r  r  r  r   r!  s   @r>   rj  rj    sw      

 
 
 
6)V  0D, $D r@   rj  c                      ^  \ rS rSr% Sr0 \R                  E\R                  ES\" SS15      \	\
S/0Er\	\S'   \R                  S5         SS	SS
SSSSSSSSSSSSSSSS.U 4S jjjrSrU =r$ )r2   i  a4  
A random forest classifier.

A random forest is a meta estimator that fits a number of decision tree
classifiers on various sub-samples of the dataset and uses averaging to
improve the predictive accuracy and control over-fitting.
Trees in the forest use the best split strategy, i.e. equivalent to passing
`splitter="best"` to the underlying :class:`~sklearn.tree.DecisionTreeClassifier`.
The sub-sample size is controlled with the `max_samples` parameter if
`bootstrap=True` (default), otherwise the whole dataset is used to build
each tree.

For a comparison between tree-based ensemble models see the example
:ref:`sphx_glr_auto_examples_ensemble_plot_forest_hist_grad_boosting_comparison.py`.

This estimator has native support for missing values (NaNs). During training,
the tree grower learns at each split point whether samples with missing values
should go to the left or right child, based on the potential gain. When predicting,
samples with missing values are assigned to the left or right child consequently.
If no missing values were encountered for a given feature during training, then
samples with missing values are mapped to whichever child has the most samples.

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

Parameters
----------
n_estimators : int, default=100
    The number of trees in the forest.

    .. versionchanged:: 0.22
       The default value of ``n_estimators`` changed from 10 to 100
       in 0.22.

criterion : {"gini", "entropy", "log_loss"}, default="gini"
    The function to measure the quality of a split. Supported criteria are
    "gini" for the Gini impurity and "log_loss" and "entropy" both for the
    Shannon information gain, see :ref:`tree_mathematical_formulation`.
    Note: This parameter is tree-specific.

max_depth : int, default=None
    The maximum depth of the tree. If None, then nodes are expanded until
    all leaves are pure or until all leaves contain less than
    min_samples_split samples.

min_samples_split : int or float, default=2
    The minimum number of samples required to split an internal node:

    - If int, then consider `min_samples_split` as the minimum number.
    - If float, then `min_samples_split` is a fraction and
      `ceil(min_samples_split * n_samples)` are the minimum
      number of samples for each split.

    .. versionchanged:: 0.18
       Added float values for fractions.

min_samples_leaf : int or float, default=1
    The minimum number of samples required to be at a leaf node.
    A split point at any depth will only be considered if it leaves at
    least ``min_samples_leaf`` training samples in each of the left and
    right branches.  This may have the effect of smoothing the model,
    especially in regression.

    - If int, then consider `min_samples_leaf` as the minimum number.
    - If float, then `min_samples_leaf` is a fraction and
      `ceil(min_samples_leaf * n_samples)` are the minimum
      number of samples for each node.

    .. versionchanged:: 0.18
       Added float values for fractions.

min_weight_fraction_leaf : float, default=0.0
    The minimum weighted fraction of the sum total of weights (of all
    the input samples) required to be at a leaf node. Samples have
    equal weight when sample_weight is not provided.

max_features : {"sqrt", "log2", None}, int or float, default="sqrt"
    The number of features to consider when looking for the best split:

    - If int, then consider `max_features` features at each split.
    - If float, then `max_features` is a fraction and
      `max(1, int(max_features * n_features_in_))` features are considered at each
      split.
    - If "sqrt", then `max_features=sqrt(n_features)`.
    - If "log2", then `max_features=log2(n_features)`.
    - If None, then `max_features=n_features`.

    .. versionchanged:: 1.1
        The default of `max_features` changed from `"auto"` to `"sqrt"`.

    Note: the search for a split does not stop until at least one
    valid partition of the node samples is found, even if it requires to
    effectively inspect more than ``max_features`` features.

max_leaf_nodes : int, default=None
    Grow trees with ``max_leaf_nodes`` in best-first fashion.
    Best nodes are defined as relative reduction in impurity.
    If None then unlimited number of leaf nodes.

min_impurity_decrease : float, default=0.0
    A node will be split if this split induces a decrease of the impurity
    greater than or equal to this value.

    The weighted impurity decrease equation is the following::

        N_t / N * (impurity - N_t_R / N_t * right_impurity
                            - N_t_L / N_t * left_impurity)

    where ``N`` is the total number of samples, ``N_t`` is the number of
    samples at the current node, ``N_t_L`` is the number of samples in the
    left child, and ``N_t_R`` is the number of samples in the right child.

    ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
    if ``sample_weight`` is passed.

    .. versionadded:: 0.19

bootstrap : bool, default=True
    Whether bootstrap samples are used when building trees. If False, the
    whole dataset is used to build each tree.

oob_score : bool or callable, default=False
    Whether to use out-of-bag samples to estimate the generalization score.
    By default, :func:`~sklearn.metrics.accuracy_score` is used.
    Provide a callable with signature `metric(y_true, y_pred)` to use a
    custom metric. Only available if `bootstrap=True`.

    For an illustration of out-of-bag (OOB) error estimation, see the example
    :ref:`sphx_glr_auto_examples_ensemble_plot_ensemble_oob.py`.

n_jobs : int, default=None
    The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,
    :meth:`decision_path` and :meth:`apply` are all parallelized over the
    trees. ``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 both the randomness of the bootstrapping of the samples used
    when building trees (if ``bootstrap=True``) and the sampling of the
    features to consider when looking for the best split at each node
    (if ``max_features < n_features``).
    See :term:`Glossary <random_state>` for details.

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

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 forest. See :term:`Glossary <warm_start>` and
    :ref:`tree_ensemble_warm_start` for details.

class_weight : {"balanced", "balanced_subsample"}, dict or list of dicts,             default=None
    Weights associated with classes in the form ``{class_label: weight}``.
    If not given, all classes are supposed to have weight one. For
    multi-output problems, a list of dicts can be provided in the same
    order as the columns of y.

    Note that for multioutput (including multilabel) weights should be
    defined for each class of every column in its own dict. For example,
    for four-class multilabel classification weights should be
    [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of
    [{1:1}, {2:5}, {3:1}, {4:1}].

    The "balanced" mode uses the values of y to automatically adjust
    weights inversely proportional to class frequencies in the input data
    as ``n_samples / (n_classes * np.bincount(y))``

    The "balanced_subsample" mode is the same as "balanced" except that
    weights are computed based on the bootstrap sample for every tree
    grown.

    For multi-output, the weights of each column of y will be multiplied.

    Note that these weights will be multiplied with sample_weight (passed
    through the fit method) if sample_weight is specified.

ccp_alpha : non-negative float, default=0.0
    Complexity parameter used for Minimal Cost-Complexity Pruning. The
    subtree with the largest cost complexity that is smaller than
    ``ccp_alpha`` will be chosen. By default, no pruning is performed. See
    :ref:`minimal_cost_complexity_pruning` for details. See
    :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py`
    for an example of such pruning.

    .. versionadded:: 0.22

max_samples : int or float, default=None
    If bootstrap is True, the number of samples to draw from X
    to train each base estimator.

    - If None (default), then draw `X.shape[0]` samples.
    - If int, then draw `max_samples` samples.
    - If float, then draw `max(round(n_samples * max_samples), 1)` samples. Thus,
      `max_samples` should be in the interval `(0.0, 1.0]`.

    .. versionadded:: 0.22

monotonic_cst : array-like of int of shape (n_features), default=None
    Indicates the monotonicity constraint to enforce on each feature.
      - 1: monotonic increase
      - 0: no constraint
      - -1: monotonic decrease

    If monotonic_cst is None, no constraints are applied.

    Monotonicity constraints are not supported for:
      - multiclass classifications (i.e. when `n_classes > 2`),
      - multioutput classifications (i.e. when `n_outputs_ > 1`),
      - classifications trained on data with missing values.

    The constraints hold over the probability of the positive class.

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

    .. versionadded:: 1.4

Attributes
----------
estimator_ : :class:`~sklearn.tree.DecisionTreeClassifier`
    The child estimator template used to create the collection of fitted
    sub-estimators.

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

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

classes_ : ndarray of shape (n_classes,) or a list of such arrays
    The classes labels (single output problem), or a list of arrays of
    class labels (multi-output problem).

n_classes_ : int or list
    The number of classes (single output problem), or a list containing the
    number of classes for each output (multi-output problem).

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

n_outputs_ : int
    The number of outputs when ``fit`` is performed.

feature_importances_ : ndarray of shape (n_features,)
    The impurity-based feature importances.
    The higher, the more important the feature.
    The importance of a feature is computed as the (normalized)
    total reduction of the criterion brought by that feature.  It is also
    known as the Gini importance.

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

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) or             (n_samples, n_classes, n_outputs)
    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.

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.

    .. versionadded:: 1.4

See Also
--------
sklearn.tree.DecisionTreeClassifier : A decision tree classifier.
sklearn.ensemble.ExtraTreesClassifier : Ensemble of extremely randomized
    tree classifiers.
sklearn.ensemble.HistGradientBoostingClassifier : A Histogram-based Gradient
    Boosting Classification Tree, very fast for big datasets (n_samples >=
    10_000).

Notes
-----
The default values for the parameters controlling the size of the trees
(e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
unpruned trees which can potentially be very large on some data sets. To
reduce memory consumption, the complexity and size of the trees should be
controlled by setting those parameter values.

The features are always randomly permuted at each split. Therefore,
the best found split may vary, even with the same training data,
``max_features=n_features`` and ``bootstrap=False``, if the improvement
of the criterion is identical for several splits enumerated during the
search of the best split. To obtain a deterministic behaviour during
fitting, ``random_state`` has to be fixed.

References
----------
.. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001.

Examples
--------
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=1000, n_features=4,
...                            n_informative=2, n_redundant=0,
...                            random_state=0, shuffle=False)
>>> clf = RandomForestClassifier(max_depth=2, random_state=0)
>>> clf.fit(X, y)
RandomForestClassifier(...)
>>> print(clf.predict([[0, 0, 0, 0]]))
[1]
rn   r[   r\   Nr   splitterginir   r-   rx   sqrtTFr   r   	max_depthmin_samples_splitmin_samples_leafmin_weight_fraction_leafmax_featuresmax_leaf_nodesmin_impurity_decreaserh   r|   r}   rG   rm   r~   rn   	ccp_alphar<   monotonic_cstc                   > [         TU ]  [        5       USU
UUUUUUUS9  X l        X0l        X@l        XPl        X`l        Xpl        Xl	        Xl
        UU l        UU l        g Nr   r  r  r  r  r  r  r  rG   r  r  r,  )r   r   r   r   r  r  r  r  r  r  r  r  r  r   r{   r   r  r  r  r  r  r  r  rh   r|   r}   rG   rm   r~   rn   r  r<   r  r   s                       r>   r   RandomForestClassifier.__init__  s~    . 	,.%  %!%#/ 	 	
4 #"!2 0(@%(,%:"*"r@   
r  r   r  r  r  r  r  r  r  r  r  r   r  r  r  r  r*  r   r   r"   r  listr  popr   r  r   r!  s   @r>   r2   r2     s    AF
	$

1
1	$
 
7
7	$ 	,j9:	
	$D 	 z* :# !$!+:# :#r@   r2   c                      ^  \ rS rSr% Sr0 \R                  E\R                  Er\\	S'   \R                  S5         SSSSSS	S
SS	SSSSSSS	SSS.U 4S jjjrSrU =r$ )r3   i#  a0  
A random forest regressor.

A random forest is a meta estimator that fits a number of decision tree
regressors on various sub-samples of the dataset and uses averaging to
improve the predictive accuracy and control over-fitting.
Trees in the forest use the best split strategy, i.e. equivalent to passing
`splitter="best"` to the underlying :class:`~sklearn.tree.DecisionTreeRegressor`.
The sub-sample size is controlled with the `max_samples` parameter if
`bootstrap=True` (default), otherwise the whole dataset is used to build
each tree.

This estimator has native support for missing values (NaNs). During training,
the tree grower learns at each split point whether samples with missing values
should go to the left or right child, based on the potential gain. When predicting,
samples with missing values are assigned to the left or right child consequently.
If no missing values were encountered for a given feature during training, then
samples with missing values are mapped to whichever child has the most samples.

For a comparison between tree-based ensemble models see the example
:ref:`sphx_glr_auto_examples_ensemble_plot_forest_hist_grad_boosting_comparison.py`.

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

Parameters
----------
n_estimators : int, default=100
    The number of trees in the forest.

    .. versionchanged:: 0.22
       The default value of ``n_estimators`` changed from 10 to 100
       in 0.22.

criterion : {"squared_error", "absolute_error", "friedman_mse", "poisson"},             default="squared_error"
    The function to measure the quality of a split. Supported criteria
    are "squared_error" for the mean squared error, which is equal to
    variance reduction as feature selection criterion and minimizes the L2
    loss using the mean of each terminal node, "friedman_mse", which uses
    mean squared error with Friedman's improvement score for potential
    splits, "absolute_error" for the mean absolute error, which minimizes
    the L1 loss using the median of each terminal node, and "poisson" which
    uses reduction in Poisson deviance to find splits.
    Training using "absolute_error" is significantly slower
    than when using "squared_error".

    .. versionadded:: 0.18
       Mean Absolute Error (MAE) criterion.

    .. versionadded:: 1.0
       Poisson criterion.

max_depth : int, default=None
    The maximum depth of the tree. If None, then nodes are expanded until
    all leaves are pure or until all leaves contain less than
    min_samples_split samples.

min_samples_split : int or float, default=2
    The minimum number of samples required to split an internal node:

    - If int, then consider `min_samples_split` as the minimum number.
    - If float, then `min_samples_split` is a fraction and
      `ceil(min_samples_split * n_samples)` are the minimum
      number of samples for each split.

    .. versionchanged:: 0.18
       Added float values for fractions.

min_samples_leaf : int or float, default=1
    The minimum number of samples required to be at a leaf node.
    A split point at any depth will only be considered if it leaves at
    least ``min_samples_leaf`` training samples in each of the left and
    right branches.  This may have the effect of smoothing the model,
    especially in regression.

    - If int, then consider `min_samples_leaf` as the minimum number.
    - If float, then `min_samples_leaf` is a fraction and
      `ceil(min_samples_leaf * n_samples)` are the minimum
      number of samples for each node.

    .. versionchanged:: 0.18
       Added float values for fractions.

min_weight_fraction_leaf : float, default=0.0
    The minimum weighted fraction of the sum total of weights (of all
    the input samples) required to be at a leaf node. Samples have
    equal weight when sample_weight is not provided.

max_features : {"sqrt", "log2", None}, int or float, default=1.0
    The number of features to consider when looking for the best split:

    - If int, then consider `max_features` features at each split.
    - If float, then `max_features` is a fraction and
      `max(1, int(max_features * n_features_in_))` features are considered at each
      split.
    - If "sqrt", then `max_features=sqrt(n_features)`.
    - If "log2", then `max_features=log2(n_features)`.
    - If None or 1.0, then `max_features=n_features`.

    .. note::
        The default of 1.0 is equivalent to bagged trees and more
        randomness can be achieved by setting smaller values, e.g. 0.3.

    .. versionchanged:: 1.1
        The default of `max_features` changed from `"auto"` to 1.0.

    Note: the search for a split does not stop until at least one
    valid partition of the node samples is found, even if it requires to
    effectively inspect more than ``max_features`` features.

max_leaf_nodes : int, default=None
    Grow trees with ``max_leaf_nodes`` in best-first fashion.
    Best nodes are defined as relative reduction in impurity.
    If None then unlimited number of leaf nodes.

min_impurity_decrease : float, default=0.0
    A node will be split if this split induces a decrease of the impurity
    greater than or equal to this value.

    The weighted impurity decrease equation is the following::

        N_t / N * (impurity - N_t_R / N_t * right_impurity
                            - N_t_L / N_t * left_impurity)

    where ``N`` is the total number of samples, ``N_t`` is the number of
    samples at the current node, ``N_t_L`` is the number of samples in the
    left child, and ``N_t_R`` is the number of samples in the right child.

    ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
    if ``sample_weight`` is passed.

    .. versionadded:: 0.19

bootstrap : bool, default=True
    Whether bootstrap samples are used when building trees. If False, the
    whole dataset is used to build each tree.

oob_score : bool or callable, default=False
    Whether to use out-of-bag samples to estimate the generalization score.
    By default, :func:`~sklearn.metrics.r2_score` is used.
    Provide a callable with signature `metric(y_true, y_pred)` to use a
    custom metric. Only available if `bootstrap=True`.

    For an illustration of out-of-bag (OOB) error estimation, see the example
    :ref:`sphx_glr_auto_examples_ensemble_plot_ensemble_oob.py`.

n_jobs : int, default=None
    The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,
    :meth:`decision_path` and :meth:`apply` are all parallelized over the
    trees. ``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 both the randomness of the bootstrapping of the samples used
    when building trees (if ``bootstrap=True``) and the sampling of the
    features to consider when looking for the best split at each node
    (if ``max_features < n_features``).
    See :term:`Glossary <random_state>` for details.

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

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 forest. See :term:`Glossary <warm_start>` and
    :ref:`tree_ensemble_warm_start` for details.

ccp_alpha : non-negative float, default=0.0
    Complexity parameter used for Minimal Cost-Complexity Pruning. The
    subtree with the largest cost complexity that is smaller than
    ``ccp_alpha`` will be chosen. By default, no pruning is performed. See
    :ref:`minimal_cost_complexity_pruning` for details. See
    :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py`
    for an example of such pruning.

    .. versionadded:: 0.22

max_samples : int or float, default=None
    If bootstrap is True, the number of samples to draw from X
    to train each base estimator.

    - If None (default), then draw `X.shape[0]` samples.
    - If int, then draw `max_samples` samples.
    - If float, then draw `max(round(n_samples * max_samples), 1)` samples. Thus,
      `max_samples` should be in the interval `(0.0, 1.0]`.

    .. versionadded:: 0.22

monotonic_cst : array-like of int of shape (n_features), default=None
    Indicates the monotonicity constraint to enforce on each feature.
      - 1: monotonically increasing
      - 0: no constraint
      - -1: monotonically decreasing

    If monotonic_cst is None, no constraints are applied.

    Monotonicity constraints are not supported for:
      - multioutput regressions (i.e. when `n_outputs_ > 1`),
      - regressions trained on data with missing values.

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

    .. versionadded:: 1.4

Attributes
----------
estimator_ : :class:`~sklearn.tree.DecisionTreeRegressor`
    The child estimator template used to create the collection of fitted
    sub-estimators.

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

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

feature_importances_ : ndarray of shape (n_features,)
    The impurity-based feature importances.
    The higher, the more important the feature.
    The importance of a feature is computed as the (normalized)
    total reduction of the criterion brought by that feature.  It is also
    known as the Gini importance.

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

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

n_outputs_ : int
    The number of outputs when ``fit`` is performed.

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,) or (n_samples, n_outputs)
    Prediction computed with out-of-bag estimate on the training set.
    This attribute exists only when ``oob_score`` is True.

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.

    .. versionadded:: 1.4

See Also
--------
sklearn.tree.DecisionTreeRegressor : A decision tree regressor.
sklearn.ensemble.ExtraTreesRegressor : Ensemble of extremely randomized
    tree regressors.
sklearn.ensemble.HistGradientBoostingRegressor : A Histogram-based Gradient
    Boosting Regression Tree, very fast for big datasets (n_samples >=
    10_000).

Notes
-----
The default values for the parameters controlling the size of the trees
(e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
unpruned trees which can potentially be very large on some data sets. To
reduce memory consumption, the complexity and size of the trees should be
controlled by setting those parameter values.

The features are always randomly permuted at each split. Therefore,
the best found split may vary, even with the same training data,
``max_features=n_features`` and ``bootstrap=False``, if the improvement
of the criterion is identical for several splits enumerated during the
search of the best split. To obtain a deterministic behaviour during
fitting, ``random_state`` has to be fixed.

The default value ``max_features=1.0`` uses ``n_features``
rather than ``n_features / 3``. The latter was originally suggested in
[1], whereas the former was more recently justified empirically in [2].

References
----------
.. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001.

.. [2] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized
       trees", Machine Learning, 63(1), 3-42, 2006.

Examples
--------
>>> from sklearn.ensemble import RandomForestRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_features=4, n_informative=2,
...                        random_state=0, shuffle=False)
>>> regr = RandomForestRegressor(max_depth=2, random_state=0)
>>> regr.fit(X, y)
RandomForestRegressor(...)
>>> print(regr.predict([[0, 0, 0, 0]]))
[-8.32987858]
r   r  squared_errorNr   r-   rx   ry   TFr   r   r  r  r  r  r  r  r  rh   r|   r}   rG   rm   r~   r  r<   r  c                   > [         TU ]  [        5       USU
UUUUUUS9
  X l        X0l        X@l        XPl        X`l        Xpl        Xl	        Xl
        UU l        UU l        g Nr  
r   r{   r   rh   r|   r}   rG   rm   r~   r<   )r   r   r   r   r  r  r  r  r  r  r  r  r  r   r{   r   r  r  r  r  r  r  r  rh   r|   r}   rG   rm   r~   r  r<   r  r   s                      r>   r   RandomForestRegressor.__init__[  s{    , 	+-%  %!#- 	 	
2 #"!2 0(@%(,%:""*r@   r  r  r   r  r  r  r  rj  r   r   r  r  r  r   r  r   r!  s   @r>   r3   r3   #  s    ob	$

0
0$

6
6$D  z* 8+ "!$!)8+ 8+r@   r3   c                      ^  \ rS rSr% Sr0 \R                  E\R                  ES\" SS15      \	\
S/0Er\	\S'   \R                  S5         SS	SS
SSSSSSSSSSSSSSSS.U 4S jjjrSrU =r$ )r0   i  a0  
An extra-trees classifier.

This class implements a meta estimator that fits a number of
randomized decision trees (a.k.a. extra-trees) on various sub-samples
of the dataset and uses averaging to improve the predictive accuracy
and control over-fitting.

This estimator has native support for missing values (NaNs) for
random splits. During training, a random threshold will be chosen
to split the non-missing values on. Then the non-missing values will be sent
to the left and right child based on the randomly selected threshold, while
the missing values will also be randomly sent to the left or right child.
This is repeated for every feature considered at each split. The best split
among these is chosen.

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

Parameters
----------
n_estimators : int, default=100
    The number of trees in the forest.

    .. versionchanged:: 0.22
       The default value of ``n_estimators`` changed from 10 to 100
       in 0.22.

criterion : {"gini", "entropy", "log_loss"}, default="gini"
    The function to measure the quality of a split. Supported criteria are
    "gini" for the Gini impurity and "log_loss" and "entropy" both for the
    Shannon information gain, see :ref:`tree_mathematical_formulation`.
    Note: This parameter is tree-specific.

max_depth : int, default=None
    The maximum depth of the tree. If None, then nodes are expanded until
    all leaves are pure or until all leaves contain less than
    min_samples_split samples.

min_samples_split : int or float, default=2
    The minimum number of samples required to split an internal node:

    - If int, then consider `min_samples_split` as the minimum number.
    - If float, then `min_samples_split` is a fraction and
      `ceil(min_samples_split * n_samples)` are the minimum
      number of samples for each split.

    .. versionchanged:: 0.18
       Added float values for fractions.

min_samples_leaf : int or float, default=1
    The minimum number of samples required to be at a leaf node.
    A split point at any depth will only be considered if it leaves at
    least ``min_samples_leaf`` training samples in each of the left and
    right branches.  This may have the effect of smoothing the model,
    especially in regression.

    - If int, then consider `min_samples_leaf` as the minimum number.
    - If float, then `min_samples_leaf` is a fraction and
      `ceil(min_samples_leaf * n_samples)` are the minimum
      number of samples for each node.

    .. versionchanged:: 0.18
       Added float values for fractions.

min_weight_fraction_leaf : float, default=0.0
    The minimum weighted fraction of the sum total of weights (of all
    the input samples) required to be at a leaf node. Samples have
    equal weight when sample_weight is not provided.

max_features : {"sqrt", "log2", None}, int or float, default="sqrt"
    The number of features to consider when looking for the best split:

    - If int, then consider `max_features` features at each split.
    - If float, then `max_features` is a fraction and
      `max(1, int(max_features * n_features_in_))` features are considered at each
      split.
    - If "sqrt", then `max_features=sqrt(n_features)`.
    - If "log2", then `max_features=log2(n_features)`.
    - If None, then `max_features=n_features`.

    .. versionchanged:: 1.1
        The default of `max_features` changed from `"auto"` to `"sqrt"`.

    Note: the search for a split does not stop until at least one
    valid partition of the node samples is found, even if it requires to
    effectively inspect more than ``max_features`` features.

max_leaf_nodes : int, default=None
    Grow trees with ``max_leaf_nodes`` in best-first fashion.
    Best nodes are defined as relative reduction in impurity.
    If None then unlimited number of leaf nodes.

min_impurity_decrease : float, default=0.0
    A node will be split if this split induces a decrease of the impurity
    greater than or equal to this value.

    The weighted impurity decrease equation is the following::

        N_t / N * (impurity - N_t_R / N_t * right_impurity
                            - N_t_L / N_t * left_impurity)

    where ``N`` is the total number of samples, ``N_t`` is the number of
    samples at the current node, ``N_t_L`` is the number of samples in the
    left child, and ``N_t_R`` is the number of samples in the right child.

    ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
    if ``sample_weight`` is passed.

    .. versionadded:: 0.19

bootstrap : bool, default=False
    Whether bootstrap samples are used when building trees. If False, the
    whole dataset is used to build each tree.

oob_score : bool or callable, default=False
    Whether to use out-of-bag samples to estimate the generalization score.
    By default, :func:`~sklearn.metrics.accuracy_score` is used.
    Provide a callable with signature `metric(y_true, y_pred)` to use a
    custom metric. Only available if `bootstrap=True`.

    For an illustration of out-of-bag (OOB) error estimation, see the example
    :ref:`sphx_glr_auto_examples_ensemble_plot_ensemble_oob.py`.

n_jobs : int, default=None
    The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,
    :meth:`decision_path` and :meth:`apply` are all parallelized over the
    trees. ``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 3 sources of randomness:

    - the bootstrapping of the samples used when building trees
      (if ``bootstrap=True``)
    - the sampling of the features to consider when looking for the best
      split at each node (if ``max_features < n_features``)
    - the draw of the splits for each of the `max_features`

    See :term:`Glossary <random_state>` for details.

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

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 forest. See :term:`Glossary <warm_start>` and
    :ref:`tree_ensemble_warm_start` for details.

class_weight : {"balanced", "balanced_subsample"}, dict or list of dicts,             default=None
    Weights associated with classes in the form ``{class_label: weight}``.
    If not given, all classes are supposed to have weight one. For
    multi-output problems, a list of dicts can be provided in the same
    order as the columns of y.

    Note that for multioutput (including multilabel) weights should be
    defined for each class of every column in its own dict. For example,
    for four-class multilabel classification weights should be
    [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of
    [{1:1}, {2:5}, {3:1}, {4:1}].

    The "balanced" mode uses the values of y to automatically adjust
    weights inversely proportional to class frequencies in the input data
    as ``n_samples / (n_classes * np.bincount(y))``

    The "balanced_subsample" mode is the same as "balanced" except that
    weights are computed based on the bootstrap sample for every tree
    grown.

    For multi-output, the weights of each column of y will be multiplied.

    Note that these weights will be multiplied with sample_weight (passed
    through the fit method) if sample_weight is specified.

ccp_alpha : non-negative float, default=0.0
    Complexity parameter used for Minimal Cost-Complexity Pruning. The
    subtree with the largest cost complexity that is smaller than
    ``ccp_alpha`` will be chosen. By default, no pruning is performed. See
    :ref:`minimal_cost_complexity_pruning` for details. See
    :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py`
    for an example of such pruning.

    .. versionadded:: 0.22

max_samples : int or float, default=None
    If bootstrap is True, the number of samples to draw from X
    to train each base estimator.

    - If None (default), then draw `X.shape[0]` samples.
    - If int, then draw `max_samples` samples.
    - If float, then draw `max_samples * X.shape[0]` samples. Thus,
      `max_samples` should be in the interval `(0.0, 1.0]`.

    .. versionadded:: 0.22

monotonic_cst : array-like of int of shape (n_features), default=None
    Indicates the monotonicity constraint to enforce on each feature.
      - 1: monotonically increasing
      - 0: no constraint
      - -1: monotonically decreasing

    If monotonic_cst is None, no constraints are applied.

    Monotonicity constraints are not supported for:
      - multiclass classifications (i.e. when `n_classes > 2`),
      - multioutput classifications (i.e. when `n_outputs_ > 1`),
      - classifications trained on data with missing values.

    The constraints hold over the probability of the positive class.

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

    .. versionadded:: 1.4

Attributes
----------
estimator_ : :class:`~sklearn.tree.ExtraTreeClassifier`
    The child estimator template used to create the collection of fitted
    sub-estimators.

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

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

classes_ : ndarray of shape (n_classes,) or a list of such arrays
    The classes labels (single output problem), or a list of arrays of
    class labels (multi-output problem).

n_classes_ : int or list
    The number of classes (single output problem), or a list containing the
    number of classes for each output (multi-output problem).

feature_importances_ : ndarray of shape (n_features,)
    The impurity-based feature importances.
    The higher, the more important the feature.
    The importance of a feature is computed as the (normalized)
    total reduction of the criterion brought by that feature.  It is also
    known as the Gini importance.

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

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

n_outputs_ : int
    The number of outputs when ``fit`` is performed.

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) or             (n_samples, n_classes, n_outputs)
    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.

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.

    .. versionadded:: 1.4

See Also
--------
ExtraTreesRegressor : An extra-trees regressor with random splits.
RandomForestClassifier : A random forest classifier with optimal splits.
RandomForestRegressor : Ensemble regressor using trees with optimal splits.

Notes
-----
The default values for the parameters controlling the size of the trees
(e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
unpruned trees which can potentially be very large on some data sets. To
reduce memory consumption, the complexity and size of the trees should be
controlled by setting those parameter values.

References
----------
.. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized
       trees", Machine Learning, 63(1), 3-42, 2006.

Examples
--------
>>> from sklearn.ensemble import ExtraTreesClassifier
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_features=4, random_state=0)
>>> clf = ExtraTreesClassifier(n_estimators=100, random_state=0)
>>> clf.fit(X, y)
ExtraTreesClassifier(random_state=0)
>>> clf.predict([[0, 0, 0, 0]])
array([1])
rn   r[   r\   Nr   r  r  r   r-   rx   r  Fr   r  c                   > [         TU ]  [        5       USU
UUUUUUUS9  X l        X0l        X@l        XPl        X`l        Xpl        Xl	        Xl
        UU l        UU l        g r  )r   r   r   r   r  r  r  r  r  r  r  r  r  r  s                       r>   r   ExtraTreesClassifier.__init__  s~    . 	)+%  %!%#/ 	 	
4 #"!2 0(@%(,%:""*r@   r  r  r  r!  s   @r>   r0   r0     s    tl		$

1
1	$
 
7
7	$ 	,j9:	
	$D 	 z* :+ !$!+:+ :+r@   r0   c                      ^  \ rS rSr% Sr0 \R                  E\R                  Er\\	S'   \R                  S5         SSSSSS	S
SS	SSSSSSS	SSS.U 4S jjjrSrU =r$ )r1   i	  a0,  
An extra-trees regressor.

This class implements a meta estimator that fits a number of
randomized decision trees (a.k.a. extra-trees) on various sub-samples
of the dataset and uses averaging to improve the predictive accuracy
and control over-fitting.

This estimator has native support for missing values (NaNs) for
random splits. During training, a random threshold will be chosen
to split the non-missing values on. Then the non-missing values will be sent
to the left and right child based on the randomly selected threshold, while
the missing values will also be randomly sent to the left or right child.
This is repeated for every feature considered at each split. The best split
among these is chosen.

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

Parameters
----------
n_estimators : int, default=100
    The number of trees in the forest.

    .. versionchanged:: 0.22
       The default value of ``n_estimators`` changed from 10 to 100
       in 0.22.

criterion : {"squared_error", "absolute_error", "friedman_mse", "poisson"},             default="squared_error"
    The function to measure the quality of a split. Supported criteria
    are "squared_error" for the mean squared error, which is equal to
    variance reduction as feature selection criterion and minimizes the L2
    loss using the mean of each terminal node, "friedman_mse", which uses
    mean squared error with Friedman's improvement score for potential
    splits, "absolute_error" for the mean absolute error, which minimizes
    the L1 loss using the median of each terminal node, and "poisson" which
    uses reduction in Poisson deviance to find splits.
    Training using "absolute_error" is significantly slower
    than when using "squared_error".

    .. versionadded:: 0.18
       Mean Absolute Error (MAE) criterion.

max_depth : int, default=None
    The maximum depth of the tree. If None, then nodes are expanded until
    all leaves are pure or until all leaves contain less than
    min_samples_split samples.

min_samples_split : int or float, default=2
    The minimum number of samples required to split an internal node:

    - If int, then consider `min_samples_split` as the minimum number.
    - If float, then `min_samples_split` is a fraction and
      `ceil(min_samples_split * n_samples)` are the minimum
      number of samples for each split.

    .. versionchanged:: 0.18
       Added float values for fractions.

min_samples_leaf : int or float, default=1
    The minimum number of samples required to be at a leaf node.
    A split point at any depth will only be considered if it leaves at
    least ``min_samples_leaf`` training samples in each of the left and
    right branches.  This may have the effect of smoothing the model,
    especially in regression.

    - If int, then consider `min_samples_leaf` as the minimum number.
    - If float, then `min_samples_leaf` is a fraction and
      `ceil(min_samples_leaf * n_samples)` are the minimum
      number of samples for each node.

    .. versionchanged:: 0.18
       Added float values for fractions.

min_weight_fraction_leaf : float, default=0.0
    The minimum weighted fraction of the sum total of weights (of all
    the input samples) required to be at a leaf node. Samples have
    equal weight when sample_weight is not provided.

max_features : {"sqrt", "log2", None}, int or float, default=1.0
    The number of features to consider when looking for the best split:

    - If int, then consider `max_features` features at each split.
    - If float, then `max_features` is a fraction and
      `max(1, int(max_features * n_features_in_))` features are considered at each
      split.
    - If "sqrt", then `max_features=sqrt(n_features)`.
    - If "log2", then `max_features=log2(n_features)`.
    - If None or 1.0, then `max_features=n_features`.

    .. note::
        The default of 1.0 is equivalent to bagged trees and more
        randomness can be achieved by setting smaller values, e.g. 0.3.

    .. versionchanged:: 1.1
        The default of `max_features` changed from `"auto"` to 1.0.

    Note: the search for a split does not stop until at least one
    valid partition of the node samples is found, even if it requires to
    effectively inspect more than ``max_features`` features.

max_leaf_nodes : int, default=None
    Grow trees with ``max_leaf_nodes`` in best-first fashion.
    Best nodes are defined as relative reduction in impurity.
    If None then unlimited number of leaf nodes.

min_impurity_decrease : float, default=0.0
    A node will be split if this split induces a decrease of the impurity
    greater than or equal to this value.

    The weighted impurity decrease equation is the following::

        N_t / N * (impurity - N_t_R / N_t * right_impurity
                            - N_t_L / N_t * left_impurity)

    where ``N`` is the total number of samples, ``N_t`` is the number of
    samples at the current node, ``N_t_L`` is the number of samples in the
    left child, and ``N_t_R`` is the number of samples in the right child.

    ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
    if ``sample_weight`` is passed.

    .. versionadded:: 0.19

bootstrap : bool, default=False
    Whether bootstrap samples are used when building trees. If False, the
    whole dataset is used to build each tree.

oob_score : bool or callable, default=False
    Whether to use out-of-bag samples to estimate the generalization score.
    By default, :func:`~sklearn.metrics.r2_score` is used.
    Provide a callable with signature `metric(y_true, y_pred)` to use a
    custom metric. Only available if `bootstrap=True`.

    For an illustration of out-of-bag (OOB) error estimation, see the example
    :ref:`sphx_glr_auto_examples_ensemble_plot_ensemble_oob.py`.

n_jobs : int, default=None
    The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,
    :meth:`decision_path` and :meth:`apply` are all parallelized over the
    trees. ``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 3 sources of randomness:

    - the bootstrapping of the samples used when building trees
      (if ``bootstrap=True``)
    - the sampling of the features to consider when looking for the best
      split at each node (if ``max_features < n_features``)
    - the draw of the splits for each of the `max_features`

    See :term:`Glossary <random_state>` for details.

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

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 forest. See :term:`Glossary <warm_start>` and
    :ref:`tree_ensemble_warm_start` for details.

ccp_alpha : non-negative float, default=0.0
    Complexity parameter used for Minimal Cost-Complexity Pruning. The
    subtree with the largest cost complexity that is smaller than
    ``ccp_alpha`` will be chosen. By default, no pruning is performed. See
    :ref:`minimal_cost_complexity_pruning` for details. See
    :ref:`sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py`
    for an example of such pruning.

    .. versionadded:: 0.22

max_samples : int or float, default=None
    If bootstrap is True, the number of samples to draw from X
    to train each base estimator.

    - If None (default), then draw `X.shape[0]` samples.
    - If int, then draw `max_samples` samples.
    - If float, then draw `max_samples * X.shape[0]` samples. Thus,
      `max_samples` should be in the interval `(0.0, 1.0]`.

    .. versionadded:: 0.22

monotonic_cst : array-like of int of shape (n_features), default=None
    Indicates the monotonicity constraint to enforce on each feature.
      - 1: monotonically increasing
      - 0: no constraint
      - -1: monotonically decreasing

    If monotonic_cst is None, no constraints are applied.

    Monotonicity constraints are not supported for:
      - multioutput regressions (i.e. when `n_outputs_ > 1`),
      - regressions trained on data with missing values.

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

    .. versionadded:: 1.4

Attributes
----------
estimator_ : :class:`~sklearn.tree.ExtraTreeRegressor`
    The child estimator template used to create the collection of fitted
    sub-estimators.

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

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

feature_importances_ : ndarray of shape (n_features,)
    The impurity-based feature importances.
    The higher, the more important the feature.
    The importance of a feature is computed as the (normalized)
    total reduction of the criterion brought by that feature.  It is also
    known as the Gini importance.

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

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

n_outputs_ : int
    The number of outputs.

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,) or (n_samples, n_outputs)
    Prediction computed with out-of-bag estimate on the training set.
    This attribute exists only when ``oob_score`` is True.

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.

    .. versionadded:: 1.4

See Also
--------
ExtraTreesClassifier : An extra-trees classifier with random splits.
RandomForestClassifier : A random forest classifier with optimal splits.
RandomForestRegressor : Ensemble regressor using trees with optimal splits.

Notes
-----
The default values for the parameters controlling the size of the trees
(e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
unpruned trees which can potentially be very large on some data sets. To
reduce memory consumption, the complexity and size of the trees should be
controlled by setting those parameter values.

References
----------
.. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees",
       Machine Learning, 63(1), 3-42, 2006.

Examples
--------
>>> from sklearn.datasets import load_diabetes
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.ensemble import ExtraTreesRegressor
>>> X, y = load_diabetes(return_X_y=True)
>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, random_state=0)
>>> reg = ExtraTreesRegressor(n_estimators=100, random_state=0).fit(
...    X_train, y_train)
>>> reg.score(X_test, y_test)
0.2727...
r   r  r  Nr   r-   rx   ry   Fr   r  c                   > [         TU ]  [        5       USU
UUUUUUS9
  X l        X0l        X@l        XPl        X`l        Xpl        Xl	        Xl
        UU l        UU l        g r  )r   r   r   r   r  r  r  r  r  r  r  r  r  r  s                      r>   r   ExtraTreesRegressor.__init__:
  s{    , 	(*%  %!#- 	 	
2 #"!2 0(@%(,%:""*r@   r  r  r  r!  s   @r>   r1   r1   	  s    [z$

0
0$

6
6$D  z* 8+ "!$!)8+ 8+r@   r1   c                   0  ^  \ rS rSr% Sr\" \SSSS9/\S/S/S/S	.\R                  ES
S/0Er\	\
S'   S H  r\R                  \5        M     SrSr SSSSSSSSSSSSS.U 4S jjjrSS jrS S jr\" SS9S U 4S jj5       rSS jrS rU 4S jrSrU =r$ )!r4   iu
  a  
An ensemble of totally random trees.

An unsupervised transformation of a dataset to a high-dimensional
sparse representation. A datapoint is coded according to which leaf of
each tree it is sorted into. Using a one-hot encoding of the leaves,
this leads to a binary coding with as many ones as there are trees in
the forest.

The dimensionality of the resulting representation is
``n_out <= n_estimators * max_leaf_nodes``. If ``max_leaf_nodes == None``,
the number of leaf nodes is at most ``n_estimators * 2 ** max_depth``.

For an example of applying Random Trees Embedding to non-linear
classification, see
:ref:`sphx_glr_auto_examples_ensemble_plot_random_forest_embedding.py`.

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

Parameters
----------
n_estimators : int, default=100
    Number of trees in the forest.

    .. versionchanged:: 0.22
       The default value of ``n_estimators`` changed from 10 to 100
       in 0.22.

max_depth : int, default=5
    The maximum depth of each tree. If None, then nodes are expanded until
    all leaves are pure or until all leaves contain less than
    min_samples_split samples.

min_samples_split : int or float, default=2
    The minimum number of samples required to split an internal node:

    - If int, then consider `min_samples_split` as the minimum number.
    - If float, then `min_samples_split` is a fraction and
      `ceil(min_samples_split * n_samples)` is the minimum
      number of samples for each split.

    .. versionchanged:: 0.18
       Added float values for fractions.

min_samples_leaf : int or float, default=1
    The minimum number of samples required to be at a leaf node.
    A split point at any depth will only be considered if it leaves at
    least ``min_samples_leaf`` training samples in each of the left and
    right branches.  This may have the effect of smoothing the model,
    especially in regression.

    - If int, then consider `min_samples_leaf` as the minimum number.
    - If float, then `min_samples_leaf` is a fraction and
      `ceil(min_samples_leaf * n_samples)` is the minimum
      number of samples for each node.

    .. versionchanged:: 0.18
       Added float values for fractions.

min_weight_fraction_leaf : float, default=0.0
    The minimum weighted fraction of the sum total of weights (of all
    the input samples) required to be at a leaf node. Samples have
    equal weight when sample_weight is not provided.

max_leaf_nodes : int, default=None
    Grow trees with ``max_leaf_nodes`` in best-first fashion.
    Best nodes are defined as relative reduction in impurity.
    If None then unlimited number of leaf nodes.

min_impurity_decrease : float, default=0.0
    A node will be split if this split induces a decrease of the impurity
    greater than or equal to this value.

    The weighted impurity decrease equation is the following::

        N_t / N * (impurity - N_t_R / N_t * right_impurity
                            - N_t_L / N_t * left_impurity)

    where ``N`` is the total number of samples, ``N_t`` is the number of
    samples at the current node, ``N_t_L`` is the number of samples in the
    left child, and ``N_t_R`` is the number of samples in the right child.

    ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
    if ``sample_weight`` is passed.

    .. versionadded:: 0.19

sparse_output : bool, default=True
    Whether or not to return a sparse CSR matrix, as default behavior,
    or to return a dense array compatible with dense pipeline operators.

n_jobs : int, default=None
    The number of jobs to run in parallel. :meth:`fit`, :meth:`transform`,
    :meth:`decision_path` and :meth:`apply` are all parallelized over the
    trees. ``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 generation of the random `y` used to fit the trees
    and the draw of the splits for each feature at the trees' nodes.
    See :term:`Glossary <random_state>` for details.

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

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 forest. See :term:`Glossary <warm_start>` and
    :ref:`tree_ensemble_warm_start` for details.

Attributes
----------
estimator_ : :class:`~sklearn.tree.ExtraTreeRegressor` instance
    The child estimator template used to create the collection of fitted
    sub-estimators.

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

estimators_ : list of :class:`~sklearn.tree.ExtraTreeRegressor` instances
    The collection of fitted sub-estimators.

feature_importances_ : ndarray of shape (n_features,)
    The feature importances (the higher, the more important the feature).

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

n_outputs_ : int
    The number of outputs when ``fit`` is performed.

one_hot_encoder_ : OneHotEncoder instance
    One-hot encoder used to create the sparse embedding.

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.

    .. versionadded:: 1.4

See Also
--------
ExtraTreesClassifier : An extra-trees classifier.
ExtraTreesRegressor : An extra-trees regressor.
RandomForestClassifier : A random forest classifier.
RandomForestRegressor : A random forest regressor.
sklearn.tree.ExtraTreeClassifier: An extremely randomized
    tree classifier.
sklearn.tree.ExtraTreeRegressor : An extremely randomized
    tree regressor.

References
----------
.. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees",
       Machine Learning, 63(1), 3-42, 2006.
.. [2] Moosmann, F. and Triggs, B. and Jurie, F.  "Fast discriminative
       visual codebooks using randomized clustering forests"
       NIPS 2007

Examples
--------
>>> from sklearn.ensemble import RandomTreesEmbedding
>>> X = [[0,0], [1,0], [0,1], [-1,0], [0,-1]]
>>> random_trees = RandomTreesEmbedding(
...    n_estimators=5, random_state=0, max_depth=1).fit(X)
>>> X_sparse_embedding = random_trees.transform(X)
>>> X_sparse_embedding.toarray()
array([[0., 1., 1., 0., 1., 0., 0., 1., 1., 0.],
       [0., 1., 1., 0., 1., 0., 0., 1., 1., 0.],
       [0., 1., 0., 1., 0., 1., 0., 1., 0., 1.],
       [1., 0., 1., 0., 1., 0., 1., 0., 1., 0.],
       [0., 1., 1., 0., 1., 0., 0., 1., 1., 0.]])
r-   Nrt   ru   rm   rw   )r{   r}   rm   r~   sparse_outputr   )r  r  r  r  r     r   rx   Tr   F)r  r  r  r  r  r  r  r}   rG   rm   r~   c                   > [         TU ]  [        5       USSSU	U
UUS S9
  X l        X0l        X@l        XPl        X`l        Xpl        Xl	        g )N)	r   r  r  r  r  r  r  r  rG   Fr  )
r   r   r   r  r  r  r  r  r  r  )r   r{   r  r  r  r  r  r  r  r}   rG   rm   r~   r   s                r>   r   RandomTreesEmbedding.__init__<  sg      	(*%
 %!) 	 	
. #!2 0(@%,%:"*r@   c                     [        S5      e)Nz)OOB score not supported by tree embedding)NotImplementedErrorr   s       r>   r   2RandomTreesEmbedding._set_oob_score_and_attributesk  s    !"MNNr@   c                 &    U R                  XUS9  U $ )a1  
Fit estimator.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    The input samples. Use ``dtype=np.float32`` for maximum
    efficiency. Sparse matrices are also supported, use sparse
    ``csc_matrix`` for maximum efficiency.

y : Ignored
    Not used, present for API consistency by convention.

sample_weight : array-like of shape (n_samples,), default=None
    Sample weights. If None, then samples are equally weighted. Splits
    that would create child nodes with net zero or negative weight are
    ignored while searching for a split in each node. In the case of
    classification, splits are also ignored if they would result in any
    single class carrying a negative weight in either child node.

Returns
-------
self : object
    Returns the instance itself.
r]   )fit_transform)r   ri   rj   r]   s       r>   r   RandomTreesEmbedding.fitn  s    6 	1}=r@   r   c                 *  > [        U R                  5      nUR                  [        U5      S9n[        TU ]  XUS9  [        U R                  S9U l        U R                  R                  U R                  U5      5      nUR                  S   U l        U$ )a   
Fit estimator and transform dataset.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    Input data used to build forests. Use ``dtype=np.float32`` for
    maximum efficiency.

y : Ignored
    Not used, present for API consistency by convention.

sample_weight : array-like of shape (n_samples,), default=None
    Sample weights. If None, then samples are equally weighted. Splits
    that would create child nodes with net zero or negative weight are
    ignored while searching for a split in each node. In the case of
    classification, splits are also ignored if they would result in any
    single class carrying a negative weight in either child node.

Returns
-------
X_transformed : sparse matrix of shape (n_samples, n_out)
    Transformed dataset.
r   r  )r  r-   )r   rG   uniformr*   r   r   r   r  one_hot_encoder_r  r   ra   _n_features_out)r   ri   rj   r]   rndoutputr   s         r>   r  "RandomTreesEmbedding.fit_transform  s    4 !!2!23KK\!_K-A6 -D<N<N O&&44TZZ]C%||Ar@   c           	         [        U S5        [        XSS9  [        U R                  5       VVs/ s H,  nU R                  R
                  U     H  nSU SU 3PM     M.     nnn[        R                  " U[        S9$ s  snnf )a  Get output feature names for transformation.

Parameters
----------
input_features : array-like of str or None, default=None
    Only used to validate feature names with the names seen in :meth:`fit`.

Returns
-------
feature_names_out : ndarray of str objects
    Transformed feature names, in the format of
    `randomtreesembedding_{tree}_{leaf}`, where `tree` is the tree used
    to generate the leaf and `leaf` is the index of a leaf node
    in that tree. Note that the node indexing scheme is used to
    index both nodes with children (split nodes) and leaf nodes.
    Only the latter can be present as output features.
    As a consequence, there are missing indices in the output
    feature names.
r  F)input_featuresgenerate_namesrandomtreesembedding_rZ  rB   )	r+   r(   r   r{   r  categories_rE   r3  object)r   r  rg   leaffeature_namess        r>   get_feature_names_out*RandomTreesEmbedding.get_feature_names_out  s    ( 	/0	
 d//0
0--99$? $D64&1? 20 	 

 zz-v66
s   3A>c                 l    [        U 5        U R                  R                  U R                  U5      5      $ )a  
Transform dataset.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    Input data to be transformed. Use ``dtype=np.float32`` for maximum
    efficiency. Sparse matrices are also supported, use sparse
    ``csr_matrix`` for maximum efficiency.

Returns
-------
X_transformed : sparse matrix of shape (n_samples, n_out)
    Transformed dataset.
)r+   r  	transformr   )r   ri   s     r>   r  RandomTreesEmbedding.transform  s+      	$$..tzz!}==r@   c                 F   > [         TU ]  5       nSUR                  l        U$ rb  r  rf  s     r>   r  %RandomTreesEmbedding.__sklearn_tags__  r  r@   )	r  r  r  r  r  r  r  r  r  r  r   )NN)r   r  r  r  r  r    r   r   r   r  r  paramr  r   r  r   r   r   r   r  r  r  r  r  r   r!  s   @r>   r4   r4   u
  s    vr "(AtFCDT"; k	$
 
1
1$ 	)$D  L""5) L  IL -+ !$!-+ -+^O< 5  6 D7@>& r@   r4   )r   NNN)Sr  rX  abcr   r   numbersr   r   warningsr   r   r	   numpyrE   scipy.sparser
   r   r   baser   r   r   r   r   r   
exceptionsr   metricsr   r   preprocessingr   rg   r   r   r   r   r   
tree._treer   r   utilsr   r   utils._param_validationr    r!   r"   utils._tagsr#   utils.multiclassr$   r%   utils.parallelr&   r'   utils.validationr(   r)   r*   r+   r,   _baser.   r/   __all__iinforF   r9   r   r?   rK   rU   rp   rr   r(  r*  rj  r2   r3   r0   r1   r4   r   r@   r>   <module>r     s=   J  ' " 7 7  0 !  / . )  ' = F F " K .  7 ((288

 
 6B	, #'6rA!<7 AH( J
g JZcnjG cLJ#- J#Zp+O p+f}++ }+@\+/ \+~
p+Z pr@   