
    >[gU                    2   d Z ddlZddlZddlmZmZ ddlmZmZ ddl	m	Z	 ddl
ZddlmZmZmZ ddlmZmZmZmZmZmZmZmZ dd	lmZmZmZmZ dd
lmZm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z;m<Z< ddl=m>Z> ddl?m@Z@mAZAmBZB  ej                         Z ej                  eed       d ZEd ZF	 	 d&dZGd'dZH G d d      ZI G d d e>e!      ZJ G d" d#eeJ      ZK G d$ d%eeJ      ZLy)(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                     t        |      dk  ryt        |       t        |      z  }t        |       t        |      z  }t        j                  |      rt	        j
                  dt               |S )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      O/var/www/html/bid-api/venv/lib/python3.12/site-packages/sklearn/ensemble/_gb.py_safe_dividerA   A   s`     ;&  y!E+$66 y!E+$66::fMM@.Q    c                    |r~|j                  |       }|j                  s	|dddf   }t        j                  t        j                        j
                  }t        j                  ||d|z
  t        j                        }n.|j                  |       j                  t        j                        }|j                  dk(  r+|j                  j                  |      j                  dd      S |j                  j                  |      S )a  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"&&ggk3CrzzJ''*11"**=1yy~~k*222q99yy~~k**rB   c
                 |    |j                  |      }
t         t              s|
j                         }d|| <   t         t              rfd}n3t         t
              r fd}nt         t              rfd}n fd}t        j                  |j                  t        k(        d   D ]W  }t        j                  ||k(        d   }|j                  |d      }|dn||    ||||||	      }||j                  |ddf<   Y |dd|	fxx   ||j                  ddddf   j                  |
d      z  z  cc<   y)	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                     |j                  |d      }| |z
  }t        j                  |	      }t        j                  |d|z
  z  	      }t        ||      S Nr   axisweightsr,   )takerI   averagerA   )
y_indicesneg_gradientraw_predictionkneg_gprobr=   r>   sws
            r@   compute_updatez0_update_terminal_regions.<locals>.compute_update   sY     %))'):EzJJub9	 jjT):BG#I{;;rB   c                     |j                  |d      }| |z
  }
j                  }t        j                  |      }||dz
  |z  z  }t        j                  |d|z
  z        }	t	        ||	      S r\   )ra   	n_classesrI   rb   rA   )rc   rd   re   rf   rg   rh   ri   Kr=   r>   rV   rj   s             r@   rk   z0_update_terminal_regions.<locals>.compute_update   st    $))'):EzNN JJub9	a!eq[(	 jjT):BG#I{;;rB   c                     |j                  |d      }t        j                  |	      }|j                         }|| dk(  xx   dz  cc<   t        j                  |	      }t	        ||      S )Nr   r]   r_   rF   )ra   rI   rb   copyrA   )
rc   rd   re   rf   rg   rh   r=   hessianr>   rj   s
            r@   rk   z0_update_terminal_regions.<locals>.compute_update   sf    $))'):JJub9	  **,a B&  jj"=#I{;;rB   c                 :    j                  | |||f   z
        S )N)y_truesample_weight)fit_intercept_only)rc   rd   re   rf   rg   rV   rj   s        r@   rk   z0_update_terminal_regions.<locals>.compute_update   s/    ..wz ::"$ /  rB   r   r]   N)apply
isinstancer   rp   r   r   r   rI   nonzerochildren_leftr    ra   value)rV   treerT   yre   rf   rt   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<" o.
< JJt11Y>?BDjj!8D!@AG a(B&.M'4JB#B~qQF &,DJJtQz" C 1a4MDJJq!Qw,?,D,Dq -E -  rB   c                     t        j                  ||j                         z
        }t        ||d| j                  z        }t        |      | j                  _        y)z:Calculate and set self.closs.delta based on self.quantile.d   N)rI   r6   squeezer(   r2   r7   clossdelta)rV   rs   rf   rt   abserrr   s         r@   set_huber_deltar   
  sE    VVF^33556F dmm8KLEU|DJJrB   c                   $    e Zd ZdZd ZddZd Zy)VerboseReportera  Reports 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                     || _         y Nverbose)selfr   s     r@   __init__zVerboseReporter.__init__  s	    rB   c                 r   ddg}ddg}|j                   dk  r"|j                  d       |j                  d       |j                  d       |j                  d	       t        d
dt        |      dz
  z  z   t	        |      z         dj                  |      | _        d| _        t               | _	        || _
        y)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@   initzVerboseReporter.init   s      .$&<===1  /23-.23 	wC$6$:;;u]?SST88K0&,rB   c                 F   |j                   dk  }|| j                  z
  }|dz   | j                  z  dk(  r|r|j                  |   nd}|j                  |dz   z
  t               | j                  z
  z  t        |dz         z  }|dkD  rdj                  |dz        }ndj                  |      }t        | j                  j                  |dz   |j                  |   ||             | j                  dk(  r/|dz   | j                  dz  z  dkD  r| xj                  dz  c_        y	y	y	y	)
zUpdate 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   zVerboseReporter.update>  s7    "###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   N)r   )__name__
__module____qualname____doc__r   r   r    rB   r@   r   r     s    -< 'rB   r   c                      e Zd ZU dZi ej
                   eeddd      g eeddd      g e	ddh      g eedd	d
      gdgdg eedd	d      g eeddd      dg eeddd      gd	Ze
ed<   ej                  d       ej                  d       eddddddddd       Zed,d       Zed        Z	 	 d,dZd Zd Zd Zd Zd  Zd! Z ed"      d,d#       Z	 	 d-d$Zd.d%Zd& Zd' Zd.d(Zed)        Z d* Z!d+ Z"y)/BaseGradientBoostingz*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                *   || _         || _        || _        || _        || _        || _        || _        || _        || _        || _	        |	| _
        || _        |
| _        || _        || _        || _        || _        || _        || _        || _        || _        y 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   zBaseGradientBoosting.__init__s  s    4 )*	"!2 0(@%"("%:""	(
,$#6  0rB   c                      y)z'Called by fit to validate and encode y.Nr   r   r|   rt   s      r@   	_encode_yzBaseGradientBoosting._encode_y      rB   c                      y)z(Get loss object from sklearn._loss.loss.Nr   r   rt   s     r@   	_get_losszBaseGradientBoosting._get_loss  r   rB   c
                    |}
t        | j                  t              rt        | j                  |||       | j                  j	                  ||d       }|j
                  dk(  r|j                  d      }n|}t        | j                        D ]U  }| j                  j                  r(t        j                  |
|k(  t        j                        }t        | j                  d| j                  | j                   | j"                  | j$                  | j&                  | j(                  | j*                  || j,                        }| j.                  d	k  r"||j1                  t        j                        z  }||n|}|j3                  ||dd|f   |d
       |	|	n|}t5        | j                  |j6                  |||dd|f   |||| j8                  |
       || j:                  ||f<   X |S )z6Fit another stage of ``n_trees_per_iteration_`` trees.)rV   rs   rf   rt   Nrs   rf   rt   r,   )rF   r,   rD   best)r   r   r   r   r   r   r   r   r   r   r   r   F)rt   check_input)r~   rg   )rw   _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_predictionsrt   r}   r   X_cscX_csr
original_yre   
neg_g_viewrg   r{   X_for_tree_updates                   r@   
_fit_stagezBaseGradientBoosting._fit_stage  s    
djj),ZZ.+	 

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



!1a4 "00 &*DQT"Y 4\ rB   c                    t        | j                  t              r| j                  dk(  rYt        |       r:t	        dt        t        j                  | j                                    }|| _        y| j                  }|| _        y| j                  dk(  r:t	        dt        t        j                  | j                                    }|| _        yt	        dt        t        j                  | j                                    }|| _        y| j                  | j                  }|| _        yt        | j                  t              r| j                  }|| _        yt	        dt        | j                  | j                  z              }|| _        y)zSet self.max_features_.autor,   sqrtN)rw   r   strr   maxintrI   r   n_features_in_log2r   max_features_)r   r   s     r@   _set_max_featuresz&BaseGradientBoosting._set_max_features  sE   d''-  F* &#&q#bggd6I6I.J*K#LL * $(#6#6L * ""f,"1c"''$2E2E*F&GH *  #1c"''$2E2E*F&GH * &..L * ))84,,L * q#d&7&7$:M:M&M"NOL)rB   c                 ^   | j                   | _        | j                  t        |       rt        d      | _        n{t	        | j
                  t        t        f      rt        dd      | _        nHt	        | j
                  t              rt        d| j                        | _        nt        d      | _        t        j                  | j                  | j                  ft              | _        t        j"                  | j                  ft        j$                        | _        | j(                  d	k  r~t        j"                  | j                  t        j$                        | _        t        j"                  | j                  t        j$                        | _        t        j.                  | _        yy)
z@Initialize model state and allocate model state data structures.Nprior)strategyr2   g      ?)r   r2   meanrD   r   )r   init_r   r   rw   r   r   r   r   r   r   rI   emptyr   r   objectr   zerosrN   r   r   r   oob_scores_nan
oob_score_r   s    r@   _init_statez BaseGradientBoosting._init_state  s    YY
::T",g>
DJJ	(BC+Z#N
DJJ4+Z$**U
+V<
88 ; ;<F
 HHd&7&7%9L>>C$&HHd.?.?

$SD!!xx):):2::ND ffDO  rB   c                    t        | d      r t        j                  dt              | _        t        | d      r| `t        | d      r| `t        | d      r| `t        | d      r| `t        | d      r| `	t        | d	      r| `
y
y
)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_statez!BaseGradientBoosting._clear_state.  s    4'!xxf=D4(!4+,%4' 4&4!
4 	 !rB   c                     | j                   }|| j                  j                  d   k  rt        d|| j                  d   fz        t	        j
                  | j                  || j                  f      | _        t	        j
                  | j                  |      | _        | j                  dk  st        | d      rt        | d      r`t	        j
                  | j                  |      | _
        t	        j
                  | j                  |      | _        t        j                  | _        yt	        j                  |ft        j                        | _
        t	        j                  |ft        j                        | _        t        j                  | _        yy)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_statez"BaseGradientBoosting._resize_state?  sG    ".. 0 0 6 6q 99:%t'7'7':;< 
 99143N3NO
 IId&7&79KL>>A/A!Bt/0(*		))+=)% $&99T-=-=?Q#R "$&&(*'))% $&88-?,A#T "$&& "CrB   c                 4    t        t        | dg             dkD  S )Nr   r   )r   getattrr  s    r@   
