Untitled diff

Creato Il diff non scade mai
2 rimozioni
706 linee
4 aggiunte
708 linee
"""Gradient Boosted Regression Trees
"""Gradient Boosted Regression Trees


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


The module structure is the following:
The module structure is the following:


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


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


- ``GradientBoostingRegressor`` implements gradient boosting for
- ``GradientBoostingRegressor`` implements gradient boosting for
regression problems.
regression problems.
"""
"""


# Authors: Peter Prettenhofer, Scott White, Gilles Louppe, Emanuele Olivetti,
# Authors: Peter Prettenhofer, Scott White, Gilles Louppe, Emanuele Olivetti,
# Arnaud Joly, Jacob Schreiber
# Arnaud Joly, Jacob Schreiber
# License: BSD 3 clause
# License: BSD 3 clause


from __future__ import print_function
from __future__ import print_function
from __future__ import division
from __future__ import division


from abc import ABCMeta
from abc import ABCMeta
from abc import abstractmethod
from abc import abstractmethod


from .base import BaseEnsemble
from .base import BaseEnsemble
from ..base import BaseEstimator
from ..base import BaseEstimator
from ..base import ClassifierMixin
from ..base import ClassifierMixin
from ..base import RegressorMixin
from ..base import RegressorMixin
from ..externals import six
from ..externals import six
from ..feature_selection.from_model import _LearntSelectorMixin
from ..feature_selection.from_model import _LearntSelectorMixin


from ._gradient_boosting import predict_stages
from ._gradient_boosting import predict_stages
from ._gradient_boosting import predict_stage
from ._gradient_boosting import predict_stage
from ._gradient_boosting import _random_sample_mask
from ._gradient_boosting import _random_sample_mask


import numbers
import numbers
import numpy as np
import numpy as np


from scipy import stats
from scipy import stats
from scipy.sparse import csc_matrix
from scipy.sparse import csc_matrix
from scipy.sparse import csr_matrix
from scipy.sparse import csr_matrix
from scipy.sparse import issparse
from scipy.sparse import issparse


from time import time
from time import time
from ..tree.tree import DecisionTreeRegressor
from ..tree.tree import DecisionTreeRegressor
from ..tree.tree import BaseDecisionTree
from ..tree._tree import DTYPE
from ..tree._tree import DTYPE
from ..tree._tree import TREE_LEAF
from ..tree._tree import TREE_LEAF


from .forest import BaseForest

from ..utils import check_random_state
from ..utils import check_random_state
from ..utils import check_array
from ..utils import check_array
from ..utils import check_X_y
from ..utils import check_X_y
from ..utils import column_or_1d
from ..utils import column_or_1d
from ..utils import check_consistent_length
from ..utils import check_consistent_length
from ..utils import deprecated
from ..utils import deprecated
from ..utils.extmath import logsumexp
from ..utils.extmath import logsumexp
from ..utils.fixes import expit
from ..utils.fixes import expit
from ..utils.fixes import bincount
from ..utils.fixes import bincount
from ..utils.stats import _weighted_percentile
from ..utils.stats import _weighted_percentile
from ..utils.validation import check_is_fitted
from ..utils.validation import check_is_fitted
from ..utils.multiclass import check_classification_targets
from ..utils.multiclass import check_classification_targets
from ..exceptions import NotFittedError
from ..exceptions import NotFittedError




class QuantileEstimator(BaseEstimator):
class QuantileEstimator(BaseEstimator):
"""An estimator predicting the alpha-quantile of the training targets."""
"""An estimator predicting the alpha-quantile of the training targets."""
def __init__(self, alpha=0.9):
def __init__(self, alpha=0.9):
if not 0 < alpha < 1.0:
if not 0 < alpha < 1.0:
raise ValueError("`alpha` must be in (0, 1.0) but was %r" % alpha)
raise ValueError("`alpha` must be in (0, 1.0) but was %r" % alpha)
self.alpha = alpha
self.alpha = alpha


def fit(self, X, y, sample_weight=None):
def fit(self, X, y, sample_weight=None):
if sample_weight is None:
if sample_weight is None:
self.quantile = stats.scoreatpercentile(y, self.alpha * 100.0)
self.quantile = stats.scoreatpercentile(y, self.alpha * 100.0)
else:
else:
self.quantile = _weighted_percentile(y, sample_weight,
self.quantile = _weighted_percentile(y, sample_weight,
self.alpha * 100.0)
self.alpha * 100.0)


def predict(self, X):
def predict(self, X):
check_is_fitted(self, 'quantile')
check_is_fitted(self, 'quantile')


y = np.empty((X.shape[0], 1), dtype=np.float64)
y = np.empty((X.shape[0], 1), dtype=np.float64)
y.fill(self.quantile)
y.fill(self.quantile)
return y
return y




class MeanEstimator(BaseEstimator):
class MeanEstimator(BaseEstimator):
"""An estimator predicting the mean of the training targets."""
"""An estimator predicting the mean of the training targets."""
def fit(self, X, y, sample_weight=None):
def fit(self, X, y, sample_weight=None):
if sample_weight is None:
if sample_weight is None:
self.mean = np.mean(y)
self.mean = np.mean(y)
else:
else:
self.mean = np.average(y, weights=sample_weight)
self.mean = np.average(y, weights=sample_weight)


def predict(self, X):
def predict(self, X):
check_is_fitted(self, 'mean')
check_is_fitted(self, 'mean')


