
    -iV                    0   S r SSKrSSKrSSKJrJr  SSKJrJr  SSK	J	r	  SSK
rSSKJrJrJr  SSKJrJrJrJrJrJrJrJr  SS	KJrJrJrJr  SS
KJrJ r   SSK!J"r"  SSK#J$r$  SSK%J&r&  SSK'J(r(  SSK)J*r*J+r+J,r,  SSK-J.r.J/r/J0r0  SSK1J2r2J3r3J4r4  SSK5J6r6  SSK7J8r8  SSK9J:r:J;r;J<r<  SSK=J>r>  SSK?J@r@JArAJBrB  \R                  " 5       r\R                  " \\S.5        S rES rF  S&S jrGS'S jrH " S S5      rI " S S \>\S!9rJ " S" S#\\J5      rK " S$ S%\\J5      rLg)(a?  Gradient Boosted Regression Trees.

This module contains methods for fitting gradient boosted regression trees for
both classification and regression.

The module structure is the following:

- The ``BaseGradientBoosting`` base class implements a common ``fit`` method
  for all the estimators in the module. Regression and classification
  only differ in the concrete ``LossFunction`` used.

- ``GradientBoostingClassifier`` implements gradient boosting for
  classification problems.

- ``GradientBoostingRegressor`` implements gradient boosting for
  regression problems.
    N)ABCMetaabstractmethod)IntegralReal)time)
