B
    0d#                @   s  d Z ddlmZ ddlmZ ddl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 ddlmZ ddlmZ ddlmZ ddlmZ ddlZddl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 ddl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( ddl)m*Z* ddl+m,Z, G dd dZ-G d d! d!eed"Z.G d#d$ d$ee.Z/G d%d& d&e	e.Z0dS )'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.
    )ABCMeta)abstractmethodN   )BaseEnsemble   )ClassifierMixin)RegressorMixin)BaseEstimator)is_classifier)
deprecated)predict_stages)predict_stage)_random_sample_mask)
csc_matrix)
csr_matrix)issparse)time)train_test_split)DecisionTreeRegressor)DTYPEDOUBLE)
_gb_losses)check_random_state)check_array)column_or_1d)check_is_fitted_check_sample_weight)check_classification_targets)NotFittedErrorc               @   s*   e Zd ZdZdd Zd
ddZdd Zd	S )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             C   s
   || _ d S )N)verbose)selfr     r"   F/var/www/html/venv/lib/python3.7/site-packages/sklearn/ensemble/_gb.py__init__F   s    zVerboseReporter.__init__r   c             C   s   ddg}ddg}|j dk r.|d |d |d |d	 td
dt|d   t|  d|| _d| _t | _	|| _
dS )zInitialize reporter

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

        begin_at_stage : int, default=0
            stage at which to begin reporting
        Z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/   Zheader_fieldsr,   r"   r"   r#   initI   s    




 zVerboseReporter.initc             C   s   |j dk }|| j }|d | j dkr|r4|j| nd}|j|d  t | j  t|d  }|dkrvd|d }n
d|}t	| j
j|d |j| ||d | jdkr|d | jd  dkr|  jd9  _d	S )
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)iterZtrain_scoreoob_imprremaining_time
   N)r&   r/   r-   oob_improvement_n_estimatorsr   r.   floatformatr(   r,   train_score_r    )r!   jr0   do_oobir4   r5   r"   r"   r#   updateg   s     


&

 zVerboseReporter.updateN)r   )__name__
__module____qualname____doc__r$   r1   r?   r"   r"   r"   r#   r   ;   s   	
r   c            	   @   s   e Zd ZdZeddddddddd	d
Zed3ddZd4ddZdd Zdd Z	dd Z
dd Zdd Zdd Zedd Zd5ddZd6dd Zd7d"d#Zd$d% Zd&d' Zd8d(d)Zed*d+ Zd,d- Zd.d/ Zed0ed1d2 ZdS )9BaseGradientBoostingz*Abstract base class for Gradient Boosting.g?r   NFg?g-C6?)alphar    max_leaf_nodes
warm_startvalidation_fractionn_iter_no_changetolc            C   s   || _ || _|| _|| _|| _|| _|| _|| _|| _|| _	|	| _
|| _|
| _|| _|| _|| _|| _|| _|| _|| _|| _d S )N)r8   learning_rateloss	criterionmin_samples_splitmin_samples_leafmin_weight_fraction_leafr&   max_features	max_depthmin_impurity_decrease	ccp_alphar1   random_staterE   r    rF   rG   rH   rI   rJ   )r!   rL   rK   r8   rM   rN   rO   rP   rR   rS   r1   r&   rQ   rT   rU   rE   r    rF   rG   rH   rI   rJ   r"   r"   r#   r$      s*    zBaseGradientBoosting.__init__c             C   s   dS )zCalled by fit to validate y.Nr"   )r!   ysample_weightr"   r"   r#   _validate_y   s    z BaseGradientBoosting._validate_yc
             C   s   |j tkst| j}
|}| }xt|
jD ]}|
jrJtj	||ktj
d}|
j||||d}t| jd| j| j| j| j| j| j| j|| jd}| jdk r||tj
 }|	dk	r|	n|}|j|||dd |