y = np.empty((X.shape[0], 1), dtype=np.float64)
y = np.empty((X.shape[0], 1), dtype=np.float64)
y.fill(self.mean)
y.fill(self.mean)
return y
return y




class LogOddsEstimator(BaseEstimator):
class LogOddsEstimator(BaseEstimator):
"""An estimator predicting the log odds ratio."""
"""An estimator predicting the log odds ratio."""
scale = 1.0
scale = 1.0


def fit(self, X, y, sample_weight=None):
def fit(self, X, y, sample_weight=None):
# pre-cond: pos, neg are encoded as 1, 0
# pre-cond: pos, neg are encoded as 1, 0
if sample_weight is None:
if sample_weight is None:
pos = np.sum(y)
pos = np.sum(y)
neg = y.shape[0] - pos
neg = y.shape[0] - pos
else:
else:
pos = np.sum(sample_weight * y)
pos = np.sum(sample_weight * y)
neg = np.sum(sample_weight * (1 - y))
neg = np.sum(sample_weight * (1 - y))


if neg == 0 or pos == 0:
if neg == 0 or pos == 0:
raise ValueError('y contains non binary labels.')
raise ValueError('y contains non binary labels.')
self.prior = self.scale * np.log(pos / neg)
self.prior = self.scale * np.log(pos / neg)


def predict(self, X):
def predict(self, X):
check_is_fitted(self, 'prior')
check_is_fitted(self, 'prior')


y = np.empty((X.shape[0], 1), dtype=np.float64)
y = np.empty((X.shape[0], 1), dtype=np.float64)
y.fill(self.prior)
y.fill(self.prior)
return y
return y




class ScaledLogOddsEstimator(LogOddsEstimator):
class ScaledLogOddsEstimator(LogOddsEstimator):
"""Log odds ratio scaled by 0.5 -- for exponential loss. """
"""Log odds ratio scaled by 0.5 -- for exponential loss. """
scale = 0.5
scale = 0.5




class PriorProbabilityEstimator(BaseEstimator):
class PriorProbabilityEstimator(BaseEstimator):
"""An estimator predicting the probability of each
"""An estimator predicting the probability of each
class in the training data.
class in the training data.
"""
"""
def fit(self, X, y, sample_weight=None):
def fit(self, X, y, sample_weight=None):
if sample_weight is None:
if sample_weight is None:
sample_weight = np.ones_like(y, dtype=np.float64)
sample_weight = np.ones_like(y, dtype=np.float64)
class_counts = bincount(y, weights=sample_weight)
class_counts = bincount(y, weights=sample_weight)
self.priors = class_counts / class_counts.sum()
self.priors = class_counts / class_counts.sum()


def predict(self, X):
def predict(self, X):
check_is_fitted(self, 'priors')
check_is_fitted(self, 'priors')


y = np.empty((X.shape[0], self.priors.shape[0]), dtype=np.float64)
y = np.empty((X.shape[0], self.priors.shape[0]), dtype=np.float64)
y[:] = self.priors
y[:] = self.priors
return y
return y




class ZeroEstimator(BaseEstimator):
class ZeroEstimator(BaseEstimator):
"""An estimator that simply predicts zero. """
"""An estimator that simply predicts zero. """


def fit(self, X, y, sample_weight=None):
def fit(self, X, y, sample_weight=None):
if np.issubdtype(y.dtype, int):
if np.issubdtype(y.dtype, int):
# classification
# classification
self.n_classes = np.unique(y).shape[0]
self.n_classes = np.unique(y).shape[0]
if self.n_classes == 2:
if self.n_classes == 2:
self.n_classes = 1
self.n_classes = 1
else:
else:
# regression
# regression
self.n_classes = 1
self.n_classes = 1


def predict(self, X):
def predict(self, X):
check_is_fitted(self, 'n_classes')
check_is_fitted(self, 'n_classes')


y = np.empty((X.shape[0], self.n_classes), dtype=np.float64)
y = np.empty((X.shape[0], self.n_classes), dtype=np.float64)
y.fill(0.0)
y.fill(0.0)
return y
return y




class LossFunction(six.with_metaclass(ABCMeta, object)):
class LossFunction(six.with_metaclass(ABCMeta, object)):
"""Abstract base class for various loss functions.
"""Abstract base class for various loss functions.


Attributes
Attributes
----------
----------
K : int
K : int
The number of regression trees to be induced;
The number of regression trees to be induced;
1 for regression and binary classification;
1 for regression and binary classification;
``n_classes`` for multi-class classification.
``n_classes`` for multi-class classification.
"""
"""


is_multi_class = False
is_multi_class = False


def __init__(self, n_classes):
def __init__(self, n_classes):
self.K = n_classes
self.K = n_classes


def init_estimator(self):
def init_estimator(self):
"""Default ``init`` estimator for loss function. """
"""Default ``init`` estimator for loss function. """
raise NotImplementedError()
raise NotImplementedError()


@abstractmethod
@abstractmethod
def __call__(self, y, pred, sample_weight=None):
def __call__(self, y, pred, sample_weight=None):
"""Compute the loss of prediction ``pred`` and ``y``. """
"""Compute the loss of prediction ``pred`` and ``y``. """


@abstractmethod
@abstractmethod
def negative_gradient(self, y, y_pred, **kargs):
def negative_gradient(self, y, y_pred, **kargs):
"""Compute the negative gradient.
"""Compute the negative gradient.