csc_matrix
csr_matrixissparse   )_LOSSESAbsoluteErrorExponentialLossHalfBinomialLossHalfMultinomialLossHalfSquaredError	HuberLossPinballLoss)ClassifierMixinRegressorMixin_fit_contextis_classifier)DummyClassifierDummyRegressor)NotFittedError)train_test_split)LabelEncoder)DecisionTreeRegressor)DOUBLEDTYPE	TREE_LEAF)check_arraycheck_random_statecolumn_or_1d)
HasMethodsInterval
StrOptions)check_classification_targets)_weighted_percentile)_check_sample_weightcheck_is_fittedvalidate_data   )BaseEnsemble)_random_sample_maskpredict_stagepredict_stagesquantilehuberc                     [        U5      S:  a  g[        U 5      [        U5      -  n[        U 5      [        U5      -  n[        R                  " U5      (       a  [        R
                  " S[        5        U$ )z'Prevents overflow and division by zero.gu?j/         z$overflow encountered in _safe_divide)absfloatmathisinfwarningswarnRuntimeWarning)	numeratordenominatorresults      G/var/www/html/venv/lib/python3.13/site-packages/sklearn/ensemble/_gb.py_safe_dividerA   A   sc     ;&  y!E+$66 y!E+$66::fMM@.Q    c                    U(       a  UR                  U 5      nUR                  (       d	  USS2S4   n[        R                  " [        R                  5      R
                  n[        R                  " XESU-
  [        R                  S9nO.UR                  U 5      R                  [        R                  5      nUR                  S:X  a+  UR                  R                  U5      R                  SS5      $ UR                  R                  U5      $ )ay  Return the initial raw predictions.

Parameters
----------
X : ndarray of shape (n_samples, n_features)
    The data array.
estimator : object
    The estimator to use to compute the predictions.
loss : BaseLoss
    An instance of a loss function class.
use_predict_proba : bool
    Whether estimator.predict_proba is used instead of estimator.predict.

Returns
-------
raw_predictions : ndarray of shape (n_samples, K)
    The initial raw predictions. K is equal to 1 for binary
    classification and regression, and equal to the number of classes
    for multiclass classification. ``raw_predictions`` is casted
    into float64.
Nr,   dtype)predict_probais_multiclassnpfinfofloat32epsclipfloat64predictastypendimlinkreshape)X	estimatorlossuse_predict_probapredictionsrL   s         r@   _init_raw_predictionsrY   V   s    2   --a0!!%ad+Khhrzz"&&ggkCrzzJ''*11"**=1yy~~k*222q99yy~~k**rB   c
           	        ^ ^ UR                  U5      n
[        T [        5      (       d  U
R                  5       nSX) '   [        T [        5      (       a  U4S jnO@[        T [
        5      (       a  U U4S jnO#[        T [        5      (       a  U4S jnOU U4S jn[        R                  " UR                  [        :H  5      S    HS  n[        R                  " X:H  5      S   nUR                  USS9nUc  SOXn   mU" XXEU	5      nUUR                  USS4'   MU     USS2U	4==   XR                  SS2SS4   R                  U
SS9-  -  ss'   g)	a  Update the leaf values to be predicted by the tree and raw_prediction.

The current raw predictions of the model (of this stage) are updated.

Additionally, the terminal regions (=leaves) of the given tree are updated as well.
This corresponds to the line search step in "Greedy Function Approximation" by
Friedman, Algorithm 1 step 5.

Update equals:
    argmin_{x} loss(y_true, raw_prediction_old + x * tree.value)

For non-trivial cases like the Binomial loss, the update has no closed formula and
is an approximation, again, see the Friedman paper.

Also note that the update formula for the SquaredError is the identity. Therefore,
in this case, the leaf values don't need an update and only the raw_predictions are
updated (with the learning rate included).

Parameters
----------
loss : BaseLoss
tree : tree.Tree
    The tree object.
X : ndarray of shape (n_samples, n_features)
    The data array.
y : ndarray of shape (n_samples,)
    The target labels.
neg_gradient : ndarray of shape (n_samples,)
    The negative gradient.
raw_prediction : ndarray of shape (n_samples, n_trees_per_iteration)
    The raw predictions (i.e. values from the tree leaves) of the
    tree ensemble at iteration ``i - 1``.
sample_weight : ndarray of shape (n_samples,)
    The weight of each sample.
sample_mask : ndarray of shape (n_samples,)
    The sample mask to be used.
learning_rate : float, default=0.1
    Learning rate shrinks the contribution of each tree by
     ``learning_rate``.
k : int, default=0
    The index of the estimator being updated.
rF   c                    > UR                  USS9nX-
  n[        R                  " UT	S9n[        R                  " USU-
  -  T	S9n[        Xx5      $ Nr   axisweightsr,   )takerI   averagerA   )
y_indicesneg_gradientraw_predictionkneg_gprobr=   r>   sws
            r@   compute_update0_update_terminal_regions.<locals>.compute_update   sU     %))'):zJJub9	 jjT):BG#I;;rB   c                    > UR                  USS9nX-
  nT
R                  n[        R                  " UTS9nXS-
  U-  -  n[        R                  " USU-
  -  TS9n	[	        X5      $ r\   )ra   	n_classesrI   rb   rA   )rc   rd   re   rf   rg   rh   ri   Kr=   r>   rV   rj   s             r@   rk   rl      sn    $))'):zNN JJub9	!eq[(	 jjT):BG#I;;rB   c                    > UR                  USS9n[        R                  " UT	S9nUR                  5       nXpS:H  ==   S-  ss'   [        R                  " UT	S9n[	        Xh5      $ )Nr   r]   r_   rF   )ra   rI   rb   copyrA   )
rc   rd   re   rf   rg   rh   r=   hessianr>   rj   s
            r@   rk   rl      sb    $))'):JJub9	  **,a B&  jj"=#I;;rB   c                 0   > TR                  XX4   -
  TS9$ )N)y_truesample_weight)fit_intercept_only)rc   rd   re   rf   rg   rV   rj   s        r@   rk   rl      s+    ..wz ::"$ /  rB   r   r]   N)apply
isinstancer   rq   r   r   r   rI   nonzerochildren_leftr    ra   value)rV   treerT   yre   rf   ru   sample_masklearning_raterg   terminal_regionsmasked_terminal_regionsrk   leafrd   rc   updaterj   s   `                @r@   _update_terminal_regionsr      sF   n zz!}d,--"2"7"7"902-d,--< 122<" o..
< JJt11Y>?BDjj!8!@AG a(B&.M4JB#BqQF &,DJJtQz" C 1a4MJJq!Qw,?,D,Dq -E -  rB   c                     [         R                  " XR                  5       -
  5      n[        XCSU R                  -  5      n[        U5      U R                  l        g)z:Calculate and set self.closs.delta based on self.quantile.d   N)rI   r6   squeezer(   r2   r7   clossdelta)rV   rt   rf   ru   abserrr   s         r@   set_huber_deltar   
  sA    VVF33556F dmm8KLEU|DJJrB   c                   .    \ rS rSrSrS rSS jrS rSrg)	VerboseReporteri  zReports verbose output to stdout.

Parameters
----------
verbose : int
    Verbosity level. If ``verbose==1`` output is printed once in a while
    (when iteration mod verbose_mod is zero).; if larger than 1 then output
    is printed for each update.
c                     Xl         g Nverbose)selfr   s     r@   __init__VerboseReporter.__init__  s    rB   c                 r   SS/nSS/nUR                   S:  a"  UR                  S5        UR                  S5        UR                  S5        UR                  S	5        [        S
S[        U5      S-
  -  -   [	        U5      -  5        SR                  U5      U l        SU l        [        5       U l	        X l
        g)zInitialize reporter

Parameters
----------
est : Estimator
    The estimator

begin_at_stage : int, default=0
    stage at which to begin reporting
Iterz
Train Lossz{iter:>10d}z{train_score:>16.4f}r,   zOOB Improvez{oob_impr:>16.4f}zRemaining Timez{remaining_time:>16s}z%10s z%16s  N)	subsampleappendprintlentuplejoinverbose_fmtverbose_modr   
start_timebegin_at_stage)r   estr   header_fieldsr   s        r@   initVerboseReporter.init   s      .$&<===1  /23-.23 	wC$6$:;;u]?SST88K0&,rB   c           	      P   UR                   S:  nXR                  -
  nUS-   U R                  -  S:X  a  U(       a  UR                  U   OSnUR                  US-   -
  [        5       U R                  -
  -  [        US-   5      -  nUS:  a  SR                  US-  5      nOSR                  U5      n[        U R                  R                  US-   UR                  U   UUS95        U R                  S:X  a0  US-   U R                  S-  -  S:  a  U =R                  S-  sl        g	g	g	g	)
z}Update reporter with new iteration.

Parameters
----------
j : int
    The new iteration.
est : Estimator
    The estimator.
r,   r   <   z{0:.2f}mg      N@z{0:.2f}s)itertrain_scoreoob_imprremaining_time
   N)r   r   r   oob_improvement_n_estimatorsr   r   r7   formatr   r   train_score_r   )r   jr   do_oobir   r   s          r@   r   VerboseReporter.update>  s5    "###ET%%%*28s++A.aH!!QU+0HIERSVWRWLX  "!+!2!2>D3H!I!+!2!2>!B  ''Q # 0 0 3%#1	 (  ||q q1u$2B2BR2G&H1&L  B&  'M # +rB   )r   r   r   r   r   N)r   )	__name__
__module____qualname____firstlineno____doc__r   r   r   __static_attributes__ rB   r@   r   r     s    -< 'rB   r   c                     ^  \ rS rSr% Sr0 \R                  E\" \SSSS9/\" \	SSSS9/\
" SS	15      /\" \SS
SS9/S/S/\" \SS
SS9/\" \	SSSS9S/\" \SSSS9/S.	Er\\S'   \R                  S5        \R                  S5        \SSSSSSSS.S j5       r\S/S j5       r\S 5       r  S/S jrS rS rS rS  rS! rS" r\" SS#9S/S$ j5       r  S0S% jrS1S& jrS' rS( rS1S) jr\ S* 5       r!S+ r"S, r#U 4S- jr$S.r%U =r&$ )2BaseGradientBoostingia  z*Abstract base class for Gradient Boosting.r5   Nleftclosedr,   friedman_msesquared_error      ?rightr   booleanneither)	r   r   	criterionr   r   
warm_startvalidation_fractionn_iter_no_changetol_parameter_constraintssplittermonotonic_cst?r   F皙?-C6?)alphar   max_leaf_nodesr   r   r   r   c                   X0l         X l        Xl        X@l        XPl        X`l        Xpl        Xl        Xl        Xl	        Xl
        Xl        Xl        Xl        Xl        UU l        UU l        UU l        UU l        UU l        UU l        g r   )r   r   rV   r   min_samples_splitmin_samples_leafmin_weight_fraction_leafr   max_features	max_depthmin_impurity_decrease	ccp_alphar   random_stater   r   r   r   r   r   r   )r   rV   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                         r@   r   BaseGradientBoosting.__init__s  s    4 )*	"!2 0(@%"("%:""	(
,$#6  0rB   c                     g)z'Called by fit to validate and encode y.Nr   r   r}   ru   s      r@   	_encode_yBaseGradientBoosting._encode_y      rB   c                     g)z(Get loss object from sklearn._loss.loss.Nr   r   ru   s     r@   	_get_lossBaseGradientBoosting._get_loss  r   rB   c
                    Un
[        U R                  [        5      (       a  [        U R                  UUUS9  U R                  R	                  UUSS9* nUR
                  S:X  a  UR                  S5      nOUn[        U R                  5       GHN  nU R                  R                  (       a%  [        R                  " X:H  [        R                  S9n[        U R                  SU R                  U R                   U R"                  U R$                  U R&                  U R(                  U R*                  UU R,                  S9nU R.                  S	:  a!  XVR1                  [        R                  5      -  nUb  UOUnUR3                  X,SS2U4   US
S9  U	b  U	OUn[5        U R                  UR6                  UUUSS2U4   UUUU R8                  US9
  XR:                  X4'   GMQ     U$ )z6Fit another stage of ``n_trees_per_iteration_`` trees.)rV   rt   rf   ru   Nrt   rf   ru   r,   )rF   r,   rD   best)r   r   r   r   r   r   r   r   r   r   r   r   F)ru   check_input)r   rg   )rx   _lossr   r   gradientrQ   rS   rangen_trees_per_iteration_rH   rI   arrayrN   r   r   r   r   r   r   r   r   r   r   r   rP   fitr   tree_r   estimators_)r   r   rT   r}   raw_predictionsru   r~   r   X_cscX_csr
original_yre   
neg_g_viewrg   r|   X_for_tree_updates                   r@   
_fit_stageBaseGradientBoosting._fit_stage  s    
djj),,ZZ.+	 

++* , 
 
 !%--g6J%Jt223Azz''HHZ_BJJ? )...."&"8"8!%!6!6)-)F)F&*&@&@!..#22)..D ~~# -0B0B2::0N N*AHHad#=e  
 */):$



!1a4 "00 &*QT"Y 4\ rB   c                    [        U R                  [        5      (       a  U R                  S:X  aQ  [        U 5      (       a4  [	        S[        [        R                  " U R                  5      5      5      nOU R                  nOU R                  S:X  a4  [	        S[        [        R                  " U R                  5      5      5      nO[	        S[        [        R                  " U R                  5      5      5      nOrU R                  c  U R                  nOX[        U R                  [        5      (       a  U R                  nO,[	        S[        U R                  U R                  -  5      5      nXl        g)zSet self.max_features_.autor,   sqrtN)rx   r   strr   maxintrI   r   n_features_in_log2r   max_features_)r   r   s     r@   _set_max_features&BaseGradientBoosting._set_max_features  s   d''--  F* &&#&q#bggd6I6I.J*K#LL#'#6#6L""f,"1c"''$2E2E*F&GH"1c"''$2E2E*F&GH&..L))844,,Lq#d&7&7$:M:M&M"NOL)rB   c                 X   U R                   U l        U R                  c  [        U 5      (       a  [        SS9U l        O|[	        U R
                  [        [        45      (       a  [        SSS9U l        OG[	        U R
                  [        5      (       a  [        SU R                  S9U l        O[        SS9U l        [        R                  " U R                  U R                  4[        S9U l        [        R"                  " U R                  4[        R$                  S9U l        U R(                  S	:  az  [        R"                  " U R                  [        R$                  S9U l        [        R"                  " U R                  [        R$                  S9U l        [        R.                  U l        gg)
z@Initialize model state and allocate model state data structures.Nprior)strategyr2   g      ?)r  r2   meanrD   r   )r   init_r   r   rx   r   r   r   r   r   r   rI   emptyr   r   objectr   zerosrN   r   r   r   oob_scores_nan
oob_score_r   s    r@   _init_state BaseGradientBoosting._init_state  s"    YY
::T"",g>
DJJ	(BCC+Z#N
DJJ44+Z$**U
+V<
88 ; ;<F
 HHd&7&7%9L>>C$&HHd.?.?

$SD!!xx):):2::ND ffDO  rB   c                 H   [        U S5      (       a  [        R                  " S[        S9U l        [        U S5      (       a  U ?[        U S5      (       a  U ?[        U S5      (       a  U ?[        U S5      (       a  U ?[        U S5      (       a  U ?	[        U S	5      (       a  U ?
g
g
)z/Clear the state of the gradient boosting model.r   r   r   rD   r   r   r  r  r
  _rngN)hasattrrI   r  r  r   r   r   r  r  r
  r  r  s    r@   _clear_state!BaseGradientBoosting._clear_state.  s    4''!xxf=D4((!4+,,%4'' 4&&4!!
4  	 !rB   c                 2   U R                   nXR                  R                  S   :  a  [        SXR                  S   4-  5      e[        R
                  " U R                  XR                  45      U l        [        R
                  " U R                  U5      U l        U R                  S:  d  [        U S5      (       a  [        U S5      (       ab  [        R
                  " U R                  U5      U l
        [        R
                  " U R                  U5      U l        [        R                  U l        g[        R                  " U4[        R                  S9U l
        [        R                  " U4[        R                  S9U l        [        R                  U l        gg)z:Add additional ``n_estimators`` entries to all attributes.r   z(resize with smaller n_estimators %d < %dr,   r   rD   N)r   r   shape
ValueErrorrI   resizer   r   r   r  r   r  r  r  r  rN   )r   total_n_estimatorss     r@   _resize_state"BaseGradientBoosting._resize_state?  sG    ".. 0 0 6 6q 99:%'7'7':;< 
 9913N3NO
 IId&7&79KL>>A/A!B!Bt/00(*		))+=)% $&99T-=-=?Q#R "$&&(*'))% $&88-?,A#T "$&& "CrB   c                 4    [        [        U S/ 5      5      S:  $ )Nr   r   )r   getattrr  s    r@   
_is_fittedBaseGradientBoosting._is_fitted\  s    7434q88rB   c                     [        U 5        g)zACheck that the estimator is initialized, raising an error if not.N)r*   r  s    r@   _check_initialized'BaseGradientBoosting._check_initialized_  s
    rB   )prefer_skip_nested_validationc                 :   U R                   (       d  U R                  5         [        U UU/ SQ[        SS9u  pUSL n[	        X15      nU(       a  U R                  USS9nOU R                  X#S9n[        USS9nU R                  5         U R                  US9U l	        U R                  b  [        U 5      (       a  UOSn[        UUUU R                  U R                  US9u  nnn	n
nn[        U 5      (       a<  U R                  [         R"                  " U	5      R$                  S	   :w  a  ['        S
5      eO	XUpnS=n=pUR$                  S	   nU R)                  5       (       Gd  U R+                  5         U R,                  S:X  a/  [         R.                  " XR0                  4[         R2                  S9nOU(       a  U R,                  R5                  Xy5        OJSR7                  U R,                  R8                  R:                  5      n U R,                  R5                  XyUS9  [A        XpR,                  U R                  [        U 5      5      nS	n[C        U R                  5      U l"        OU RF                  U RH                  R$                  S	   :  a1  ['        SU RF                  U RH                  R$                  S	   4-  5      eU RH                  R$                  S	   n[K        U[        SSSS9nU RM                  U5      nU RO                  5         U RQ                  UU	UUU RD                  UU
UUU5
      nUU RH                  R$                  S	   :w  au  U RH                  SU U l$        U RR                  SU U l)        [U        U S5      (       a<  U RV                  SU U l+        U RX                  SU U l,        U RX                  S   U l-        UU l.        U $ ! [<         a!  nS[?        U5      ;   a  ['        U5      Uee SnAf[&         a!  nS[?        U5      ;   a  ['        U5      Uee SnAff = f)ah  Fit the gradient boosting model.

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

y : array-like of shape (n_samples,)
    Target values (strings or integers in classification, real numbers
    in regression)
    For classification, labels must correspond to classes.

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.

monitor : callable, default=None
    The monitor is called after each iteration with the current
    iteration, a reference to the estimator and the local variables of
    ``_fit_stages`` as keyword arguments ``callable(i, self,
    locals())``. If the callable returns ``True`` the fitting procedure
    is stopped. The monitor can be used for various things such as
    computing held-out estimates, early stopping, model introspect, and
    snapshotting.

Returns
-------
self : object
    Fitted estimator.
)csrcsccooT)accept_sparserE   multi_outputN)r}   ru   )r;   ru   )r   	test_sizestratifyr   zhThe training data after the early stopping split is missing some classes. Try using another random seed.zeror  rE   z9The initial estimator {} does not support sample weights.z+unexpected keyword argument 'sample_weight'zPpass parameters to specific steps of your pipeline using the stepname__parameterzXn_estimators=%d must be larger or equal to estimators_.shape[0]=%d when warm_start==TrueCr*  F)rE   orderr-  ensure_all_finiter   rF   )/r   r  r+   r   r)   r   r#   r  r   r   r   r   r   r   r   
n_classes_rI   uniquer  r  r#  r  r
  r  r   rN   r   r   	__class__r   	TypeErrorr   rY   r"   r  r   r   r!   _raw_predictr  _fit_stagesr   r  r   r  r  n_estimators_)r   rT   r}   ru   monitorsample_weight_is_noner1  X_trainX_valy_trainy_valsample_weight_trainsample_weight_val	n_samplesr   msger   n_stagess                      r@   r   BaseGradientBoosting.fitc  s   P  /
 !. 5,]> $7A@A&  ^^-^@
  ,)$//qTH !!..22!#! T""??bii&8&>&>q&AA
 %   56-1G044E4EMM!$	    zzV#"$(($&A&AB**# )JJNN74##)6$***>*>*G*G#H "

#<O ' & #8ZZ]45H# N +4+<+<=DI   4#3#3#9#9!#<< '*.*;*;T=M=M=S=STU=V)WX 
 "--33A6N "#"'G #//8O  ##II
 t''--a00#//	:D $ 1 1)8 <Dt/00(,(=(=ix(H%#'#3#3IX#> "&"2"22"6%S % "HCPQFR",S/q8!% "258V< #-S/q8!"s$   O 
PO,,P9PPc                 X   UR                   S   nU R                  S:  n[        R                  " U4[        S9n[        S[        U R                  U-  5      5      nU R                  (       a$  [        U R                  S9nUR                  X	5        [        U5      (       a  [        U5      OSn[        U5      (       a  [        U5      OSnU R                  b?  [        R                  " U R                  [        R                  5      nU R!                  USS9n[#        U R$                  [&        [(        45      (       a  S	nOSnU	n[+        XR,                  5       GH  nU(       a3  [/        XU5      nX-)    nXM)    nUS:X  a  UU R%                  UX=)    US
9-  nU R1                  UUUUUUUUUS9	nU(       a  UU R%                  X-   X=   XM   S
9-  U R2                  U'   UU R%                  WX=)    WS
9-  U R4                  U'   US:X  a  WOU R4                  US-
     nUU R4                  U   -
  U R6                  U'   U R4                  S   U l        O!UU R%                  UUUS
9-  U R2                  U'   U R                  S:  a  WR;                  UU 5        U
b  U
" UU [=        5       5      nU(       a    US-   $ U R                  c  GMj  UU R%                  U[?        W5      U5      -  n[        R@                  " UU RB                  -   W:  5      (       a  UUU[E        U5      -  '   GM    US-   $    US-   $ )zIteratively fits the stages.

For each stage it computes the progress (OOB, train score)
and delegates to ``_fit_stage``.
Returns the number of stages fit; might differ from ``n_estimators``
due to early stopping.
r   r   rD   r,   r   NFr   r   r   )r   r   rF   )#r  r   rI   onesboolr   r   r   r   r   r
   r   r	   r   fullinf_staged_raw_predictrx   r   r   r   r   r   r.   r   r   r  r   r  r   localsnextanyr   r   )r   rT   r}   r   ru   r   rA  rC  rE  r   r>  rF  r   r~   n_inbagverbose_reporterr   r   loss_historyy_val_pred_iterfactorr   y_oob_maskedsample_weight_oob_maskedinitial_lossprevious_lossearly_stoppingvalidation_losss                               r@   r<   BaseGradientBoosting._fit_stages,  sQ   ( GGAJ	#%ggyl$7aT^^i789<<.t||D!!$7!)!
1$!)!
1$  ,774#8#8"&&AL #66u%6PO JJ  
 
 FF ~'8'89A1)lS +8+F(6#)DJJ+'6|'D&> -7 - $L #oo . 
O '-

>#2#?"/"< 1; 1 (!!!$
 '-tzz'#2<#@": 0: 0 '  #
 12QD<L<LQQRU<S+84;K;KA;N+N%%a("&"2"22"6 (.

#2"/ 1; 1 (!!!$ ||a ''40"!(D&(!;!$ 1u $$0 #)4::402C, # 66/DHH4|CDD:ILS%6!671uS :R 1urB   c                     [        5       er   )NotImplementedError)r   r   s     r@   _make_estimator$BaseGradientBoosting._make_estimator  s    !##rB   c                 P   U R                  5         U R                  S   R                  USS9nU R                  S:X  a>  [        R
                  " UR                  S   U R                  4[        R                  S9nU$ [        XR                  U R                  [        U 5      5      nU$ )z>Check input and compute raw predictions of the init estimator.r  TrL  r2  r   r3  )r&  r   _validate_X_predictr
  rI   r  r  r   rN   rY   r   r   r   rT   r   s      r@   _raw_predict_init&BaseGradientBoosting._raw_predict_init  s    !T"66qd6K:: hhwwqz4#>#>?rzzO  4::tzz=+>O rB   c                     [        U 5        U R                  U5      n[        U R                  XR                  U5        U$ )z?Return the sum of the trees raw predictions (+ init estimator).)r*   rh  r0   r   r   rg  s      r@   r;  !BaseGradientBoosting._raw_predict  s8    003t'',>,>PrB   c           	   #     #    U(       a  [        X[        SSSS9nU R                  U5      n[        U R                  R
                  S   5       H7  n[        U R                  XAU R                  U5        UR                  5       v   M9     g7f)a  Compute raw predictions of ``X`` for each iteration.

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

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

check_input : bool, default=True
    If False, the input arrays X will not be checked.

Returns
-------
raw_predictions : generator of ndarray of shape (n_samples, k)
    The raw predictions of the input samples. The order of the
    classes corresponds to that in the attribute :term:`classes_`.
    Regression and binary classification are special cases with
    ``k == 1``, otherwise ``k==n_classes``.
r4  r*  FrE   r5  r-  resetr   N)	r+   r   rh  r   r   r  r/   r   rq   )r   rT   r   r   r   s        r@   rQ  (BaseGradientBoosting._staged_raw_predict  sz     0 uCuEA 003t''--a01A$**A$2D2DoV!&&(( 2s   BB
c                    U R                  5         U R                   VVs/ s H+  nU  H!  nUR                  R                  S:  d  M  UPM#     M-     nnnU(       d-  [        R
                  " U R                  [        R                  S9$ U Vs/ s H  nUR                  R                  SS9PM     nn[        R                  " US[        R                  S9nU[        R                  " U5      -  $ s  snnf s  snf )a  The impurity-based feature importances.

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

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

Returns
-------
feature_importances_ : ndarray of shape (n_features,)
    The 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,   r3  F)	normalizer   )r^   rE   )r&  r   r   
node_countrI   r  r  rN   compute_feature_importancesr	  sum)r   stager|   relevant_treesrelevant_feature_importancesavg_feature_importancess         r@   feature_importances_)BaseGradientBoosting.feature_importances_  s    ( 	! ))
)zz$$q(  ) 	 
 88$"5"5RZZHH '(
& JJ22U2C& 	% (
 #%''(q

#
 '0G)HHH#
(
s   $C/
C/#C5c                 @   U R                   b(  [        R                  " SU R                   -  [        5        [        R
                  " U[        SS9nU R                  R                  u  p4[        R                  " XAR                  S   4[        R                  SS9n[        R
                  " U[        R                  SS9n[        U5       HC  n[        U5       H1  nU R                  Xg4   R                  nUR                  XXW   5        M3     ME     XPR                  -  nU$ )a$  Fast partial dependence computation.

Parameters
----------
grid : ndarray of shape (n_samples, n_target_features), dtype=np.float32
    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_trees_per_iteration_, n_samples)
    The value of the partial dependence function on each grid point.
zxUsing recursion method with a non-constant init predictor will lead to incorrect partial dependence values. Got init=%s.r4  )rE   r5  r   )r   r:   r;   UserWarningrI   asarrayr   r   r  r  rN   intpr   r   compute_partial_dependencer   )	r   gridtarget_featuresr   n_trees_per_stageaveraged_predictionsru  rg   r|   s	            r@   %_compute_partial_dependence_recursion:BaseGradientBoosting._compute_partial_dependence_recursion  s    $ 99 MM!%+ 	 zz$e37*.*:*:*@*@'!xx

1.bjj 
 **_BGG3O<(E,-''177//+?+B . ) 	 2 22##rB   c                 p   U R                  5         U R                  S   R                  USS9nU R                  R                  u  p#[        R
                  " UR                  S   X#45      n[        U5       H<  n[        U5       H*  nU R                  XV4   nUR                  USS9USS2XV4'   M,     M>     U$ )ae  Apply trees in the ensemble to X, return leaf indices.

.. versionadded:: 0.17

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 to a sparse ``csr_matrix``.

Returns
-------
X_leaves : array-like of shape (n_samples, n_estimators, n_classes)
    For each datapoint x in X and for each tree in the ensemble,
    return the index of the leaf x ends up in each estimator.
    In the case of binary classification n_classes is 1.
r  TrL  r   FN)r&  r   rf  r  rI   r  r   rw   )r   rT   r   rn   leavesr   r   rU   s           r@   rw   BaseGradientBoosting.apply=  s    ( 	!T"66qd6K #'"2"2"8"81771:|?@|$A9% ,,QT2	"+//!/"Gq!w & %
 rB   c                 F   > [         TU ]  5       nSUR                  l        U$ )NT)super__sklearn_tags__
input_tagssparse)r   tagsr9  s     r@   r  %BaseGradientBoosting.__sklearn_tags__`  s!    w')!%rB   )r   r  r   r   r   r   r   r
  r   rV   r   r   r  r   r   r   r   r   r   r=  r   r   r  r  r   r   r   r   r   r   r   NN)r   N)T)'r   r   r   r   r   r   r   r%   r   r   r&   dict__annotations__popr   r   r   r   r   r  r  r  r  r#  r&  r   r   r<  rc  rh  r;  rQ  propertyry  r  rw   r  r   __classcell__r9  s   @r@   r   r   a  s   4$

6
6$"4d6BC!(AtFCD ./!BCDtS#g>?; k (sC	 JK%h4GNsD89$D  z*/$ /- -^ 6 6 7 7 Tl**%0"):9 &+C	C^ BH$)B &I &IP($T!F rB   r   )	metaclassc                      ^  \ rS rSr% Sr0 \R                  E\" SS15      /\" S15      S\" SS/5      /S	.Er\	\
S
'   S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rS rS rS rS rS rS rS rS rS  rS!rU =r$ )"GradientBoostingClassifierif  a55  Gradient Boosting for classification.

This algorithm builds an additive model in a forward stage-wise fashion; it
allows for the optimization of arbitrary differentiable loss functions. In
each stage ``n_classes_`` regression trees are fit on the negative gradient
of the loss function, e.g. binary or multiclass log loss. Binary
classification is a special case where only a single regression tree is
induced.

:class:`~sklearn.ensemble.HistGradientBoostingClassifier` is a much faster variant
of this algorithm for intermediate and large datasets (`n_samples >= 10_000`) and
supports monotonic constraints.

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

Parameters
----------
loss : {'log_loss', 'exponential'}, default='log_loss'
    The loss function to be optimized. 'log_loss' refers to binomial and
    multinomial deviance, the same as used in logistic regression.
    It is a good choice for classification with probabilistic outputs.
    For loss 'exponential', gradient boosting recovers the AdaBoost algorithm.

learning_rate : float, default=0.1
    Learning rate shrinks the contribution of each tree by `learning_rate`.
    There is a trade-off between learning_rate and n_estimators.
    Values must be in the range `[0.0, inf)`.

    For an example of the effects of this parameter and its interaction with
    ``subsample``, see
    :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_regularization.py`.

n_estimators : int, default=100
    The number of boosting stages to perform. Gradient boosting
    is fairly robust to over-fitting so a large number usually
    results in better performance.
    Values must be in the range `[1, inf)`.

subsample : float, default=1.0
    The fraction of samples to be used for fitting the individual base
    learners. If smaller than 1.0 this results in Stochastic Gradient
    Boosting. `subsample` interacts with the parameter `n_estimators`.
    Choosing `subsample < 1.0` leads to a reduction of variance
    and an increase in bias.
    Values must be in the range `(0.0, 1.0]`.

criterion : {'friedman_mse', 'squared_error'}, default='friedman_mse'
    The function to measure the quality of a split. Supported criteria are
    'friedman_mse' for the mean squared error with improvement score by
    Friedman, 'squared_error' for mean squared error. The default value of
    'friedman_mse' is generally the best as it can provide a better
    approximation in some cases.

    .. versionadded:: 0.18

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

    - If int, values must be in the range `[2, inf)`.
    - If float, values must be in the range `(0.0, 1.0]` and `min_samples_split`
      will be `ceil(min_samples_split * n_samples)`.

    .. 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, values must be in the range `[1, inf)`.
    - If float, values must be in the range `(0.0, 1.0)` and `min_samples_leaf`
      will be `ceil(min_samples_leaf * n_samples)`.

    .. 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.
    Values must be in the range `[0.0, 0.5]`.

max_depth : int or None, default=3
    Maximum depth of the individual regression estimators. The maximum
    depth limits the number of nodes in the tree. Tune this parameter
    for best performance; the best value depends on the interaction
    of the input variables. If None, then nodes are expanded until
    all leaves are pure or until all leaves contain less than
    min_samples_split samples.
    If int, values must be in the range `[1, inf)`.

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.
    Values must be in the range `[0.0, inf)`.

    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

init : estimator or 'zero', default=None
    An estimator object that is used to compute the initial predictions.
    ``init`` has to provide :term:`fit` and :term:`predict_proba`. If
    'zero', the initial raw predictions are set to zero. By default, a
    ``DummyEstimator`` predicting the classes priors is used.

random_state : int, RandomState instance or None, default=None
    Controls the random seed given to each Tree estimator at each
    boosting iteration.
    In addition, it controls the random permutation of the features at
    each split (see Notes for more details).
    It also controls the random splitting of the training data to obtain a
    validation set if `n_iter_no_change` is not None.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

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

    - If int, values must be in the range `[1, inf)`.
    - If float, values must be in the range `(0.0, 1.0]` and the features
      considered at each split will be `max(1, int(max_features * n_features_in_))`.
    - If 'sqrt', then `max_features=sqrt(n_features)`.
    - If 'log2', then `max_features=log2(n_features)`.
    - If None, then `max_features=n_features`.

    Choosing `max_features < n_features` leads to a reduction of variance
    and an increase in bias.

    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.

verbose : int, default=0
    Enable verbose output. If 1 then it prints progress and performance
    once in a while (the more trees the lower the frequency). If greater
    than 1 then it prints progress and performance for every tree.
    Values must be in the range `[0, inf)`.

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.
    Values must be in the range `[2, inf)`.
    If `None`, then unlimited number of leaf nodes.

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 erase the
    previous solution. See :term:`the Glossary <warm_start>`.

validation_fraction : float, default=0.1
    The proportion of training data to set aside as validation set for
    early stopping. Values must be in the range `(0.0, 1.0)`.
    Only used if ``n_iter_no_change`` is set to an integer.

    .. versionadded:: 0.20

n_iter_no_change : int, default=None
    ``n_iter_no_change`` is used to decide if early stopping will be used
    to terminate training when validation score is not improving. By
    default it is set to None to disable early stopping. If set to a
    number, it will set aside ``validation_fraction`` size of the training
    data as validation and terminate training when validation score is not
    improving in all of the previous ``n_iter_no_change`` numbers of
    iterations. The split is stratified.
    Values must be in the range `[1, inf)`.
    See
    :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_early_stopping.py`.

    .. versionadded:: 0.20

tol : float, default=1e-4
    Tolerance for the early stopping. When the loss is not improving
    by at least tol for ``n_iter_no_change`` iterations (if set to a
    number), the training stops.
    Values must be in the range `[0.0, inf)`.

    .. versionadded:: 0.20

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.
    Values must be in the range `[0.0, inf)`.
    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

Attributes
----------
n_estimators_ : int
    The number of estimators as selected by early stopping (if
    ``n_iter_no_change`` is specified). Otherwise it is set to
    ``n_estimators``.

    .. versionadded:: 0.20

n_trees_per_iteration_ : int
    The number of trees that are built at each iteration. For binary classifiers,
    this is always 1.

    .. versionadded:: 1.4.0

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_improvement_ : ndarray of shape (n_estimators,)
    The improvement in loss on the out-of-bag samples
    relative to the previous iteration.
    ``oob_improvement_[0]`` is the improvement in
    loss of the first stage over the ``init`` estimator.
    Only available if ``subsample < 1.0``.

oob_scores_ : ndarray of shape (n_estimators,)
    The full history of the loss values on the out-of-bag
    samples. Only available if `subsample < 1.0`.

    .. versionadded:: 1.3

oob_score_ : float
    The last value of the loss on the out-of-bag samples. It is
    the same as `oob_scores_[-1]`. Only available if `subsample < 1.0`.

    .. versionadded:: 1.3

train_score_ : ndarray of shape (n_estimators,)
    The i-th score ``train_score_[i]`` is the loss of the
    model at iteration ``i`` on the in-bag sample.
    If ``subsample == 1`` this is the loss on the training data.

init_ : estimator
    The estimator that provides the initial predictions. Set via the ``init``
    argument.

estimators_ : ndarray of DecisionTreeRegressor of             shape (n_estimators, ``n_trees_per_iteration_``)
    The collection of fitted sub-estimators. ``n_trees_per_iteration_`` is 1 for
    binary classification, otherwise ``n_classes``.

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

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_classes_ : int
    The number of classes.

max_features_ : int
    The inferred value of max_features.

See Also
--------
HistGradientBoostingClassifier : Histogram-based Gradient Boosting
    Classification Tree.
sklearn.tree.DecisionTreeClassifier : A decision tree classifier.
RandomForestClassifier : 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.
AdaBoostClassifier : A meta-estimator that begins by fitting a classifier
    on the original dataset and then fits additional copies of the
    classifier on the same dataset where the weights of incorrectly
    classified instances are adjusted such that subsequent classifiers
    focus more on difficult cases.

Notes
-----
The features are always randomly permuted at each split. Therefore,
the best found split may vary, even with the same training data and
``max_features=n_features``, 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
----------
J. Friedman, Greedy Function Approximation: A Gradient Boosting
Machine, The Annals of Statistics, Vol. 29, No. 5, 2001.

J. Friedman, Stochastic Gradient Boosting, 1999

T. Hastie, R. Tibshirani and J. Friedman.
Elements of Statistical Learning Ed. 2, Springer, 2009.

Examples
--------
The following example shows how to fit a gradient boosting classifier with
100 decision stumps as weak learners.

>>> from sklearn.datasets import make_hastie_10_2
>>> from sklearn.ensemble import GradientBoostingClassifier

>>> X, y = make_hastie_10_2(random_state=0)
>>> X_train, X_test = X[:2000], X[2000:]
>>> y_train, y_test = y[:2000], y[2000:]

>>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0,
...     max_depth=1, random_state=0).fit(X_train, y_train)
>>> clf.score(X_test, y_test)
0.913
log_lossexponentialr2  Nr   rG   )rV   r   r   r   r   r   r   r   r,   r5      r   Fr   )rV   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                F   > [         TU ]  UUUUUUUU	UUUUUUU
UUUUUS9  g )N)rV   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   )r   rV   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r9  s                        r@   r   #GradientBoostingClassifier.__init__  sS    0 	'%/-%=%%)"7! 3-) 	 	
rB   c                    [        U5        [        5       nUR                  U5      nUR                  U l        U R                  R                  S   nUS::  a  SOUU l        UR                  [        SS9nXPl        Uc  UnO*[        R                  " [        R                  " XB5      5      nUS:  a  [        SU-  5      eU$ )Nr   r   r,   Frq   zuy contains %d class after sample_weight trimmed classes with zero weights, while a minimum of 2 classes are required.)r'   r   fit_transformclasses_r  r   rP   r7   r7  rI   count_nonzerobincountr  )r   r}   ru   label_encoderencoded_y_intrn   	encoded_yn_trim_classess           r@   r   $GradientBoostingClassifier._encode_y  s     	%Q'$%33A6%..MM''*	 ,5>ay#!((U(;	 $ &N--bkk-.WXNA57EF 
 rB   c                    U R                   S:X  a,  U R                  S:X  a	  [        US9$ [        XR                  S9$ U R                   S:X  a?  U R                  S:  a&  [	        SU R                    SU R                   S35      e[        US9$ g )	Nr  r   r/  )ru   rn   r  zloss='zK' is only suitable for a binary classification problem, you have n_classes=z%. Please use loss='log_loss' instead.)rV   r7  r   r   r  r   r   s     r@   r   $GradientBoostingClassifier._get_loss  s    99
"!#'mDD*"/??  YY-'" TYYK (337??2C D::  ']CC (rB   c           	          [        X[        SSSS9nU R                  U5      nUR                  S   S:X  a  UR	                  5       $ U$ )a  Compute the decision function of ``X``.

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

Returns
-------
score : ndarray of shape (n_samples, n_classes) or (n_samples,)
    The decision function of the input samples, which corresponds to
    the raw values predicted from the trees of the ensemble . The
    order of the classes corresponds to that in the attribute
    :term:`classes_`. Regression and binary classification produce an
    array of shape (n_samples,).
r4  r*  Frm  r,   )r+   r   r;  r  ravelrg  s      r@   decision_function,GradientBoostingClassifier.decision_function  sS    & 55
 ++A.  #q("((**rB   c              #   B   #    U R                  U5       Sh  vN   g N7f)a  Compute decision function of ``X`` for each iteration.

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

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

Yields
------
score : generator of ndarray of shape (n_samples, k)
    The decision function of the input samples, which corresponds to
    the raw values predicted from the trees of the ensemble . The
    classes corresponds to that in the attribute :term:`classes_`.
    Regression and binary classification are special cases with
    ``k == 1``, otherwise ``k==n_classes``.
N)rQ  r   rT   s     r@   staged_decision_function3GradientBoostingClassifier.staged_decision_function4  s     , ++A...s   c                     U R                  U5      nUR                  S:X  a  US:  R                  [        5      nO[        R
                  " USS9nU R                  U   $ )aQ  Predict class for X.

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

Returns
-------
y : ndarray of shape (n_samples,)
    The predicted values.
r,   r   r]   )r  rQ   rP   r   rI   argmaxr  r   rT   r   encoded_classess       r@   rO   "GradientBoostingClassifier.predictL  sV     0031$.!3;;C@O iia@O}}_--rB   c              #   t  #    U R                   S:X  a[  U R                  U5       HE  nUR                  5       S:  R                  [        5      nU R
                  R                  USS9v   MG     gU R                  U5       H4  n[        R                  " USS9nU R
                  R                  USS9v   M6     g7f)a  Predict class at each stage for X.

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

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

Yields
------
y : generator of ndarray of shape (n_samples,)
    The predicted value of the input samples.
r   r   r]   r,   N)	r7  rQ  r   rP   r   r  ra   rI   r  r  s       r@   staged_predict)GradientBoostingClassifier.staged_predictb  s     $ ??a#'#;#;A#>#2#:#:#<#A"I"I#"Nmm((q(AA $? $(#;#;A#>"$))O!"Dmm((q(AA $?s   B6B8c                 Z    U R                  U5      nU R                  R                  U5      $ )a'  Predict class probabilities for X.

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

Returns
-------
p : ndarray of shape (n_samples, n_classes)
    The class probabilities of the input samples. The order of the
    classes corresponds to that in the attribute :term:`classes_`.

Raises
------
AttributeError
    If the ``loss`` does not support probabilities.
)r  r   rG   rg  s      r@   rG   (GradientBoostingClassifier.predict_proba}  s)    * 003zz''88rB   c                 P    U R                  U5      n[        R                  " U5      $ )a/  Predict class log-probabilities for X.

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

Returns
-------
p : ndarray of shape (n_samples, n_classes)
    The class log-probabilities of the input samples. The order of the
    classes corresponds to that in the attribute :term:`classes_`.

Raises
------
AttributeError
    If the ``loss`` does not support probabilities.
)rG   rI   log)r   rT   probas      r@   predict_log_proba,GradientBoostingClassifier.predict_log_proba  s"    * ""1%vve}rB   c              #      #     U R                  U5       H   nU R                  R                  U5      v   M"     g! [         a    e [         a  n[	        SU R
                  -  5      UeSnAff = f7f)a  Predict class probabilities at each stage for X.

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

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

Yields
------
y : generator of ndarray of shape (n_samples,)
    The predicted value of the input samples.
z&loss=%r does not support predict_probaN)rQ  r   rG   r   AttributeErrorrV   )r   rT   r   rH  s       r@   staged_predict_proba/GradientBoostingClassifier.staged_predict_proba  sj     $	#'#;#;A#>jj..?? $? 	 	 8499D	s%   A/5: A/A,A''A,,A/)r  r7  r   )r   r   r   r   r   r   r   r&   r$   r  r  r   r   r   r  r  rO   r  rG   r  r  r   r  r  s   @r@   r  r  f  s    KZ
$

5
5$Z789VH%tZ8P-QR$D   !$!--
 -
^<D$6/0.,B6900 rB   r  c                      ^  \ rS rSr% Sr0 \R                  E\" 1 Sk5      /\" S15      S\" SS/5      /\	" \
SS	S
S9/S.Er\\S'   SS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rS!S jrS rS rS rU 4S jrS rU =r$ )"GradientBoostingRegressori  a3  Gradient Boosting for regression.

This estimator builds an additive model in a forward stage-wise fashion; it
allows for the optimization of arbitrary differentiable loss functions. In
each stage a regression tree is fit on the negative gradient of the given
loss function.

:class:`~sklearn.ensemble.HistGradientBoostingRegressor` is a much faster variant
of this algorithm for intermediate and large datasets (`n_samples >= 10_000`) and
supports monotonic constraints.

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

Parameters
----------
loss : {'squared_error', 'absolute_error', 'huber', 'quantile'},             default='squared_error'
    Loss function to be optimized. 'squared_error' refers to the squared
    error for regression. 'absolute_error' refers to the absolute error of
    regression and is a robust loss function. 'huber' is a
    combination of the two. 'quantile' allows quantile regression (use
    `alpha` to specify the quantile).
    See
    :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_quantile.py`
    for an example that demonstrates quantile regression for creating
    prediction intervals with `loss='quantile'`.

learning_rate : float, default=0.1
    Learning rate shrinks the contribution of each tree by `learning_rate`.
    There is a trade-off between learning_rate and n_estimators.
    Values must be in the range `[0.0, inf)`.

n_estimators : int, default=100
    The number of boosting stages to perform. Gradient boosting
    is fairly robust to over-fitting so a large number usually
    results in better performance.
    Values must be in the range `[1, inf)`.

subsample : float, default=1.0
    The fraction of samples to be used for fitting the individual base
    learners. If smaller than 1.0 this results in Stochastic Gradient
    Boosting. `subsample` interacts with the parameter `n_estimators`.
    Choosing `subsample < 1.0` leads to a reduction of variance
    and an increase in bias.
    Values must be in the range `(0.0, 1.0]`.

criterion : {'friedman_mse', 'squared_error'}, default='friedman_mse'
    The function to measure the quality of a split. Supported criteria are
    "friedman_mse" for the mean squared error with improvement score by
    Friedman, "squared_error" for mean squared error. The default value of
    "friedman_mse" is generally the best as it can provide a better
    approximation in some cases.

    .. versionadded:: 0.18

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

    - If int, values must be in the range `[2, inf)`.
    - If float, values must be in the range `(0.0, 1.0]` and `min_samples_split`
      will be `ceil(min_samples_split * n_samples)`.

    .. 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, values must be in the range `[1, inf)`.
    - If float, values must be in the range `(0.0, 1.0)` and `min_samples_leaf`
      will be `ceil(min_samples_leaf * n_samples)`.

    .. 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.
    Values must be in the range `[0.0, 0.5]`.

max_depth : int or None, default=3
    Maximum depth of the individual regression estimators. The maximum
    depth limits the number of nodes in the tree. Tune this parameter
    for best performance; the best value depends on the interaction
    of the input variables. If None, then nodes are expanded until
    all leaves are pure or until all leaves contain less than
    min_samples_split samples.
    If int, values must be in the range `[1, inf)`.

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.
    Values must be in the range `[0.0, inf)`.

    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

init : estimator or 'zero', default=None
    An estimator object that is used to compute the initial predictions.
    ``init`` has to provide :term:`fit` and :term:`predict`. If 'zero', the
    initial raw predictions are set to zero. By default a
    ``DummyEstimator`` is used, predicting either the average target value
    (for loss='squared_error'), or a quantile for the other losses.

random_state : int, RandomState instance or None, default=None
    Controls the random seed given to each Tree estimator at each
    boosting iteration.
    In addition, it controls the random permutation of the features at
    each split (see Notes for more details).
    It also controls the random splitting of the training data to obtain a
    validation set if `n_iter_no_change` is not None.
    Pass an int for reproducible output across multiple function calls.
    See :term:`Glossary <random_state>`.

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

    - If int, values must be in the range `[1, inf)`.
    - If float, values must be in the range `(0.0, 1.0]` and the features
      considered at each split will be `max(1, int(max_features * n_features_in_))`.
    - If "sqrt", then `max_features=sqrt(n_features)`.
    - If "log2", then `max_features=log2(n_features)`.
    - If None, then `max_features=n_features`.

    Choosing `max_features < n_features` leads to a reduction of variance
    and an increase in bias.

    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.

alpha : float, default=0.9
    The alpha-quantile of the huber loss function and the quantile
    loss function. Only if ``loss='huber'`` or ``loss='quantile'``.
    Values must be in the range `(0.0, 1.0)`.

verbose : int, default=0
    Enable verbose output. If 1 then it prints progress and performance
    once in a while (the more trees the lower the frequency). If greater
    than 1 then it prints progress and performance for every tree.
    Values must be in the range `[0, inf)`.

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.
    Values must be in the range `[2, inf)`.
    If None, then unlimited number of leaf nodes.

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 erase the
    previous solution. See :term:`the Glossary <warm_start>`.

validation_fraction : float, default=0.1
    The proportion of training data to set aside as validation set for
    early stopping. Values must be in the range `(0.0, 1.0)`.
    Only used if ``n_iter_no_change`` is set to an integer.

    .. versionadded:: 0.20

n_iter_no_change : int, default=None
    ``n_iter_no_change`` is used to decide if early stopping will be used
    to terminate training when validation score is not improving. By
    default it is set to None to disable early stopping. If set to a
    number, it will set aside ``validation_fraction`` size of the training
    data as validation and terminate training when validation score is not
    improving in all of the previous ``n_iter_no_change`` numbers of
    iterations.
    Values must be in the range `[1, inf)`.
    See
    :ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_early_stopping.py`.

    .. versionadded:: 0.20

tol : float, default=1e-4
    Tolerance for the early stopping. When the loss is not improving
    by at least tol for ``n_iter_no_change`` iterations (if set to a
    number), the training stops.
    Values must be in the range `[0.0, inf)`.

    .. versionadded:: 0.20

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.
    Values must be in the range `[0.0, inf)`.
    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

Attributes
----------
n_estimators_ : int
    The number of estimators as selected by early stopping (if
    ``n_iter_no_change`` is specified). Otherwise it is set to
    ``n_estimators``.

n_trees_per_iteration_ : int
    The number of trees that are built at each iteration. For regressors, this is
    always 1.

    .. versionadded:: 1.4.0

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_improvement_ : ndarray of shape (n_estimators,)
    The improvement in loss on the out-of-bag samples
    relative to the previous iteration.
    ``oob_improvement_[0]`` is the improvement in
    loss of the first stage over the ``init`` estimator.
    Only available if ``subsample < 1.0``.

oob_scores_ : ndarray of shape (n_estimators,)
    The full history of the loss values on the out-of-bag
    samples. Only available if `subsample < 1.0`.

    .. versionadded:: 1.3

oob_score_ : float
    The last value of the loss on the out-of-bag samples. It is
    the same as `oob_scores_[-1]`. Only available if `subsample < 1.0`.

    .. versionadded:: 1.3

train_score_ : ndarray of shape (n_estimators,)
    The i-th score ``train_score_[i]`` is the loss of the
    model at iteration ``i`` on the in-bag sample.
    If ``subsample == 1`` this is the loss on the training data.

init_ : estimator
    The estimator that provides the initial predictions. Set via the ``init``
    argument.

estimators_ : ndarray of DecisionTreeRegressor of shape (n_estimators, 1)
    The collection of fitted sub-estimators.

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

max_features_ : int
    The inferred value of max_features.

See Also
--------
HistGradientBoostingRegressor : Histogram-based Gradient Boosting
    Classification Tree.
sklearn.tree.DecisionTreeRegressor : A decision tree regressor.
sklearn.ensemble.RandomForestRegressor : A random forest regressor.

Notes
-----
The features are always randomly permuted at each split. Therefore,
the best found split may vary, even with the same training data and
``max_features=n_features``, 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
----------
J. Friedman, Greedy Function Approximation: A Gradient Boosting
Machine, The Annals of Statistics, Vol. 29, No. 5, 2001.

J. Friedman, Stochastic Gradient Boosting, 1999

T. Hastie, R. Tibshirani and J. Friedman.
Elements of Statistical Learning Ed. 2, Springer, 2009.

Examples
--------
>>> from sklearn.datasets import make_regression
>>> from sklearn.ensemble import GradientBoostingRegressor
>>> from sklearn.model_selection import train_test_split
>>> X, y = make_regression(random_state=0)
>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, random_state=0)
>>> reg = GradientBoostingRegressor(random_state=0)
>>> reg.fit(X_train, y_train)
GradientBoostingRegressor(random_state=0)
>>> reg.predict(X_test[1:2])
array([-61.1])
>>> reg.score(X_test, y_test)
0.4...

For a detailed example of utilizing
:class:`~sklearn.ensemble.GradientBoostingRegressor`
to fit an ensemble of weak predictive models, please refer to
:ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_regression.py`.
>   r3   r2   r   absolute_errorr2  Nr   rO   r5   r   r   r   )rV   r   r   r   r   r   r   r   r   r,   r  r   r   Fr   )rV   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c                H   > [         TU ]  UUUUUUUU	UUUU
UUUUUUUUUS9  g )N)rV   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  )r   rV   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r9  s                         r@   r   "GradientBoostingRegressor.__init__  sV    2 	'%/-%=%"7%)! 3-+ 	 	
rB   c                 <    SU l         UR                  [        SS9nU$ )Nr,   Fr  )r   rP   r   r   s      r@   r   #GradientBoostingRegressor._encode_yI  s!    &'#HHV%H(rB   c                     U R                   S;   a!  [        U R                      " XR                  S9$ [        U R                      " US9$ )Nr1   )ru   r2   r/  )rV   r   r   r   s     r@   r   #GradientBoostingRegressor._get_lossO  s;    99--499%MJJWW499%MBBrB   c           	      b    [        X[        SSSS9nU R                  U5      R                  5       $ )a]  Predict regression target for X.

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

Returns
-------
y : ndarray of shape (n_samples,)
    The predicted values.
r4  r*  Frm  )r+   r   r;  r  r  s     r@   rO   !GradientBoostingRegressor.predictU  s5     55
   #))++rB   c              #   `   #    U R                  U5       H  nUR                  5       v   M     g7f)a  Predict regression target at each stage for X.

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

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

Yields
------
y : generator of ndarray of shape (n_samples,)
    The predicted value of the input samples.
N)rQ  r  rg  s      r@   r  (GradientBoostingRegressor.staged_predictj  s+     $  $77:O!''))  ;s   ,.c                    > [         TU ]  U5      nUR                  UR                  S   U R                  R                  S   5      nU$ )a!  Apply trees in the ensemble to X, return leaf indices.

.. versionadded:: 0.17

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 to a sparse ``csr_matrix``.

Returns
-------
X_leaves : array-like of shape (n_samples, n_estimators)
    For each datapoint x in X and for each tree in the ensemble,
    return the index of the leaf x ends up in each estimator.
r   )r  rw   rS   r  r   )r   rT   r  r9  s      r@   rw   GradientBoostingRegressor.apply  sA    & q!
D,<,<,B,B1,EFrB   )r   r  )r   r   r   r   r   r   r   r&   r$   r%   r   r  r  r   r   r   rO   r  rw   r   r  r  s   @r@   r  r    s    DL
$

5
5$TUVVH%tZ	8J-KL4c)<=	$D   !$!//
 /
bC,*** rB   r  )r   r   r   )Mr   r8   r:   abcr   r   numbersr   r   r   numpyrI   scipy.sparser   r	   r
   
_loss.lossr   r   r   r   r   r   r   r   baser   r   r   r   dummyr   r   
exceptionsr   model_selectionr   preprocessingr   r|   r   
tree._treer   r   r    utilsr!   r"   r#   utils._param_validationr$   r%   r&   utils.multiclassr'   utils.statsr(   utils.validationr)   r*   r+   _baser-   _gradient_boostingr.   r/   r0   rq   r   rA   rY   r   r   r   r   r  r  r   rB   r@   <module>r     s   *   ' "   9 9	 	 	 P O 3 ' . ( ( 1 1 A A F F ; . S S  R R
,,. *'+f GT$L' L'^B<7 BJa	2F a	HJ0D JrB   