`L iV2dZddlZddlZddlmZmZddlmZmZddl m Z ddl Z ddl m Z mZmZddlmZmZmZmZmZmZmZmZdd lmZmZmZmZdd lmZm Z dd l!m"Z"dd l#m$Z$dd l%m&Z&ddl'm(Z(ddl)m*Z*m+Z+m,Z,ddl-m.Z.m/Z/m0Z0ddl1m2Z2m3Z3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:m;Z;mZ>ddl?m@Z@mAZAmBZBejZejeeddZEdZF d&dZGd'dZHGddZIGdd e>e!ZJGd"d#eeJZKGd$d%eeJZLy)(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)ABCMetaabstractmethod)IntegralReal)time) csc_matrix csr_matrixissparse)_LOSSES AbsoluteErrorExponentialLossHalfBinomialLossHalfMultinomialLossHalfSquaredError HuberLoss PinballLoss)ClassifierMixinRegressorMixin _fit_context is_classifier)DummyClassifierDummyRegressor)NotFittedError)train_test_split) LabelEncoder)DecisionTreeRegressor)DOUBLEDTYPE TREE_LEAF) check_arraycheck_random_state column_or_1d) HasMethodsInterval StrOptions)check_classification_targets)_weighted_percentile)_check_sample_weightcheck_is_fitted validate_data) BaseEnsemble)_random_sample_mask predict_stagepredict_stagesquantilehuberct|dkryt|t|z }t|t|z }tj|rt j dt |S)z'Prevents overflow and division by zero.gu?j/ z$overflow encountered in _safe_divide)absfloatmathisinfwarningswarnRuntimeWarning) numerator denominatorresults Z/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/ensemble/_gb.py _safe_dividerAAs` ;& y!E+$66y!E+$66 ::f  MM@. Q c|r~|j|}|js |dddf}tjtjj }tj ||d|z tj}n.|j|jtj}|jdk(r+|jj|jddS|jj|S)aReturn 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_multiclassnpfinfofloat32epsclipfloat64predictastypendimlinkreshape)X estimatorlossuse_predict_proba predictionsrLs r@_init_raw_predictionsrYVs2 --a0 !!%ad+Khhrzz"&&ggk3CrzzJ ''*11"**= 1yy~~k*222q99yy~~k**rBc ||j|} tts| j} d| |<ttrfd} n3tt rfd} ntt rfd} nfd} tj|jtk(dD]W} tj| | k(d}|j|d}|dn||| ||||| }||j| ddf<Y|dd| fxx||jddddfj| dzz cc<y) aUpdate 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. rFc|j|d}||z }tj| }tj|d|z z }t||SNraxisweightsr,)takerIaveragerA) y_indices neg_gradientraw_predictionkneg_gprobr=r>sws r@compute_updatez0_update_terminal_regions..compute_updatesY%))'):EzJJub9  jjT):BG #I{;;rBc|j|d}||z } j}tj| }||dz |z z}tj|d|z z } t || Sr\)ra n_classesrIrbrA) rcrdrerfrgrhriKr=r>rVrjs r@rkz0_update_terminal_regions..compute_updatest$))'):EzNNJJub9 a!eq[(  jjT):BG #I{;;rBc|j|d}tj| }|j}||dk(xxdzcc<tj| }t ||S)Nrr]r_rF)rarIrbcopyrA) rcrdrerfrgrhr=hessianr>rjs r@rkz0_update_terminal_regions..compute_updatesf$))'):JJub9  **,a B&  jj"= #I{;;rBc:j||||fz S)N)y_true sample_weight)fit_intercept_only)rcrdrerfrgrVrjs r@rkz0_update_terminal_regions..compute_updates/..wz ::"$/rBrr]N) apply isinstancerrprrrrInonzero children_leftr ravalue)rVtreerTyrerfrt sample_mask learning_ratergterminal_regionsmasked_terminal_regionsrkleafrdrcupdaterjs` @r@_update_terminal_regionsrsJnzz!} d, -"2"7"7"902 - d, - <1 2 <"o . < JJt11Y>?B ,Djj!8D!@AGa(B&.M'4JB#B~qQF&,DJJtQz " ,1a4MDJJq!Qw,?,D,Dq-E-rBctj||jz }t||d|jz}t ||j _y)z:Calculate and set self.closs.delta based on self.quantile.dN)rIr6squeezer(r2r7clossdelta)rVrsrfrtabserrrs r@set_huber_deltar sE VVF^3355 6F dmm8K LEU|DJJrBc$eZdZdZdZddZdZy)VerboseReporteraReports 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||_yNverbose)selfrs r@__init__zVerboseReporter.__init__s  rBcrddg}ddg}|jdkr"|jd|jd|jd|jd td d t|dz zzt |zd 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}zRemaining Timez{remaining_time:>16s}z%10s z%16s  N) subsampleappendprintlentuplejoin verbose_fmt verbose_modr start_timebegin_at_stage)restr header_fieldsrs r@initzVerboseReporter.init s . $&<= ==1    /   2 3-.23 wC $6$:;;u]?SST88K0&,rBcF|jdk}||jz }|dz|jzdk(r|r|j|nd}|j|dzz t |j z zt|dzz }|dkDrdj|dz }ndj|}t|jj|dz|j||||jdk(r/|dz|jdzzdkDr|xjdzc_y y y y ) zUpdate reporter with new iteration. Parameters ---------- j : int The new iteration. est : Estimator The estimator. r,r<z{0:.2f}mgN@z{0:.2f}s)iter train_scoreoob_imprremaining_time N) rrroob_improvement_ n_estimatorsrrr7formatrr train_score_r)rjrdo_oobirrs r@rzVerboseReporter.update>s7" ## # ET%% % *28s++A.aH!!QU+0HIERSVWRWLX "!+!2!2>D3H!I!+!2!2>!B   ''Q # 0 0 3%#1 ( ||q q1u$2B2BR2G&H1&L  B& 'M # +rBN)r)__name__ __module__ __qualname____doc__rrrrBr@rrs-< 'rBrceZdZUdZiej eedddgeedddge ddhgeedd d gd gd geedd d geeddddgeedddgd Ze e d<ejdejde dddddddddZe d-dZe dZ d-dZdZdZdZdZd Zd!Zed"d-d#Z d.d$Zd/d%Zd&Zd'Zd/d(Zed)Z d*Z!d+Z"fd,Z#xZ$S)0BaseGradientBoostingz*Abstract base class for Gradient Boosting.r5Nleftclosedr, friedman_mse squared_error?rightrbooleanneither) r~r criterionrr warm_startvalidation_fractionn_iter_no_changetol_parameter_constraintssplitter monotonic_cst?rF皙?-C6?)alpharmax_leaf_nodesrrrrc*||_||_||_||_||_||_||_| |_| |_||_ | |_ | |_ | |_ ||_ ||_||_||_||_||_||_||_yr)rr~rVrmin_samples_splitmin_samples_leafmin_weight_fraction_leafr max_features max_depthmin_impurity_decrease ccp_alphar random_staterrrrrrr)rrVr~rrrrrrrrrrrrrrrrrrrs r@rzBaseGradientBoosting.__init__ss4)* "!2 0(@%"("%:"" (  ,$#6 0rBcy)z'Called by fit to validate and encode y.Nrrr|rts r@ _encode_yzBaseGradientBoosting._encode_yrBcy)z(Get loss object from sklearn._loss.loss.Nrrrts r@ _get_losszBaseGradientBoosting._get_lossrrBc |} t|jtrt|j||||jj ||d } | j dk(r| j d} n| } t|jD]U} |jjr(tj| | k(tj}t|jd|j|j |j"|j$|j&|j(|j*||j, }|j.d kr"||j1tjz}||n|}|j3|| dd| f|d | | n|}t5|j|j6||| dd| f||||j8| ||j:|| f<X|S) z6Fit another stage of ``n_trees_per_iteration_`` trees.)rVrsrfrtNrsrfrtr,)rFr,rDbest) rrrrrrrrrrrrF)rt check_input)r~rg)rw_lossrrgradientrQrSrangen_trees_per_iteration_rHrIarrayrNrrrrrrrrrrrrPfitrtree_r~ estimators_)rrrTr|raw_predictionsrtr}rX_cscX_csr original_yre neg_g_viewrgr{X_for_tree_updates r@ _fit_stagezBaseGradientBoosting._fit_stages djj) , ZZ.+   ++*,      !%--g6J%Jt223, *Azz''HHZ1_BJJ?)...."&"8"8!%!6!6)-)F)F&*&@&@!..#22).. D~~# - 0B0B2::0N N *A HH:ad#=e   */):  $  !1a4 "00 &*D  QT "Y, *\rBct|jtr|jdk(rYt|r:t dt t j|j}||_ y|j}||_ y|jdk(r:t dt t j|j}||_ yt dt t j|j}||_ y|j|j}||_ yt|jtr|j}||_ yt dt |j|jz}||_ y)zSet self.max_features_.autor,sqrtN) rwrstrrmaxintrIrn_features_in_log2r max_features_)rrs r@_set_max_featuresz&BaseGradientBoosting._set_max_featuressE d'' -  F* &#&q#bggd6I6I.J*K#LL*$(#6#6L*""f,"1c"''$2E2E*F&GH * #1c"''$2E2E*F&GH *   &..L * ))8 4,,L*q#d&7&7$:M:M&M"NOL)rBc^|j|_|jt|rtd|_n{t |j t tfrtdd|_nHt |j trtd|j|_ntd|_tj|j|jft|_tj"|jftj$|_|j(d kr~tj"|jtj$|_tj"|jtj$|_tj.|_yy) z@Initialize model state and allocate model state data structures.Nprior)strategyr2g?)rr2meanrDr)rinit_rrrwrr rrrrrIemptyrrobjectrzerosrNrrr oob_scores_nan oob_score_rs r@ _init_statez BaseGradientBoosting._init_statesYY :: T",g> DJJ (BC+Z#N DJJ 4+Z$**U +V< 88    ; ; >C $&HHd.?.? $SD !!xx):):2::ND  ffDO rBct|dr tjdt|_t|dr|`t|dr|`t|dr|`t|dr|`t|dr|` t|d r|` y y ) z/Clear the state of the gradient boosting model.rrrrDrrrrr_rngN) hasattrrIrrrrrrrrr rs r@ _clear_statez!BaseGradientBoosting._clear_state.s 4 '!xxf=D  4 (! 4+ ,% 4 ' 4 & 4 ! 4   !rBc |j}||jjdkrtd||jdfzt j |j||j f|_t j |j||_|jdks t|drt|dr`t j |j||_ t j |j||_ tj|_ yt j|ftj|_ t j|ftj|_ tj|_ yy)z:Add additional ``n_estimators`` entries to all attributes.rz(resize with smaller n_estimators %d < %dr,rrDN)rrshape ValueErrorrIresizerrrr rrrrrrN)rtotal_n_estimatorss r@ _resize_statez"BaseGradientBoosting._resize_state?sG"..  0 0 6 6q 9 9:%t'7'7':;<  99   143N3NO IId&7&79KL >>A /A!Bt/0(* ))+=)%$&99T-=-=?Q#R "$&&(*'))%$&88-?,A#T "$&&"CrBc4tt|dgdkDS)Nrr)rgetattrrs r@ _is_fittedzBaseGradientBoosting._is_fitted\s7434q88rBct|y)zACheck that the estimator is initialized, raising an error if not.N)r*rs r@_check_initializedz'BaseGradientBoosting._check_initialized_s rB)prefer_skip_nested_validationc "|js|jt|||gdtd\}}|du}t ||}|r|j |d}n|j ||}t |d}|j|j||_ |jt|r|nd}t||||j|j|\}}} } } } t|rF|jt!j"| j$d k7rt'd |||} } }dx}x} } |j$d } |j)s|j+|j,d k(r2t!j.| |j0ft j2 }n|r|j,j5|| nNd j7|j,j8j:} |j,j5|| | tA||j,|jt|}d }tC|j|_"n|jF|jHj$d kr1t'd|jF|jHj$d fz|jHj$d }tK|tddd}|jM|}|jO|jQ|| || |jD|| | || }||jHj$d k7rp|jHd||_$|jRd||_)tU|dr<|jVd||_+|jXd||_,|jXd|_-||_.|S#t<$r}dt?|vr t'||d}~wt&$r}dt?|vr t'||d}~wwxYw)aPFit 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. )csrcsccooT) accept_sparserE multi_outputN)r|rt)r;rt)r test_sizestratifyrzhThe training data after the early stopping split is missing some classes. Try using another random seed.zerorrEz9The 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==TrueCrF)rEorderrensure_all_finiterrF)/rr r+rr)rr#rrrrrrrr n_classes_rIuniquerrrrrrrrNrr __class__r TypeErrorrrYr"r rrr! _raw_predictr _fit_stagesrr rrr n_estimators_)rrTr|rtmonitorsample_weight_is_noner!X_trainX_valy_trainy_valsample_weight_trainsample_weight_val n_samplesrmsgern_stagess r@rzBaseGradientBoosting.fitcsP       /  1!. 5,]A> $7A-@A  &  ^^-^@  ,)$/qTH!!..22!  #!T"??bii&8&>&>q&AA %  56q-1WG04 4E 4E-MM!$     zzV#"$(($d&A&AB**# )JJNN7G4##)6$***>*>*G*G#H" #W "&"2"22"6% S%"HCPQFR",S/q8!%"258V<#-S/q8!"s$<O P O## P/P  Pc 4|jd} |jdk} tj| ft} t dt |j| z}|jr(t|j}|j|| t|r t|nd}t|r t|nd}|jAtj|jtj}|j!|d}t#|j$t&t(frd }nd}| }t+| |j,D]}| r9t/| ||} || }|| }|dk(r||j%||| | z}|j1|||||| ||| }| r||j%|| || ||  z|j2|<||j%||  z|j4|<|dk(rn|j4|dz }||j4|z |j6|<|j4d |_n$||j%||| z|j2|<|jdkDrj;||| | ||t=}|r|dzS|jl||j%|t?|z}tj@||jBzkr|||tE|z<|dzS|dzS) 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. rrrDr,rNFrr r)rrrF)#rrrIonesboolrrrrrr rr rfullinf_staged_raw_predictrwrrrrrr.rrrrrrlocalsnextanyrr)rrTr|rrtrr1r3r5rr.r6rr}n_inbagverbose_reporterrr loss_historyy_val_pred_iterfactorr y_oob_maskedsample_weight_oob_masked initial_loss previous_lossearly_stoppingvalidation_losss r@r,z BaseGradientBoosting._fit_stages,s`(GGAJ #%ggyl$7 aT^^i789 <<.t||D   ! !$ 7!)! 1 $!)! 1 $  ,774#8#8"&&AL#66u%6PO  JJ    FF ~t'8'89G A1)WlS  + +8++F(6#)DJJ+'6 |'D&>-7-$L#oo. O'- [>#2;#?"/ "<1;1(!!!$ '-tzz'#2K<#@":0:0'  # 12Q DCheck input and compute raw predictions of the init estimator.r Tr;r"rr#) rr_validate_X_predictrrIrrrrNrYrrrrTrs r@_raw_predict_initz&BaseGradientBoosting._raw_predict_inits !   T " 6 6qd 6 K ::  hhwwqz4#>#>?rzzO44::tzz=+>OrBct||j|}t|j||j||S)z?Return the sum of the trees raw predictions (+ init estimator).)r*rUr0rr~rTs r@r+z!BaseGradientBoosting._raw_predicts:003t''D,>,>PrBc#K|rt||tddd}|j|}t|jj dD]7}t |j|||j||j9yw)aCompute 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$rFrEr%rresetrN) r+rrUrrrr/r~rp)rrTrrrs r@r@z(BaseGradientBoosting._staged_raw_predicts0 auCuEA003t''--a01 )A $**Aq$2D2Do V!&&( ( )sBBc|j|jDcgc]$}|D]}|jjdkDr|&}}}|s/t j |j tjS|Dcgc]}|jjd }}t j|dtj}|t j|z Scc}}wcc}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) rrr node_countrIrrrNcompute_feature_importancesrsum)rstager{relevant_treesrelevant_feature_importancesavg_feature_importancess r@feature_importances_z)BaseGradientBoosting.feature_importances_s( !))  zz$$q(    88$"5"5RZZH H'(  JJ 2 2U 2 C( $( #%'' (q # '0G)HHH# ( s )C$#C*cL|j'tjd|jztt j |t d}|jj\}}t j||jdftjd}t j |tjd}t|D]C}t|D]3}|j||fj}|j||||5E||jz}|S)aFast 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$)rEr%r)rr:r; UserWarningrIasarrayrrrrrNintprrcompute_partial_dependencer~) rgridtarget_featuresrn_trees_per_stageaveraged_predictionsr_rgr{s r@%_compute_partial_dependence_recursionz:BaseGradientBoosting._compute_partial_dependence_recursions$ 99 MM!%+   zz$e37*.*:*:*@*@' '!xx  1 .bjj **_BGG3O<( E,- ''q177///+?+B    2 22##rBcz|j|jdj|d}|jj\}}t j |jd||f}t |D]>}t |D].}|j||f}|j|d|dd||f<0@|S)aApply 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;rFN)rrrSrrIrrrv)rrTrrmleavesrrrUs r@rvzBaseGradientBoosting.apply=s( !   T " 6 6qd 6 K#'"2"2"8"8 i1771:|Y?@|$ HA9% H ,,QT2 "+//!/"Gq!Qw H H  rBcFt|}d|j_|S)NT)super__sklearn_tags__ input_tagssparse)rtagsr)s r@rrz%BaseGradientBoosting.__sklearn_tags__`s!w')!% rBNN)rN)T)%rrrrrrr%rrr&dict__annotations__poprrrrrrrr rrrrrr,rQrUr+r@propertyrcrmrvrr __classcell__r)s@r@rras4 $  6 6 $"4d6BC!(AtFCD ./!BCDtS#g>?; k (sC JK%h4GNsD89 $D z*/$ /--^6677Tl**%0"):9&+C C^BH$ )B&I&IP($T!FrBr) metaclassceZdZUdZiej eddhgedhdeddggdZee d <dd d d d dddddddddddd ddddfd Z dZ dZ dZ dZdZdZdZdZdZxZS) GradientBoostingClassifieraA9Gradient 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 `. 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 `. 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 `. 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"NrrG)rVrrrrrrr r,r5rFr)rVr~rrrrrrrrrrrrrrrrrrcLt||||||||| | || | ||| |||||y)N)rVr~rrrrrrrrrrrrrrrrrrrqr)rrVr~rrrrrrrrrrrrrrrrrrr)s r@rz#GradientBoostingClassifier.__init__sS0 '%/-%=%%)"7! 3-)  rBct|t}|j|}|j|_|jjd}|dkrdn||_|j td}||_||}n)tjtj||}|dkrtd|z|S)Nrr r,Frpzuy contains %d class after sample_weight trimmed classes with zero weights, while a minimum of 2 classes are required.) r'r fit_transformclasses_rrrPr7r'rI count_nonzerobincountr)rr|rt label_encoder encoded_y_intrm encoded_yn_trim_classess r@rz$GradientBoostingClassifier._encode_ys %Q'$ %33A6 %.. MM''* ,5>ay#!((U(; $  &N--bkk-.WXN A 57EF  rBc&|jdk(r2|jdk(r t|St||jS|jdk(rA|jdkDr&t d|jd|jdt |Sy) Nrr r)rtrmrzloss='zK' is only suitable for a binary classification problem, you have n_classes=z%. Please use loss='log_loss' instead.)rVr'rrrrrs r@rz$GradientBoostingClassifier._get_losss 99 "!#'mDD*"/4??YY- '" TYYK(337??2CD:: ']CC(rBct||tddd}|j|}|jddk(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$rFrXr,)r+rr+rravelrTs r@decision_functionz,GradientBoostingClassifier.decision_functionsU&  !55 ++A.   #q ("((* *rBc#BK|j|Ed{y7w)aCompute 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@rrTs r@staged_decision_functionz3GradientBoostingClassifier.staged_decision_function4s,++A...s c|j|}|jdk(r|dk\jt}nt j |d}|j |S)aPredict 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,rr])rrQrPrrIargmaxrrrTrencoded_classess r@rOz"GradientBoostingClassifier.predictLsV003   1 $.!3;;C@O iia@O}}_--rBc#zK|jdk(r\|j|D]G}|jdk\jt}|j j |dIy|j|D]8}tj|d}|j j |d:yw)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 rr]r,N) r'r@rrPrrrarIrrs r@staged_predictz)GradientBoostingClassifier.staged_predictbs$ ??a #'#;#;A#> B#2#:#:#<#A"I"I#"Nmm((q(AA B$(#;#;A#> B"$))O!"Dmm((q(AA BsB9B;cZ|j|}|jj|S)aPredict 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. )rrrGrTs r@rGz(GradientBoostingClassifier.predict_proba}s)*003zz''88rBcN|j|}tj|S)aPredict 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. )rGrIlog)rrTprobas r@predict_log_probaz,GradientBoostingClassifier.predict_log_probas"*""1%vve}rBc#K |j|D]}|jj|!y#t$rt$r}t d|j z|d}~wwxYww)aKPredict 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@rrGrAttributeErrorrV)rrTrr8s r@staged_predict_probaz/GradientBoostingClassifier.staged_predict_probasr$ #'#;#;A#> @jj..?? @    8499D  s%A+38A+A( A##A((A+)rrrrrrr&r$rwrxrrrrrrOrrGrrr{r|s@r@rrfsKZ $  5 5$Z789VH%tZ8P-QR$D !$!  -- ^<D$6/0.,B6900rBrceZdZUdZiej ehdgedhdeddggee ddd gd Ze e d <d dddddddddddddddddddddfd Z ddZ dZdZdZfdZxZS) GradientBoostingRegressora7Gradient 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 `. 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 `. 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 `. 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`. >r3r2rabsolute_errorr"NrrOr5rrr)rVrrrrrrrr r,rrrFr)rVr~rrrrrrrrrrrrrrrrrrrcNt||||||||| | || | | ||||||||y)N)rVr~rrrrrrrrrrrrrrrrrrrr)rrVr~rrrrrrrrrrrrrrrrrrrr)s r@rz"GradientBoostingRegressor.__init__sV2 '%/-%=%"7%)! 3-+  rBcBd|_|jtd}|S)Nr,Fr)rrPrrs r@rz#GradientBoostingRegressor._encode_yIs!&'# HHV%H (rBc|jdvr$t|j||jSt|j|S)Nr1)rtr2r)rVr rrs r@rz#GradientBoostingRegressor._get_lossOs= 99- -499%MDJJW W499%MB BrBcjt||tddd}|j|jS)aPredict 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$rFrX)r+rr+rrs r@rOz!GradientBoostingRegressor.predictUs7  !55   #))++rBc#\K|j|D]}|jyw)aIPredict 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@rrTs r@rz(GradientBoostingRegressor.staged_predictjs1$ $77: *O!'') ) *s*,ct||}|j|jd|jjd}|S)aApply 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)rqrvrSrr)rrTror)s r@rvzGradientBoostingRegressor.applysA&q! D,<,<,B,B1,EF rBrv)rrrrrrr&r$r%rrwrxrrrrOrrvr{r|s@r@rrsDL $  5 5$TUVVH%tZ 8J-KL4c)<= $D !$!  // b C ,***rBr)rrr)Mrr8r:abcrrnumbersrrrnumpyrI scipy.sparserr r _loss.lossr r rrrrrrbaserrrrdummyrr exceptionsrmodel_selectionr preprocessingrr{r tree._treerrr utilsr!r"r#utils._param_validationr$r%r&utils.multiclassr' utils.statsr(utils.validationr)r*r+_baser-_gradient_boostingr.r/r0rprrArYrrrrrrrrBr@rs* '"99   PO3'.((11AAFF;.SSRR ',,.*'+fGT$L'L'^B <7B Ja 2Fa HJ0DJrB