Parameters
Parameters
---------
---------
y : np.ndarray, shape=(n,)
y : np.ndarray, shape=(n,)
The target labels.
The target labels.
y_pred : np.ndarray, shape=(n,):
y_pred : np.ndarray, shape=(n,):
The predictions.
The predictions.
"""
"""


def update_terminal_regions(self, tree, X, y, residual, y_pred,
def update_terminal_regions(self, tree, X, y, residual, y_pred,
sample_weight, sample_mask,
sample_weight, sample_mask,
learning_rate=1.0, k=0):
learning_rate=1.0, k=0):
"""Update the terminal regions (=leaves) of the given tree and
"""Update the terminal regions (=leaves) of the given tree and
updates the current predictions of the model. Traverses tree
updates the current predictions of the model. Traverses tree
and invokes template method `_update_terminal_region`.
and invokes template method `_update_terminal_region`.


Parameters
Parameters
----------
----------
tree : tree.Tree
tree : tree.Tree
The tree object.
The tree object.
X : ndarray, shape=(n, m)
X : ndarray, shape=(n, m)
The data array.
The data array.
y : ndarray, shape=(n,)
y : ndarray, shape=(n,)
The target labels.
The target labels.
residual : ndarray, shape=(n,)
residual : ndarray, shape=(n,)
The residuals (usually the negative gradient).
The residuals (usually the negative gradient).
y_pred : ndarray, shape=(n,)
y_pred : ndarray, shape=(n,)
The predictions.
The predictions.
sample_weight : ndarray, shape=(n,)
sample_weight : ndarray, shape=(n,)
The weight of each sample.
The weight of each sample.
sample_mask : ndarray, shape=(n,)
sample_mask : ndarray, shape=(n,)
The sample mask to be used.
The sample mask to be used.
learning_rate : float, default=0.1
learning_rate : float, default=0.1
learning rate shrinks the contribution of each tree by
learning rate shrinks the contribution of each tree by
``learning_rate``.
``learning_rate``.
k : int, default 0
k : int, default 0
The index of the estimator being updated.
The index of the estimator being updated.


"""
"""
# compute leaf for each sample in ``X``.
# compute leaf for each sample in ``X``.
terminal_regions = tree.apply(X)
terminal_regions = tree.apply(X)


# mask all which are not in sample mask.
# mask all which are not in sample mask.
masked_terminal_regions = terminal_regions.copy()
masked_terminal_regions = terminal_regions.copy()
masked_terminal_regions[~sample_mask] = -1
masked_terminal_regions[~sample_mask] = -1


# update each leaf (= perform line search)
# update each leaf (= perform line search)
for leaf in np.where(tree.children_left == TREE_LEAF)[0]:
for leaf in np.where(tree.children_left == TREE_LEAF)[0]:
self._update_terminal_region(tree, masked_terminal_regions,
self._update_terminal_region(tree, masked_terminal_regions,
leaf, X, y, residual,
leaf, X, y, residual,
y_pred[:, k], sample_weight)
y_pred[:, k], sample_weight)


# update predictions (both in-bag and out-of-bag)
# update predictions (both in-bag and out-of-bag)
y_pred[:, k] += (learning_rate
y_pred[:, k] += (learning_rate
* tree.value[:, 0, 0].take(terminal_regions, axis=0))
* tree.value[:, 0, 0].take(terminal_regions, axis=0))


@abstractmethod
@abstractmethod
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
residual, pred, sample_weight):
"""Template method for updating terminal regions (=leaves). """
"""Template method for updating terminal regions (=leaves). """




class RegressionLossFunction(six.with_metaclass(ABCMeta, LossFunction)):
class RegressionLossFunction(six.with_metaclass(ABCMeta, LossFunction)):
"""Base class for regression loss functions. """
"""Base class for regression loss functions. """


def __init__(self, n_classes):
def __init__(self, n_classes):
if n_classes != 1:
if n_classes != 1:
raise ValueError("``n_classes`` must be 1 for regression but "
raise ValueError("``n_classes`` must be 1 for regression but "
"was %r" % n_classes)
"was %r" % n_classes)
super(RegressionLossFunction, self).__init__(n_classes)
super(RegressionLossFunction, self).__init__(n_classes)




class LeastSquaresError(RegressionLossFunction):
class LeastSquaresError(RegressionLossFunction):
"""Loss function for least squares (LS) estimation.
"""Loss function for least squares (LS) estimation.
Terminal regions need not to be updated for least squares. """
Terminal regions need not to be updated for least squares. """
def init_estimator(self):
def init_estimator(self):
return MeanEstimator()
return MeanEstimator()


def __call__(self, y, pred, sample_weight=None):
def __call__(self, y, pred, sample_weight=None):
if sample_weight is None:
if sample_weight is None:
return np.mean((y - pred.ravel()) ** 2.0)
return np.mean((y - pred.ravel()) ** 2.0)
else:
else:
return (1.0 / sample_weight.sum() *
return (1.0 / sample_weight.sum() *
np.sum(sample_weight * ((y - pred.ravel()) ** 2.0)))
np.sum(sample_weight * ((y - pred.ravel()) ** 2.0)))


def negative_gradient(self, y, pred, **kargs):
def negative_gradient(self, y, pred, **kargs):
return y - pred.ravel()
return y - pred.ravel()