j|j||||||| j|d		 || j||f< q,W |S )
z@Fit another stage of ``_n_classes`` trees to the boosting model.)dtype)krW   best)rM   ZsplitterrR   rN   rO   rP   rS   rQ   rF   rU   rT   g      ?NF)rW   check_input)rK   rZ   )rY   boolAssertionErrorloss_copyrangeKZis_multi_classnparrayfloat64Znegative_gradientr   rM   rR   rN   rO   rP   rS   rQ   rF   rT   r&   astypefitZupdate_terminal_regionstree_rK   estimators_)r!   r>   XrV   raw_predictionsrW   sample_maskrU   X_cscX_csrrL   Z
original_yZraw_predictions_copyrZ   Zresidualtreer"   r"   r#   
_fit_stage   sJ    

zBaseGradientBoosting._fit_stagec             C   s  | j dkrtd| j  | jdkr0td| j | j| jksH| jtjkrXtd| j| jdkrpt	dt
 n| jdkrt	d	t
 | jd
krt| jdkrtjntj}ntj| j }t| r|| j| _n | jdkr|| j| _n| | _d| j  k rdksn td| j | jdk	rlt| jtrB| j| j n*t| jtr\| jdksltd| jd| j  k rdk sn td| j t| jtr2| jdkrt| rtdtt| j}n| j}nV| jdkrtdtt| j}n2| jdkr"tdtt| j}ntd| j nj| jdkrF| j}nVt| jt j!r^| j}n>d| j  k rxdkrn ntt| j| j d}ntd|| _"t| j#t j!t$dfstd| j# dS )z?Check validity of parameters and raise ValueError if not valid.r   z.n_estimators must be greater than 0 but was %rg        z/learning_rate must be greater than 0 but was %rzLoss '{0:s}' not supported. lszqThe loss 'ls' was deprecated in v1.0 and will be removed in version 1.2. Use 'squared_error' which is equivalent.ladzsThe loss 'lad' was deprecated in v1.0 and will be removed in version 1.2. Use 'absolute_error' which is equivalent.deviancer   )huberquantileg      ?z%subsample must be in (0,1] but was %rNzeroz>The init parameter must be an estimator or 'zero'. Got init={}z&alpha must be in (0.0, 1.0) but was %rautor   sqrtlog2zWInvalid value for max_features: %r. Allowed string values are 'auto', 'sqrt' or 'log2'.z'max_features must be in (0, n_features]zCn_iter_no_change should either be None or an integer. %r was passed)%r8   
ValueErrorrK   rL   _SUPPORTED_LOSSr   ZLOSS_FUNCTIONSr:   warningswarnFutureWarningr)   classes_ZMultinomialDevianceZBinomialDeviancer
   
n_classes_r_   rE   r&   r1   
isinstancer	   Zcheck_init_estimatorstrrQ   maxintrc   rx   n_features_in_ry   numbersIntegralZmax_features_rI   type)r!   Z
loss_classrQ   r"   r"   r#   _check_params
  sz    







z"BaseGradientBoosting._check_paramsc             C   sp   | j | _| jdkr| j | _tj| j| jjftd| _	tj
| jftjd| _| jdk rltj
| jtjd| _dS )z@Initialize model state and allocate model state data structures.N)rY   g      ?)r1   init_r_   Zinit_estimatorrc   emptyr8   rb   objectri   zerosre   r;   r&   r7   )r!   r"   r"   r#   _init_stateo  s    

z BaseGradientBoosting._init_statec             C   sV   t | drtjdtd| _t | dr(| `t | dr6| `t | drD| `t | drR| `dS )	z/Clear the state of the gradient boosting model.ri   )r   r   )rY   r;   r7   r   _rngN)	hasattrrc   r   r   ri   r;   r7   r   r   )r!   r"   r"   r#   _clear_state|  s    