_is_fittedzBaseGradientBoosting._is_fitted\  s    7434q88rB   c                     t        |        y)zACheck that the estimator is initialized, raising an error if not.N)r*   r  s    r@   _check_initializedz'BaseGradientBoosting._check_initialized_  s
    rB   )prefer_skip_nested_validationc                 "   | j                   s| j                          t        | ||g dt        d      \  }}|du }t	        ||      }|r| j                  |d      }n| j                  ||      }t        |d      }| j                          | j                  |      | _	        | j                  t        |       r|nd}t        |||| j                  | j                  |      \  }}}	}
}}t        |       rF| j                  t!        j"                  |	      j$                  d	   k7  rt'        d
      |||}}	}dx}x}
}|j$                  d	   }| j)                         s| j+                          | j,                  dk(  r2t!        j.                  || j0                  ft         j2                        }n|r| j,                  j5                  ||	       nNdj7                  | j,                  j8                  j:                        }	 | j,                  j5                  ||	|       tA        || j,                  | j                  t        |             }d	}tC        | j                        | _"        n| jF                  | jH                  j$                  d	   k  r1t'        d| jF                  | jH                  j$                  d	   fz        | jH                  j$                  d	   }tK        |t        ddd      }| jM                  |      }| jO                          | jQ                  ||	||| jD                  ||
|||
      }|| jH                  j$                  d	   k7  rp| jH                  d| | _$        | jR                  d| | _)        tU        | d      r<| jV                  d| | _+        | jX                  d| | _,        | jX                  d   | _-        || _.        | S # t<        $ r}dt?        |      v rt'        |      | d}~wt&        $ r}dt?        |      v rt'        |      | d}~ww xY w)aP  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|   rt   )r;   rt   )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|   rt   monitorsample_weight_is_noner!  X_trainX_valy_trainy_valsample_weight_trainsample_weight_val	n_samplesr   msger   n_stagess                      r@   r   zBaseGradientBoosting.fitc  s   P  /