def update_terminal_regions(self, tree, X, y, residual, y_pred,
def update_terminal_regions(self, tree, X, y, residual, y_pred,
sample_weight, sample_mask,
sample_weight, sample_mask,
learning_rate=1.0, k=0):
learning_rate=1.0, k=0):
"""Least squares does not need to update terminal regions.
"""Least squares does not need to update terminal regions.


But it has to update the predictions.
But it has to update the predictions.
"""
"""
# update predictions
# update predictions
y_pred[:, k] += learning_rate * tree.predict(X).ravel()
y_pred[:, k] += learning_rate * tree.predict(X).ravel()


def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
residual, pred, sample_weight):
pass
pass




class LeastAbsoluteError(RegressionLossFunction):
class LeastAbsoluteError(RegressionLossFunction):
"""Loss function for least absolute deviation (LAD) regression. """
"""Loss function for least absolute deviation (LAD) regression. """
def init_estimator(self):
def init_estimator(self):
return QuantileEstimator(alpha=0.5)
return QuantileEstimator(alpha=0.5)


def __call__(self, y, pred, sample_weight=None):
def __call__(self, y, pred, sample_weight=None):
if sample_weight is None:
if sample_weight is None:
return np.abs(y - pred.ravel()).mean()
return np.abs(y - pred.ravel()).mean()
else:
else:
return (1.0 / sample_weight.sum() *
return (1.0 / sample_weight.sum() *
np.sum(sample_weight * np.abs(y - pred.ravel())))
np.sum(sample_weight * np.abs(y - pred.ravel())))


def negative_gradient(self, y, pred, **kargs):
def negative_gradient(self, y, pred, **kargs):
"""1.0 if y - pred > 0.0 else -1.0"""
"""1.0 if y - pred > 0.0 else -1.0"""
pred = pred.ravel()
pred = pred.ravel()
return 2.0 * (y - pred > 0.0) - 1.0
return 2.0 * (y - pred > 0.0) - 1.0


def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
residual, pred, sample_weight):
"""LAD updates terminal regions to median estimates. """
"""LAD updates terminal regions to median estimates. """
terminal_region = np.where(terminal_regions == leaf)[0]
terminal_region = np.where(terminal_regions == leaf)[0]
sample_weight = sample_weight.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)
diff = y.take(terminal_region, axis=0) - pred.take(terminal_region, axis=0)
diff = y.take(terminal_region, axis=0) - pred.take(terminal_region, axis=0)
tree.value[leaf, 0, 0] = _weighted_percentile(diff, sample_weight, percentile=50)
tree.value[leaf, 0, 0] = _weighted_percentile(diff, sample_weight, percentile=50)




class HuberLossFunction(RegressionLossFunction):
class HuberLossFunction(RegressionLossFunction):
"""Huber loss function for robust regression.
"""Huber loss function for robust regression.


M-Regression proposed in Friedman 2001.
M-Regression proposed in Friedman 2001.


References
References
----------
----------
J. Friedman, Greedy Function Approximation: A Gradient Boosting
J. Friedman, Greedy Function Approximation: A Gradient Boosting
Machine, The Annals of Statistics, Vol. 29, No. 5, 2001.
Machine, The Annals of Statistics, Vol. 29, No. 5, 2001.
"""
"""


def __init__(self, n_classes, alpha=0.9):
def __init__(self, n_classes, alpha=0.9):
super(HuberLossFunction, self).__init__(n_classes)
super(HuberLossFunction, self).__init__(n_classes)
self.alpha = alpha
self.alpha = alpha
self.gamma = None
self.gamma = None


def init_estimator(self):
def init_estimator(self):
return QuantileEstimator(alpha=0.5)
return QuantileEstimator(alpha=0.5)


def __call__(self, y, pred, sample_weight=None):
def __call__(self, y, pred, sample_weight=None):
pred = pred.ravel()
pred = pred.ravel()
diff = y - pred
diff = y - pred
gamma = self.gamma
gamma = self.gamma
if gamma is None:
if gamma is None:
if sample_weight is None:
if sample_weight is None:
gamma = stats.scoreatpercentile(np.abs(diff), self.alpha * 100)
gamma = stats.scoreatpercentile(np.abs(diff), self.alpha * 100)
else:
else:
gamma = _weighted_percentile(np.abs(diff), sample_weight, self.alpha * 100)
gamma = _weighted_percentile(np.abs(diff), sample_weight, self.alpha * 100)


gamma_mask = np.abs(diff) <= gamma
gamma_mask = np.abs(diff) <= gamma
if sample_weight is None:
if sample_weight is None:
sq_loss = np.sum(0.5 * diff[gamma_mask] ** 2.0)
sq_loss = np.sum(0.5 * diff[gamma_mask] ** 2.0)
lin_loss = np.sum(gamma * (np.abs(diff[~gamma_mask]) - gamma / 2.0))
lin_loss = np.sum(gamma * (np.abs(diff[~gamma_mask]) - gamma / 2.0))
loss = (sq_loss + lin_loss) / y.shape[0]
loss = (sq_loss + lin_loss) / y.shape[0]
else:
else:
sq_loss = np.sum(0.5 * sample_weight[gamma_mask] * diff[gamma_mask] ** 2.0)
sq_loss = np.sum(0.5 * sample_weight[gamma_mask] * diff[gamma_mask] ** 2.0)
lin_loss = np.sum(gamma * sample_weight[~gamma_mask] *
lin_loss = np.sum(gamma * sample_weight[~gamma_mask] *
(np.abs(diff[~gamma_mask]) - gamma / 2.0))
(np.abs(diff[~gamma_mask]) - gamma / 2.0))
loss = (sq_loss + lin_loss) / sample_weight.sum()
loss = (sq_loss + lin_loss) / sample_weight.sum()
return loss
return loss