z!BaseGradientBoosting._clear_statec             C   s   | j }|| jjd k r,td|| jd f t| j|| jjf| _t| j|| _| j	dk sht
| drt
| drt| j|| _ntj|ftjd| _dS )z:Add additional ``n_estimators`` entries to all attributes.r   z(resize with smaller n_estimators %d < %dr   r7   )rY   N)r8   ri   shaperz   rc   resizer_   rb   r;   r&   r   r7   r   re   )r!   Ztotal_n_estimatorsr"   r"   r#   _resize_state  s    
z"BaseGradientBoosting._resize_statec             C   s   t t| dg dkS )Nri   r   )r)   getattr)r!   r"   r"   r#   _is_initialized  s    z$BaseGradientBoosting._is_initializedc             C   s   t |  dS )zACheck that the estimator is initialized, raising an error if not.N)r   )r!   r"   r"   r#   _check_initialized  s    z'BaseGradientBoosting._check_initializedc             C   s   d S )Nr"   )r!   r"   r"   r#   _warn_mae_for_criterion  s    z,BaseGradientBoosting._warn_mae_for_criterionc             C   s  | j dkr|   | j dkr(tdt | js6|   | j||dddgtdd\}}|d	k}t	||}t
|dd
}t| r| ||}n
| |}| jd	k	rt| r|nd	}t|||| j| j|d\}}}}}}	t| r| jt|jd krtdnd	 } }}	|   |  s|   | jdkrJtj|jd | jjftjd}
n|r`| j|| nd| jj j!}y| jj|||d W nl t"k
r } zt||W d	d	}~X Y n@ tk
r } z dt#|krt||n W d	d	}~X Y nX | j$|| j}
d}t%| j| _&n\| j'| j(jd k rDtd| j'| j(jd f | j(jd }t)|tddd}| *|}
| +  | ,|||
|| j&|||	||
}|| j(jd kr| j(d	| | _(| j-d	| | _-t.| dr| j/d	| | _/|| _0| S )aO  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
            snapshoting.

        Returns
        -------
        self : object
            Fitted estimator.
        )absolute_errorZmaeZmsezCriterion 'mse' was deprecated in v1.0 and will be removed in version 1.2. Use `criterion='squared_error'` which is equivalent.csrZcscZcooT)accept_sparserY   Zmulti_outputN)r}   )rU   Z	test_sizestratifyr   zhThe training data after the early stopping split is missing some classes. Try using another random seed.rv   )r   rY   z9The initial estimator {} does not support sample weights.)rW   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C)rY   orderr   r7   )1rM   r   r|   r}   r~   rG   r   _validate_datar   r   r   r
   rX   rI   r   rU   rH   
_n_classesrc   uniquer   rz   r   r   r   r   r   r_   rb   re   rg   r:   	__class__r@   	TypeErrorr   get_init_raw_predictionsr   r   r8   ri   r   _raw_predictr   _fit_stagesr;   r   r7   Zn_estimators_)r!   rj   rV   rW   monitorZsample_weight_is_noner   X_valy_valsample_weight_valrk   msger/   Zn_stagesr"   r"   r#   rg     s    $






zBaseGradientBoosting.fitc             C   s  |j d }| jdk }tj|ftd}tdt| j| }| j}| jr\t	| jd}|
| |	 t|rlt|nd}t|rt|nd}| jdk	rt| jtj}| j|dd}|	}x:t|	| jD ](}|rt|||}|||  ||  ||  }| |||||||||	}|r\||| || || | j|< ||||  ||  ||   | j|< n||||| j|< | jdkr|||  |
dk	r|
|| t }|rP | jdk	r||t||}t|| j |k r|||t| < qP qW |d 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   g      ?)rY   r   )r    NF)r\   )r   r&   rc   Zonesr]   r   r   r_   r    r   r1   r   r   r   rI   fullinf_staged_raw_predictra   r8   r   rp   r;   r7   r?   localsnextanyrJ   r)   )r!   rj   rV   rk   rW   rU   r   r   r   r/   r   Z	n_samplesr=   rl   Zn_inbagr_   Zverbose_reporterrm   rn   Zloss_historyZy_val_pred_iterr>   Zold_oob_scoreZearly_stoppingZvalidation_lossr"   r"   r#   r   a  sj    




z BaseGradientBoosting._fit_stagesTc             C   s
   t  d S )N)NotImplementedError)r!   r'   r"   r"   r#   _make_estimator  s    z$BaseGradientBoosting._make_estimatorc             C   sb   |    | jd j|dd}| jdkrFtj|jd | jjftj	d}n| j
|| jtj	}|S )z>Check input and compute raw predictions of the init estimator.)r   r   T)r\   rv   r   )r   rY   )r   ri   _validate_X_predictr   rc   r   r   r_   rb   re   r   rf   )r!   rj   rk   r"   r"   r#   _raw_predict_init  s    
z&BaseGradientBoosting._raw_predict_initc             C   s    |  |}t| j|| j| |S )z?Return the sum of the trees raw predictions (+ init estimator).)r   r   ri   rK   )r!   rj   rk   r"   r"   r#   r     s    
z!BaseGradientBoosting._raw_predictc             c   s^   |r| j |tdddd}| |}x6t| jjd D ]"}t| j||| j| | V  q4W dS )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)rY   r   r   resetr   N)	r   r   r   ra   ri   r   r   rK   r`   )r!   rj   r\   rk   r>   r"   r"   r#   r     s    
z(BaseGradientBoosting._staged_raw_predictc             C   s\   |    dd | jD }|s.tj| jtjdS dd |D }tj|dtjd}|t| S )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.
        c             S   s&   g | ]}|D ]}|j jd kr|qqS )r   )rh   Z