1 !. 5,]A> $7A-@A&  ^^-^@
  ,)$/qTH !!..22!#! T"??bii&8&>&>q&AA
 %   56q-1WG044E4E-MM!$	   zzV#"$(($d&A&AB**# )JJNN7G4##)6$***>*>*G*G#H "

#W<O ' & #8TZZ]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(,(=(=ix(H%#'#3#3IX#> "&"2"22"6%S % "HCPQFR",S/q8!% "258V< #-S/q8!"s$   <O   	P	O##P/P		Pc                 4   |j                   d   }| j                  dk  }t        j                  |ft              }t        dt        | j                  |z              }| j                  r(t        | j                        }|j                  | |	       t        |      rt        |      nd}t        |      rt        |      nd}| j                  At        j                  | j                  t        j                        }| j!                  |d      }t#        | j$                  t&        t(        f      rd	}nd}|	}t+        |	| j,                        D ]  }|r9t/        |||      }||    }||    }|dk(  r|| j%                  |||    |
      z  }| j1                  |||||||||	      }|r|| j%                  ||   ||   ||   
      z  | j2                  |<   || j%                  ||    
      z  | j4                  |<   |dk(  rn| j4                  |dz
     }|| j4                  |   z
  | j6                  |<   | j4                  d   | _        n$|| j%                  |||
      z  | j2                  |<   | j                  dkD  rj;                  ||        |
 |