def negative_gradient(self, y, pred, sample_weight=None, **kargs):
def negative_gradient(self, y, pred, sample_weight=None, **kargs):
pred = pred.ravel()
pred = pred.ravel()
diff = y - pred
diff = y - pred
if sample_weight is None:
if sample_weight is None:
gamma = stats.scoreatpercentile(np.abs(diff), self.alpha * 100)
gamma = stats.scoreatpercentile(np.abs(diff), self.alpha * 100)
else:
else:
gamma = _weighted_percentile(np.abs(diff), sample_weight, self.alpha * 100)
gamma = _weighted_percentile(np.abs(diff), sample_weight, self.alpha * 100)
gamma_mask = np.abs(diff) <= gamma
gamma_mask = np.abs(diff) <= gamma
residual = np.zeros((y.shape[0],), dtype=np.float64)
residual = np.zeros((y.shape[0],), dtype=np.float64)
residual[gamma_mask] = diff[gamma_mask]
residual[gamma_mask] = diff[gamma_mask]
residual[~gamma_mask] = gamma * np.sign(diff[~gamma_mask])
residual[~gamma_mask] = gamma * np.sign(diff[~gamma_mask])
self.gamma = gamma
self.gamma = gamma
return residual
return residual


def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
residual, pred, sample_weight):
terminal_region = np.where(terminal_regions == leaf)[0]
terminal_region = np.where(terminal_regions == leaf)[0]
sample_weight = sample_weight.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)
gamma = self.gamma
gamma = self.gamma
diff = (y.take(terminal_region, axis=0)
diff = (y.take(terminal_region, axis=0)
- pred.take(terminal_region, axis=0))
- pred.take(terminal_region, axis=0))
median = _weighted_percentile(diff, sample_weight, percentile=50)
median = _weighted_percentile(diff, sample_weight, percentile=50)
diff_minus_median = diff - median
diff_minus_median = diff - median
tree.value[leaf, 0] = median + np.mean(
tree.value[leaf, 0] = median + np.mean(
np.sign(diff_minus_median) *
np.sign(diff_minus_median) *
np.minimum(np.abs(diff_minus_median), gamma))
np.minimum(np.abs(diff_minus_median), gamma))




class QuantileLossFunction(RegressionLossFunction):
class QuantileLossFunction(RegressionLossFunction):
"""Loss function for quantile regression.
"""Loss function for quantile regression.


Quantile regression allows to estimate the percentiles
Quantile regression allows to estimate the percentiles
of the conditional distribution of the target.
of the conditional distribution of the target.
"""
"""


def __init__(self, n_classes, alpha=0.9):
def __init__(self, n_classes, alpha=0.9):
super(QuantileLossFunction, self).__init__(n_classes)
super(QuantileLossFunction, self).__init__(n_classes)
assert 0 < alpha < 1.0
assert 0 < alpha < 1.0
self.alpha = alpha
self.alpha = alpha
self.percentile = alpha * 100.0
self.percentile = alpha * 100.0


def init_estimator(self):
def init_estimator(self):
return QuantileEstimator(self.alpha)
return QuantileEstimator(self.alpha)


def __call__(self, y, pred, sample_weight=None):
def __call__(self, y, pred, sample_weight=None):
pred = pred.ravel()
pred = pred.ravel()
diff = y - pred
diff = y - pred
alpha = self.alpha
alpha = self.alpha


mask = y > pred
mask = y > pred
if sample_weight is None:
if sample_weight is None:
loss = (alpha * diff[mask].sum() +
loss = (alpha * diff[mask].sum() +
(1.0 - alpha) * diff[~mask].sum()) / y.shape[0]
(1.0 - alpha) * diff[~mask].sum()) / y.shape[0]
else:
else:
loss = ((alpha * np.sum(sample_weight[mask] * diff[mask]) +
loss = ((alpha * np.sum(sample_weight[mask] * diff[mask]) +
(1.0 - alpha) * np.sum(sample_weight[~mask] * diff[~mask])) /
(1.0 - alpha) * np.sum(sample_weight[~mask] * diff[~mask])) /
sample_weight.sum())
sample_weight.sum())
return loss
return loss


def negative_gradient(self, y, pred, **kargs):
def negative_gradient(self, y, pred, **kargs):
alpha = self.alpha
alpha = self.alpha
pred = pred.ravel()
pred = pred.ravel()
mask = y > pred
mask = y > pred
return (alpha * mask) - ((1.0 - alpha) * ~mask)
return (alpha * mask) - ((1.0 - alpha) * ~mask)


def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
residual, pred, sample_weight):
terminal_region = np.where(terminal_regions == leaf)[0]
terminal_region = np.where(terminal_regions == leaf)[0]
diff = (y.take(terminal_region, axis=0)
diff = (y.take(terminal_region, axis=0)
- pred.take(terminal_region, axis=0))
- pred.take(terminal_region, axis=0))
sample_weight = sample_weight.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)


val = _weighted_percentile(diff, sample_weight, self.percentile)
val = _weighted_percentile(diff, sample_weight, self.percentile)
tree.value[leaf, 0] = val
tree.value[leaf, 0] = val