node_count).0stagero   r"   r"   r#   
<listcomp>  s   z=BaseGradientBoosting.feature_importances_.<locals>.<listcomp>)r   rY   c             S   s   g | ]}|j jd dqS )F)	normalize)rh   Zcompute_feature_importances)r   ro   r"   r"   r#   r   %  s   r   )axisrY   )r   ri   rc   r   r   re   Zmeansum)r!   Zrelevant_treesZrelevant_feature_importancesZavg_feature_importancesr"   r"   r#   feature_importances_  s    
z)BaseGradientBoosting.feature_importances_c       	      C   s   | j dk	rtd| j  t tj|tdd}| jj\}}tj	||jd ftj
dd}xDt|D ]8}x2t|D ]&}| j||f j}|||||  qlW q^W || j9 }|S )aj  Fast partial dependence computation.

        Parameters
        ----------
        grid : ndarray of shape (n_samples, n_target_features)
            The grid points on which the partial dependence should be
            evaluated.
        target_features : ndarray of shape (n_target_features,)
            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.
        NzxUsing recursion method with a non-constant init predictor will lead to incorrect partial dependence values. Got init=%s.r   )rY   r   r   )r1   r|   r}   UserWarningrc   Zasarrayr   ri   r   r   re   ra   rh   Zcompute_partial_dependencerK   )	r!   gridZtarget_featuresr8   Zn_trees_per_stageZaveraged_predictionsr   rZ   ro   r"   r"   r#   %_compute_partial_dependence_recursion-  s     

z:BaseGradientBoosting._compute_partial_dependence_recursionc             C   s   |    | jd j|dd}| jj\}}t|jd ||f}xLt|D ]@}x:t|D ].}| j||f }|j|dd|dd||f< qVW qHW |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   r   T)r\   r   FN)r   ri   r   r   rc   r   ra   apply)r!   rj   r8   Z	n_classesleavesr>   r<   Z	estimatorr"   r"   r#   r   V  s    $zBaseGradientBoosting.applyzoAttribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead.c             C   s   | j S )N)r   )r!   r"   r"   r#   n_features_{  s    z BaseGradientBoosting.n_features_)N)NN)NN)r   N)T)T)r@   rA   rB   rC   r   r$   rX   rp   r   r   r   r   r   r   r   rg   r   r   r   r   r   propertyr   r   r   r   r   r"   r"   r"   r#   rD      sD    
>e
 ? 