|| t=                     }|r |dz   S | j                  l|| j%                  |t?              |      z  }t        j@                  || jB                  z   k        r|||tE        |      z  <    |dz   S  |dz   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_predictrw   r   r   r   r   r   r.   r   r   r  r   r  r   localsnextanyr   r   )r   rT   r|   r   rt   r   r1  r3  r5  r   r.  r6  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,  z BaseGradientBoosting._fit_stages,  sY   ( 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 ~t'8'89A1)WlS ++8++F(6#)DJJ+'6|'D&> -7 - $L #oo . 
O '-

[>#2;#?"/"< 1; 1 (!!!$
 '-tzz'#2K<#@": 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:ILS%6!671uS :R 1urB   c                     t               r   )NotImplementedError)r   r   s     r@   _make_estimatorz$BaseGradientBoosting._make_estimator  s    !##rB   c                 Z   | j                          | j                  d   j                  |d      }| j                  dk(  r@t	        j
                  |j                  d   | j                  ft        j                        }|S t        || j                  | j                  t        |             }|S )z>Check input and compute raw predictions of the init estimator.r	  Tr;  r"  r   r#  )r  r   _validate_X_predictr   rI   r  r  r   rN   rY   r   r   r   rT   r   s      r@   _raw_predict_initz&BaseGradientBoosting._raw_predict_init  s    !T"66qd6K:: hhwwqz4#>#>?rzzO  44::tzz=+>O rB   c                     t        |        | j                  |      }t        | j                  || j                  |       |S )z?Return the sum of the trees raw predictions (+ init estimator).)r*   rU  r0   r   r~   rT  s      r@   r+  z!BaseGradientBoosting._raw_predict  s:    003t''D,>,>PrB   c              #     K   |rt        | |t        ddd      }| j                  |      }t        | j                  j
                  d         D ]7  }t        | j                  ||| j                  |       |j                          9 yw)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``.
        r$  r  FrE   r%  r  resetr   N)	r+   r   rU  r   r   r  r/   r~   rp   )r   rT   r   r   r   s        r@   r@  z(BaseGradientBoosting._staged_raw_predict  s     0 auCuEA 003t''--a01A$**Aq$2D2DoV!&&(( 2s   BBc                    | j                          | j                  D cg c]$  }|D ]  }|j                  j                  dkD  r| & }}}|s/t	        j
                  | j                  t        j                        S |D cg c]  }|j                  j                  d        }}t	        j                  |dt        j                        }|t	        j                  |      z  S c c}}w c c}w )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#  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_z)BaseGradientBoosting.feature_importances_  s    ( 	! ))
)zz$$q(  ) 	 
 88$"5"5RZZHH '(