class ClassificationLossFunction(six.with_metaclass(ABCMeta, LossFunction)):
class ClassificationLossFunction(six.with_metaclass(ABCMeta, LossFunction)):
"""Base class for classification loss functions. """
"""Base class for classification loss functions. """


def _score_to_proba(self, score):
def _score_to_proba(self, score):
"""Template method to convert scores to probabilities.
"""Template method to convert scores to probabilities.


the does not support probabilites raises AttributeError.
the does not support probabilites raises AttributeError.
"""
"""
raise TypeError('%s does not support predict_proba' % type(self).__name__)
raise TypeError('%s does not support predict_proba' % type(self).__name__)


@abstractmethod
@abstractmethod
def _score_to_decision(self, score):
def _score_to_decision(self, score):
"""Template method to convert scores to decisions.
"""Template method to convert scores to decisions.


Returns int arrays.
Returns int arrays.
"""
"""




class BinomialDeviance(ClassificationLossFunction):
class BinomialDeviance(ClassificationLossFunction):
"""Binomial deviance loss function for binary classification.
"""Binomial deviance loss function for binary classification.


Binary classification is a special case; here, we only need to
Binary classification is a special case; here, we only need to
fit one tree instead of ``n_classes`` trees.
fit one tree instead of ``n_classes`` trees.
"""
"""
def __init__(self, n_classes):
def __init__(self, n_classes):
if n_classes != 2:
if n_classes != 2:
raise ValueError("{0:s} requires 2 classes.".format(
raise ValueError("{0:s} requires 2 classes.".format(
self.__class__.__name__))
self.__class__.__name__))
# we only need to fit one tree for binary clf.
# we only need to fit one tree for binary clf.
super(BinomialDeviance, self).__init__(1)
super(BinomialDeviance, self).__init__(1)


def init_estimator(self):
def init_estimator(self):
return LogOddsEstimator()
return LogOddsEstimator()


def __call__(self, y, pred, sample_weight=None):
def __call__(self, y, pred, sample_weight=None):
"""Compute the deviance (= 2 * negative log-likelihood). """
"""Compute the deviance (= 2 * negative log-likelihood). """
# logaddexp(0, v) == log(1.0 + exp(v))
# logaddexp(0, v) == log(1.0 + exp(v))
pred = pred.ravel()
pred = pred.ravel()
if sample_weight is None:
if sample_weight is None:
return -2.0 * np.mean((y * pred) - np.logaddexp(0.0, pred))
return -2.0 * np.mean((y * pred) - np.logaddexp(0.0, pred))
else:
else:
return (-2.0 / sample_weight.sum() *
return (-2.0 / sample_weight.sum() *
np.sum(sample_weight * ((y * pred) - np.logaddexp(0.0, pred))))
np.sum(sample_weight * ((y * pred) - np.logaddexp(0.0, pred))))


def negative_gradient(self, y, pred, **kargs):
def negative_gradient(self, y, pred, **kargs):
"""Compute the residual (= negative gradient). """
"""Compute the residual (= negative gradient). """
return y - expit(pred.ravel())
return y - expit(pred.ravel())


def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
residual, pred, sample_weight):
"""Make a single Newton-Raphson step.
"""Make a single Newton-Raphson step.


our node estimate is given by:
our node estimate is given by:


sum(w * (y - prob)) / sum(w * prob * (1 - prob))
sum(w * (y - prob)) / sum(w * prob * (1 - prob))


we take advantage that: y - prob = residual
we take advantage that: y - prob = residual
"""
"""
terminal_region = np.where(terminal_regions == leaf)[0]
terminal_region = np.where(terminal_regions == leaf)[0]
residual = residual.take(terminal_region, axis=0)
residual = residual.take(terminal_region, axis=0)
y = y.take(terminal_region, axis=0)
y = y.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)


numerator = np.sum(sample_weight * residual)
numerator = np.sum(sample_weight * residual)
denominator = np.sum(sample_weight * (y - residual) * (1 - y + residual))
denominator = np.sum(sample_weight * (y - residual) * (1 - y + residual))


if denominator == 0.0:
if denominator == 0.0:
tree.value[leaf, 0, 0] = 0.0
tree.value[leaf, 0, 0] = 0.0
else:
else:
tree.value[leaf, 0, 0] = numerator / denominator
tree.value[leaf, 0, 0] = numerator / denominator


def _score_to_proba(self, score):
def _score_to_proba(self, score):
proba = np.ones((score.shape[0], 2), dtype=np.float64)
proba = np.ones((score.shape[0], 2), dtype=np.float64)
proba[:, 1] = expit(score.ravel())
proba[:, 1] = expit(score.ravel())
proba[:, 0] -= proba[:, 1]
proba[:, 0] -= proba[:, 1]
return proba
return proba


def _score_to_decision(self, score):
def _score_to_decision(self, score):
proba = self._score_to_proba(score)
proba = self._score_to_proba(score)
return np.argmax(proba, axis=1)
return np.argmax(proba, axis=1)




class MultinomialDeviance(ClassificationLossFunction):
class MultinomialDeviance(ClassificationLossFunction):
"""Multinomial deviance loss function for multi-class classification.
"""Multinomial deviance loss function for multi-class classification.


For multi-class classification we need to fit ``n_classes`` trees at
For multi-class classification we need to fit ``n_classes`` trees at
each stage.
each stage.
"""
"""


is_multi_class = True
is_multi_class = True