_

!))%rD   )	metaclassc                   s   e Zd ZdZdZddddddd	d
dd
dddddddddd
d fdd
Zdd Zdd Zdd Zdd Z	dd Z
dd Zdd  Zd!d" Zd#d$ Z  ZS )%GradientBoostingClassifierat5  Gradient Boosting for classification.

    GB 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
    binomial or multinomial deviance loss function. Binary classification
    is a special case where only a single regression tree is induced.

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

    Parameters
    ----------
    loss : {'deviance', 'exponential'}, default='deviance'
        The loss function to be optimized. 'deviance' refers to
        deviance (= logistic regression) 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.

    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.

    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.

    criterion : {'friedman_mse', 'squared_error', 'mse', 'mae'},             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, and 'mae'
        for the mean absolute error. The default value of 'friedman_mse' is
        generally the best as it can provide a better approximation in some
        cases.

        .. versionadded:: 0.18

        .. deprecated:: 0.24
            `criterion='mae'` is deprecated and will be removed in version
            1.1 (renaming of 0.26). Use `criterion='friedman_mse'` or
            `'squared_error'` instead, as trees should use a squared error
            criterion in Gradient Boosting.

        .. deprecated:: 1.0
            Criterion 'mse' was deprecated in v1.0 and will be removed in
            version 1.2. Use `criterion='squared_error'` which is equivalent.

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

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

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

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

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

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

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

    max_depth : int, default=3
        The 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.

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

        The weighted impurity decrease equation is the following::

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

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

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

        .. versionadded:: 0.19

    init : estimator or 'zero', default=None
        An estimator object that is used to compute the initial predictions.
        ``init`` has to provide :meth:`fit` and :meth:`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 : {'auto', 'sqrt', 'log2'}, int or float, default=None
        The number of features to consider when looking for the best split:

        - If int, then consider `max_features` features at each split.
        - If float, then `max_features` is a fraction and
          `int(max_features * n_features)` features are considered at each
          split.
        - If 'auto', then `max_features=sqrt(n_features)`.
        - 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.

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

    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. Must be between 0 and 1.
        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.

        .. 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.

        .. 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. See
        :ref:`minimal_cost_complexity_pruning` for details.

        .. 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

    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 (= deviance) 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``

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

    loss_ : LossFunction
        The concrete ``LossFunction`` object.

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

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

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

    n_features_ : int
        The number of data features.

        .. deprecated:: 1.0
            Attribute `n_features_` was deprecated in version 1.0 and will be
            removed in 1.2. Use `n_features_in_` instead.

    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...
    )rs   Zexponentialrs   g?d   g      ?friedman_mser   r   g           Nr   Fg-C6?)rL   rK   r8   r&   rM   rN   rO   rP   rR   rS   r1   rU   rQ   r    rF   rG   rH   rI   rJ   rT   c               s8   t  j||||||||	|||||||
|||||d d S )N)rL   rK   r8   rM   rN   rO   rP   rR   r1   r&   rQ   rU   r    rF   rS   rG   rH   rI   rJ   rT   )superr$   )r!   rL   rK   r8   r&   rM   rN   rO   rP   rR   rS   r1   rU   rQ   r    rF   rG   rH   rI   rJ   rT   )r   r"   r#   r$     s*    z#GradientBoostingClassifier.__init__c             C   sZ   t | tj|dd\| _}tt||}|dk rBtd| t| j| _| j| _	|S )NT)Zreturn_inverser   zuy contains %d class after sample_weight trimmed classes with zero weights, while a minimum of 2 classes are required.)
r   rc   r   r   Zcount_nonzeroZbincountrz   r)   r   r   )r!   rV   rW   Zn_trim_classesr"   r"   r#   rX     s    z&GradientBoostingClassifier._validate_yc             C   s   t dt d S )Nzcriterion='mae' was deprecated in version 0.24 and will be removed in version 1.1 (renaming of 0.26). Use criterion='friedman_mse' or 'squared_error' instead, as trees should use a squared error criterion in Gradient Boosting.)r|   r}   r~   )r!   r"   r"   r#   r     s    z2GradientBoostingClassifier._warn_mae_for_criterionc             C   s8   | j |tdddd}| |}|jd dkr4| 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   F)rY   r   r   r   r   )r   r   r   r   ravel)r!   rj   rk   r"   r"   r#   decision_function  s    
z,GradientBoostingClassifier.decision_functionc             c   s   |  |E dH  dS )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!   rj   r"   r"   r#   staged_decision_function(  s    z3GradientBoostingClassifier.staged_decision_functionc             C   s&   |  |}| j|}| jj|dd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_   _raw_prediction_to_decisionr   take)r!   rj   rk   encoded_labelsr"   r"   r#   predict@  s    
z"GradientBoostingClassifier.predictc             c   s6   x0|  |D ]"}| j|}| jj|ddV  qW dS )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   N)r   r_   r   r   r   )r!   rj   rk   r   r"   r"   r#   staged_predictS  s    z)GradientBoostingClassifier.staged_predictc          
   C   sb   |  |}y| j|S  tk
r,    Y n2 tk
r\ } ztd| j |W dd}~X Y nX d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.
        z&loss=%r does not support predict_probaN)r   r_   _raw_prediction_to_probar   AttributeErrorrL   )r!   rj   rk   r   r"   r"   r#   predict_probai  s    

z(GradientBoostingClassifier.predict_probac             C   s   |  |}t|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.
        )r   rc   log)r!   rj   Zprobar"   r"   r#   predict_log_proba  s    
z,GradientBoostingClassifier.predict_log_probac          
   c   sr   y&x |  |D ]}| j|V  qW W nF tk
r<    Y n2 tk
rl } ztd| j |W dd}~X Y nX dS )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_   r   r   r   rL   )r!   rj   rk   r   r"   r"   r#   staged_predict_proba  s    
z/GradientBoostingClassifier.staged_predict_proba)r@   rA   rB   rC   r{   r$   rX   r   r   r   r   r   r   r   r   __classcell__r"   r"   )r   r#   r     sB     =r   c                   s   e Zd ZdZdZddddddd	d
dd
ddddddddddd
d fdd
Zd!ddZdd Zdd Zdd Z	 fddZ
ededd  Z  ZS )"GradientBoostingRegressorai5  Gradient Boosting for regression.

    GB 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.

    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).

        .. deprecated:: 1.0
            The loss 'ls' was deprecated in v1.0 and will be removed in
            version 1.2. Use `loss='squared_error'` which is equivalent.

        .. deprecated:: 1.0
            The loss 'lad' was deprecated in v1.0 and will be removed in
            version 1.2. Use `loss='absolute_error'` which is equivalent.

    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.

    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.

    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.

    criterion : {'friedman_mse', 'squared_error', 'mse', 'mae'},             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, and "mae"
        for the mean absolute error. The default value of "friedman_mse" is
        generally the best as it can provide a better approximation in some
        cases.

        .. versionadded:: 0.18

        .. deprecated:: 0.24
            `criterion='mae'` is deprecated and will be removed in version
            1.1 (renaming of 0.26). The correct way of minimizing the absolute
            error is to use `loss='absolute_error'` instead.

        .. deprecated:: 1.0
            Criterion 'mse' was deprecated in v1.0 and will be removed in
            version 1.2. Use `criterion='squared_error'` which is equivalent.

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

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

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

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

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

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

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

    max_depth : int, 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.

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

        The weighted impurity decrease equation is the following::

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

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

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

        .. versionadded:: 0.19

    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 : {'auto', 'sqrt', 'log2'}, int or float, default=None
        The number of features to consider when looking for the best split:

        - If int, then consider `max_features` features at each split.
        - If float, then `max_features` is a fraction and
          `int(max_features * n_features)` features are considered at each
          split.
        - If "auto", then `max_features=n_features`.
        - 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'``.

    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.

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

    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. Must be between 0 and 1.
        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.

        .. 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.

        .. 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. See
        :ref:`minimal_cost_complexity_pruning` for details.

        .. versionadded:: 0.22

    Attributes
    ----------
    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 (= deviance) 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``

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

    loss_ : LossFunction
        The concrete ``LossFunction`` object.

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

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

    n_classes_ : int
        The number of classes, set to 1 for regressors.

        .. deprecated:: 0.24
            Attribute ``n_classes_`` was deprecated in version 0.24 and
            will be removed in 1.1 (renaming of 0.26).

    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_features_ : int
        The number of data features.

        .. deprecated:: 1.0
            Attribute `n_features_` was deprecated in version 1.0 and will be
            removed in 1.2. Use `n_features_in_` instead.

    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...
    )squared_errorrq   r   rr   rt   ru   r   g?r   g      ?r   r   r   g        r   Ng?r   Fg-C6?)rL   rK   r8   r&   rM   rN   rO   rP   rR   rS   r1   rU   rQ   rE   r    rF   rG   rH   rI   rJ   rT   c               s:   t  j||||||||	||||
|||||||||d d S )N)rL   rK   r8   rM   rN   rO   rP   rR   r1   r&   rQ   rS   rU   rE   r    rF   rG   rH   rI   rJ   rT   )r   r$   )r!   rL   rK   r8   r&   rM   rN   rO   rP   rR   rS   r1   rU   rQ   rE   r    rF   rG   rH   rI   rJ   rT   )r   r"   r#   r$     s,    z"GradientBoostingRegressor.__init__c             C   s   |j jdkr|t}|S )NO)rY   kindrf   r   )r!   rV   rW   r"   r"   r#   rX   7  s    
z%GradientBoostingRegressor._validate_yc             C   s   t dt d S )Nzcriterion='mae' was deprecated in version 0.24 and will be removed in version 1.1 (renaming of 0.26). The correct way of minimizing the absolute error is to use  loss='absolute_error' instead.)r|   r}   r~   )r!   r"   r"   r#   r   <  s    z1GradientBoostingRegressor._warn_mae_for_criterionc             C   s"   | j |tdddd}| | 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   F)rY   r   r   r   )r   r   r   r   )r!   rj   r"   r"   r#   r   F  s    z!GradientBoostingRegressor.predictc             c   s"   x|  |D ]}| V  qW dS )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   )r!   rj   rk   r"   r"   r#   r   [  s    z(GradientBoostingRegressor.staged_predictc                s*   t  |}||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   r   Zreshaper   ri   )r!   rj   r   )r   r"   r#   r   p  s    zGradientBoostingRegressor.applyzdAttribute `n_classes_` was deprecated in version 0.24 and will be removed in 1.1 (renaming of 0.26).c          
   C   sH   yt |  W n6 tk
rB } ztd| jj|W d d }~X Y nX dS )Nz&{} object has no n_classes_ attribute.r   )r   r   r   r:   r   r@   )r!   Znfer"   r"   r#   r     s    z$GradientBoostingRegressor.n_classes_)N)r@   rA   rB   rC   r{   r$   rX   r   r   r   r   r   r   r   r   r"   r"   )r   r#   r     sB     >

r   )1rC   abcr   r   r|   _baser   baser   r   r	   r
   utilsr   Z_gradient_boostingr   r   r   r   numpyrc   Zscipy.sparser   r   r   r   Zmodel_selectionr   ro   r   Z
tree._treer   r    r   r   r   r   Zutils.validationr   r   Zutils.multiclassr   
exceptionsr   r   rD   r   r   r"   r"   r"   r#   <module>   sT   O           =