& JJ22U2C& 	% (
 #%''(q

#
 '0G)HHH#
(
s   )C$#C*c                 L   | j                   't        j                  d| j                   z  t               t	        j
                  |t        d      }| j                  j                  \  }}t	        j                  ||j                  d   ft        j                  d      }t	        j
                  |t        j                  d      }t        |      D ]C  }t        |      D ]3  }| j                  ||f   j                  }|j                  ||||          5 E || j                  z  }|S )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.r$  )rE   r%  r   )r   r:   r;   UserWarningrI   asarrayr   r   r  r  rN   intpr   r   compute_partial_dependencer~   )	r   gridtarget_featuresr   n_trees_per_stageaveraged_predictionsr_  rg   r{   s	            r@   %_compute_partial_dependence_recursionz:BaseGradientBoosting._compute_partial_dependence_recursion  s   $ 99 MM!%+ 	 zz$e37*.*:*:*@*@''!xx

1.bjj 
 **_BGG3O<(E,-''q177///+?+B . ) 	 2 22##rB   c                 z   | j                          | j                  d   j                  |d      }| j                  j                  \  }}t	        j
                  |j                  d   ||f      }t        |      D ]>  }t        |      D ].  }| j                  ||f   }|j                  |d      |dd||f<   0 @ |S )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, 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	  Tr;  r   FN)r  r   rS  r  rI   r  r   rv   )r   rT   r   rm   leavesr   r   rU   s           r@   rv   zBaseGradientBoosting.apply=  s    ( 	!T"66qd6K #'"2"2"8"8i1771:|Y?@|$A9% ,,QT2	"+//!/"Gq!Qw & %
 rB   NN)r   N)T)#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,  rQ  rU  r+  r@  propertyrc  rm  rv   r   rB   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!rB   r   )	metaclassc                        e Zd ZU dZi ej
                   eddh      g edh      d eddg      gdZee	d	<   dd