def __init__(self, n_classes):
def __init__(self, n_classes):
if n_classes < 3:
if n_classes < 3:
raise ValueError("{0:s} requires more than 2 classes.".format(
raise ValueError("{0:s} requires more than 2 classes.".format(
self.__class__.__name__))
self.__class__.__name__))
super(MultinomialDeviance, self).__init__(n_classes)
super(MultinomialDeviance, self).__init__(n_classes)


def init_estimator(self):
def init_estimator(self):
return PriorProbabilityEstimator()
return PriorProbabilityEstimator()


def __call__(self, y, pred, sample_weight=None):
def __call__(self, y, pred, sample_weight=None):
# create one-hot label encoding
# create one-hot label encoding
Y = np.zeros((y.shape[0], self.K), dtype=np.float64)
Y = np.zeros((y.shape[0], self.K), dtype=np.float64)
for k in range(self.K):
for k in range(self.K):
Y[:, k] = y == k
Y[:, k] = y == k


if sample_weight is None:
if sample_weight is None:
return np.sum(-1 * (Y * pred).sum(axis=1) +
return np.sum(-1 * (Y * pred).sum(axis=1) +
logsumexp(pred, axis=1))
logsumexp(pred, axis=1))
else:
else:
return np.sum(-1 * sample_weight * (Y * pred).sum(axis=1) +
return np.sum(-1 * sample_weight * (Y * pred).sum(axis=1) +
logsumexp(pred, axis=1))
logsumexp(pred, axis=1))


def negative_gradient(self, y, pred, k=0, **kwargs):
def negative_gradient(self, y, pred, k=0, **kwargs):
"""Compute negative gradient for the ``k``-th class. """
"""Compute negative gradient for the ``k``-th class. """
return y - np.nan_to_num(np.exp(pred[:, k] -
return y - np.nan_to_num(np.exp(pred[:, k] -
logsumexp(pred, axis=1)))
logsumexp(pred, axis=1)))


def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
residual, pred, sample_weight):
"""Make a single Newton-Raphson step. """
"""Make a single Newton-Raphson step. """
terminal_region = np.where(terminal_regions == leaf)[0]
terminal_region = np.where(terminal_regions == leaf)[0]
residual = residual.take(terminal_region, axis=0)
residual = residual.take(terminal_region, axis=0)
y = y.take(terminal_region, axis=0)
y = y.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)


numerator = np.sum(sample_weight * residual)
numerator = np.sum(sample_weight * residual)
numerator *= (self.K - 1) / self.K
numerator *= (self.K - 1) / self.K


denominator = np.sum(sample_weight * (y - residual) *
denominator = np.sum(sample_weight * (y - residual) *
(1.0 - y + residual))
(1.0 - y + residual))


if denominator == 0.0:
if denominator == 0.0:
tree.value[leaf, 0, 0] = 0.0
tree.value[leaf, 0, 0] = 0.0
else:
else:
tree.value[leaf, 0, 0] = numerator / denominator
tree.value[leaf, 0, 0] = numerator / denominator


def _score_to_proba(self, score):
def _score_to_proba(self, score):
return np.nan_to_num(
return np.nan_to_num(
np.exp(score - (logsumexp(score, axis=1)[:, np.newaxis])))
np.exp(score - (logsumexp(score, axis=1)[:, np.newaxis])))


def _score_to_decision(self, score):
def _score_to_decision(self, score):
proba = self._score_to_proba(score)
proba = self._score_to_proba(score)
return np.argmax(proba, axis=1)
return np.argmax(proba, axis=1)




class ExponentialLoss(ClassificationLossFunction):
class ExponentialLoss(ClassificationLossFunction):
"""Exponential loss function for binary classification.
"""Exponential loss function for binary classification.


Same loss as AdaBoost.
Same loss as AdaBoost.


References
References
----------
----------
Greg Ridgeway, Generalized Boosted Models: A guide to the gbm package, 2007
Greg Ridgeway, Generalized Boosted Models: A guide to the gbm package, 2007
"""
"""
def __init__(self, n_classes):
def __init__(self, n_classes):
if n_classes != 2:
if n_classes != 2:
raise ValueError("{0:s} requires 2 classes.".format(
raise ValueError("{0:s} requires 2 classes.".format(
self.__class__.__name__))
self.__class__.__name__))
# we only need to fit one tree for binary clf.
# we only need to fit one tree for binary clf.
super(ExponentialLoss, self).__init__(1)
super(ExponentialLoss, self).__init__(1)


def init_estimator(self):
def init_estimator(self):
return ScaledLogOddsEstimator()
return ScaledLogOddsEstimator()


def __call__(self, y, pred, sample_weight=None):
def __call__(self, y, pred, sample_weight=None):
pred = pred.ravel()
pred = pred.ravel()
if sample_weight is None:
if sample_weight is None:
return np.mean(np.exp(-(2. * y - 1.) * pred))
return np.mean(np.exp(-(2. * y - 1.) * pred))
else:
else:
return (1.0 / sample_weight.sum() *
return (1.0 / sample_weight.sum() *
np.sum(sample_weight * np.exp(-(2 * y - 1) * pred)))
np.sum(sample_weight * np.exp(-(2 * y - 1) * pred)))


def negative_gradient(self, y, pred, **kargs):
def negative_gradient(self, y, pred, **kargs):
y_ = -(2. * y - 1.)
y_ = -(2. * y - 1.)
return y_ * np.exp(y_ * pred.ravel())
return y_ * np.exp(y_ * pred.ravel())