ddddddddddddddd
dddd fd
Z
d Zd Zd Zd Zd Zd Zd Zd Zd Z xZS ) GradientBoostingClassifiera~8  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)`.

    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exponentialr"  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                L    t         |   ||||||||	|||||||
|||||       y )N)rV   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   superr   )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   z#GradientBoostingClassifier.__init__  sS    0 	'%/-%=%%)"7! 3-) 	 	
rB   c                    t        |       t               }|j                  |      }|j                  | _        | j                  j                  d   }|dk  rdn|| _        |j                  t        d      }|| _        ||}n)t        j                  t        j                  ||            }|dk  rt        d|z        |S )Nr   r   r,   Frp   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   r'  rI   count_nonzerobincountr  )r   r|   rt   label_encoderencoded_y_intrm   	encoded_yn_trim_classess           r@   r   z$GradientBoostingClassifier._encode_y  s     	%Q'$%33A6%..MM''*	 ,5>ay#!((U(;	 $ &N--bkk-.WXNA57EF 
 rB   c                 &   | j                   dk(  r2| j                  dk(  rt        |      S t        || j                        S | j                   dk(  rA| j                  dkD  r&t	        d| j                    d| j                   d      t        |      S y )	Nrx  r   r  )rt   rm   ry  zloss='zK' is only suitable for a binary classification problem, you have n_classes=z%. Please use loss='log_loss' instead.)rV   r'  r   r   r  r   r   s     r@   r   z$GradientBoostingClassifier._get_loss  s    99
"!#'mDD*"/4??  YY-'" TYYK (337??2C D::  ']CC (rB   c                     t        | |t        ddd      }| j                  |      }|j                  d   dk(  r|j	                         S |S )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,).
        r$  r  FrX  r,   )r+   r   r+  r  ravelrT  s      r@   decision_functionz,GradientBoostingClassifier.decision_function  sU    & !55
 ++A.  #q("((**rB   c              #   B   K   | j                  |      E d{    y7 w)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)r@  r   rT   s     r@   staged_decision_functionz3GradientBoostingClassifier.staged_decision_function+  s     , ++A...s   c                     | j                  |      }|j                  dk(  r|dk\  j                  t              }nt	        j
                  |d      }| j                  |   S )a  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   z"GradientBoostingClassifier.predictC  sV     0031$.!3;;C@O iia@O}}_--rB   c              #   z  K   | j                   dk(  r\| j                  |      D ]G  }|j                         dk\  j                  t              }| j
                  j                  |d       I y| j                  |      D ]8  }t        j                  |d      }| j
                  j                  |d       : yw)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)	r'  r@  r   rP   r   r  ra   rI   r  r  s       r@   staged_predictz)GradientBoostingClassifier.staged_predictY  s     $ ??a#'#;#;A#>#2#:#:#<#A"I"I#"Nmm((q(AA $? $(#;#;A#>"$))O!"Dmm((q(AA $?s   B9B;c                 Z    | j                  |      }| j                  j                  |      S )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   rT  s      r@   rG   z(GradientBoostingClassifier.predict_probat  s)    * 003zz''88rB   c                 N    | j                  |      }t        j                  |      S )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_probaz,GradientBoostingClassifier.predict_log_proba  s"    * ""1%vve}rB   c              #      K   	 | j                  |      D ]  }| j                  j                  |       ! y# t        $ r  t        $ r}t	        d| j
                  z        |d}~ww xY ww)aK  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)r@  r   rG   r   AttributeErrorrV   )r   rT   r   r8  s       r@   staged_predict_probaz/GradientBoostingClassifier.staged_predict_proba  sk     $	#'#;#;A#>jj..?? $? 	 	 8499D	s%   A+38 A+A(
A##A((A+)r   r   r   r   r   r   r&   r$   rq  rr  r   r   r   r  r  rO   r  rG   r  r  __classcell__r)  s   @r@   rw  rw  a  s    GR
$

5
5$Z789VH%tZ8P-QR$D   !$!--
^<D$6/0.,B6900rB   rw  c                        e Zd ZU dZi ej
                   eh d      g edh      d eddg      g ee	ddd	
      gdZe
ed<   dddddddddddddddddddddd fd
ZddZd Zd Zd Z fdZ xZS ) GradientBoostingRegressora7  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...])
    >>> 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_errorr"  Nr   rO   r5   r   r   r   )rV   r   r   r   r   r   r   r   r   r,   rz  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                N    t         |   ||||||||	||||
|||||||||       y )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   r)  s                         r@   r   z"GradientBoostingRegressor.__init__  sV    2 	'%/-%=%"7%)! 3-+ 	 	
rB   c                 B    d| _         |j                  t        d      }|S )Nr,   Fr  )r   rP   r   r   s      r@   r   z#GradientBoostingRegressor._encode_y@  s!    &'#HHV%H(rB   c                     | j                   dv r$t        | j                      || j                        S t        | j                      |      S )Nr1   )rt   r2   r  )rV   r   r   r   s     r@   r   z#GradientBoostingRegressor._get_lossF  s=    99--499%MDJJWW499%MBBrB   c                 j    t        | |t        ddd      }| j                  |      j                         S )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.
        r$  r  FrX  )r+   r   r+  r  r  s     r@   rO   z!GradientBoostingRegressor.predictL  s7     !55
   #))++rB   c              #   \   K   | j                  |      D ]  }|j                           yw)aI  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)r@  r  rT  s      r@   r  z(GradientBoostingRegressor.staged_predicta  s,     $  $77:O!''))  ;s   *,c                     t         |   |      }|j                  |j                  d   | j                  j                  d         }|S )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}  rv   rS   r  r   )r   rT   ro  r)  s      r@   rv   zGradientBoostingRegressor.applyv  sA    & q!
D,<,<,B,B1,EFrB   rp  )r   r   r   r   r   r   r&   r$   r%   r   rq  rr  r   r   r   rO   r  rv   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   rp   r   rA   rY   r   r   r   r   rw  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'^}<7 }@]	2F ]	@J0D JrB   