def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
residual, pred, sample_weight):
residual, pred, sample_weight):
terminal_region = np.where(terminal_regions == leaf)[0]
terminal_region = np.where(terminal_regions == leaf)[0]
pred = pred.take(terminal_region, axis=0)
pred = pred.take(terminal_region, axis=0)
y = y.take(terminal_region, axis=0)
y = y.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)
sample_weight = sample_weight.take(terminal_region, axis=0)


y_ = 2. * y - 1.
y_ = 2. * y - 1.


numerator = np.sum(y_ * sample_weight * np.exp(-y_ * pred))
numerator = np.sum(y_ * sample_weight * np.exp(-y_ * pred))
denominator = np.sum(sample_weight * np.exp(-y_ * pred))
denominator = np.sum(sample_weight * np.exp(-y_ * pred))


if denominator == 0.0:
if denominator == 0.0:
tree.value[leaf, 0, 0] = 0.0
tree.value[leaf, 0, 0] = 0.0
else:
else:
tree.value[leaf, 0, 0] = numerator / denominator
tree.value[leaf, 0, 0] = numerator / denominator


def _score_to_proba(self, score):
def _score_to_proba(self, score):
proba = np.ones((score.shape[0], 2), dtype=np.float64)
proba = np.ones((score.shape[0], 2), dtype=np.float64)
proba[:, 1] = expit(2.0 * score.ravel())
proba[:, 1] = expit(2.0 * score.ravel())
proba[:, 0] -= proba[:, 1]
proba[:, 0] -= proba[:, 1]
return proba
return proba


def _score_to_decision(self, score):
def _score_to_decision(self, score):
return (score.ravel() >= 0.0).astype(np.int)
return (score.ravel() >= 0.0).astype(np.int)




LOSS_FUNCTIONS = {'ls': LeastSquaresError,
LOSS_FUNCTIONS = {'ls': LeastSquaresError,
'lad': LeastAbsoluteError,
'lad': LeastAbsoluteError,
'huber': HuberLossFunction,
'huber': HuberLossFunction,
'quantile': QuantileLossFunction,
'quantile': QuantileLossFunction,
'deviance': None, # for both, multinomial and binomial
'deviance': None, # for both, multinomial and binomial
'exponential': ExponentialLoss,
'exponential': ExponentialLoss,
}
}




INIT_ESTIMATORS = {'zero': ZeroEstimator}
INIT_ESTIMATORS = {'zero': ZeroEstimator}




class VerboseReporter(object):
class VerboseReporter(object):
"""Reports verbose output to stdout.
"""Reports verbose output to stdout.


If ``verbose==1`` output is printed once in a while (when iteration mod
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
verbose_mod is zero).; if larger than 1 then output is printed for
each update.
each update.
"""
"""


def __init__(self, verbose):
def __init__(self, verbose):
self.verbose = verbose
self.verbose = verbose


def init(self, est, begin_at_stage=0):
def init(self, est, begin_at_stage=0):
# header fields and line format str
# header fields and line format str
header_fields = ['Iter', 'Train Loss']
header_fields = ['Iter', 'Train Loss']
verbose_fmt = ['{iter:>10d}', '{train_score:>16.4f}']
verbose_fmt = ['{iter:>10d}', '{train_score:>16.4f}']
# do oob?
# do oob?
if est.subsample < 1:
if est.subsample < 1:
header_fields.append('OOB Improve')
header_fields.append('OOB Improve')
verbose_fmt.append('{oob_impr:>16.4f}')
verbose_fmt.append('{oob_impr:>16.4f}')
header_fields.append('Remaining Time')
header_fields.append('Remaining Time')
verbose_fmt.append('{remaining_time:>16s}')
verbose_fmt.append('{remaining_time:>16s}')


# print the header line
# print the header line
print(('%10s ' + '%16s ' *
print(('%10s ' + '%16s ' *
(len(header_fields) - 1)) % tuple(header_fields))
(len(header_fields) - 1)) % tuple(header_fields))


self.verbose_fmt = ' '.join(verbose_fmt)
self.verbose_fmt = ' '.join(verbose_fmt)
# plot verbose info each time i % verbose_mod == 0
# plot verbose info each time i % verbose_mod == 0
self.verbose_mod = 1
self.verbose_mod = 1
self.start_time = time()
self.start_time = time()
self.begin_at_stage = begin_at_stage
self.begin_at_stage = begin_at_stage


def update(self, j, est):
def update(self, j, est):
"""Update reporter with new iteration. """
"""Update reporter with new iteration. """
do_oob = est.subsample < 1
do_oob = est.subsample < 1
# we need to take into account if we fit additional estimators.
# we need to take into account if we fit additional estimators.
i = j - self.begin_at_stage # iteration relative to the start iter
i = j - self.begin_at_stage # iteration relative to the start iter
if (i + 1) % self.verbose_mod == 0:
if (i + 1) % self.verbose_mod == 0:
oob_impr = est.oob_improvement_[j] if do_oob else 0
oob_impr = est.oob_improvement_[j] if do_oob else 0
remaining_time = ((est.n_estimators - (j + 1)) *
remaining_time = ((est.n_estimators - (j + 1)) *
(time() - self.start_time) / float(i + 1))
(time() - self.start_time) / float(i + 1))
if remaining_time > 60:
if r
remaining_time = '{0:.2f}m'.format(re