# How LightGBM implements quantile regression

- suppose we have IID data with ,
- we’re often interested in estimating some quantiles of the conditional distribution .
- as in, for some , we want to estimate this:

- all else being equal, we would prefer to more flexibly approximate with as opposed to e.g. putting restrictive assumptions (e.g. considering only linear functions).
- one way of doing this flexible approximation that work fairly well in practice is
**gradient tree boosting** - this method is quite popular for general function approximation purposes, and has some quite good implementations, one of which is LightGBM
- however, it turns out the naive implementation of quantile regression for gradient boosting has some issues
- we’ll:
- describe what gradient boosting is and why it’s the way it is
- discuss why quantile regression presents an issue for gradient boosting
- look into how LightGBM dealt with it, and why they dealt with it that way

### I. Background

#### Loss functions

Assume we have as in the intro, and that we want to estimate some statistic of the conditional distribution , call it . Often, there’s some loss function associated with this , so that minimizes the loss function over the true distribution:

For concreteness, two leading examples:

- If is , then we can pick and satisfy the above relation
- To see this, just note that is convex and take the first order condition.

- If is the quantile function defined in the \eqref{quantiledef}, then we can use
- This again follows by convexity of and first order condition
- For intuition, note that if is close to 1, then essentially only penalizes situtations where the real exceeds the prediction , so that the argmin should be close to the max value that can take, which corresponds to a quantile of close to 1.

So, if we want to find that approximates , a quite reasonable thing to do is to try to pick out of some class of functions to minimize the corresponding empirical average (or equivalently, the sum) of over our data:

#### Boosting

Alright, so let’s say we’re estimating by optimizing some empirical . We’ll typically want to do this estimation fairly flexibly, so we’ll want to be fairly complex (as opposed to e.g. considering only linear functions), but complex makes it harder to do the optimization. ‘Boosting’ is a general machine learning procedure that circumvents this issue by iteratively building up via a sum of ‘base learners’ ( = simple functions). This approach allows to be quite complex (as it’s a product of a bunch of simple function spaces), but at the cost of making the approximate:

Boosting heuristic:

- Define a space of base learners
- For , (for some ), choose some base learner that incrementally improves our loss, e.g.
- Use to approximate the true

So, boosting amounts to incrementally building up an estimate of by doing a bunch of small improvements. Note that the model space here for can be highly complex, as sums of a bunch of simple functions can be quite complicated. However, the process involved in getting each is still (by assumption) tractable.

#### Tree boosting

Typically in practice, the space of base learners is some set of binary tree with some constraint on the max depth or max number of nodes. Furthermore, the base learners are chosen by building the trees up greedily node-by-node, as opposed to globally optimized as in \eqref{baselearning0}, since doing that would be too computationally intensive.

Tree boosting:

- Define a space of base learners = all trees of a certain depth or node count
- For , (for some ), grow a tree by doing this:
- Start with a root node, and put all the data in this node. Let denote this set of observations in this node.
- Compute the optimal constant prediction
- Record corresponding value of the loss

- Split the data in the node into two more nodes via this process:
- For each dimension of of (recall that is -dimensional), and for each cutoff between the min and max values of (where denotes the th dimension of ):
- Use this to split the data along dimension into two sets and , where and constains the remaining observations
- Find , as we did for
- Compute the performance gain , which is a measure of how much improvement there was to our loss function when we split the data along dimension at value

- Find the optimal by maximizing the performance gain over all possible s.
- If the optimal gain exceeds some minimum threshold, and our tree doesn’t have too many nodes already, use this to split into and , thus adding two more nodes to our tree
- Otherwise, we’re done

- For each dimension of of (recall that is -dimensional), and for each cutoff between the min and max values of (where denotes the th dimension of ):
- Recursively apply the data-splitting process of step 2.2 to and
- Eventually, this process terminates
- The leaves of this resulting tree forms a partitions the domain of , and all data that falls within some a partition gets assigned some number computed during the tree building process
- This resulting piecewise constant function is

- Start with a root node, and put all the data in this node. Let denote this set of observations in this node.
- Use to approximate the true

The process of growing each tree amounts to repeated greedy splitting: first, see what our loss would be if we just had a constant predictor for everything in this node, and then compare it to the loss if we broke this node into two nodes and fit separate constants for each. This is greedy in the sense that it optimizes split selection without taking into account further-down-the-road splits that may occur.

Note that in order to determine the optimal splits, the algorithm tests every possible cutoff point of every possible dimension , and for each pair, computes the optimal constants and the corresponding losses for the two partitions of the data . Generically, computing the loss on a set of observations will require operations, as one would typically need to compute for each observation . So, if we assume that computing the optimal is also , the time complexity of of growing the entire tree would be , and thus the time complexity of all the splitting needed for the entire boosting procedure would be , where

- is the number of trees grown
- is max height of the tree
- is dimensionaly of = number of features
- is the number of cutoffs points to consider for each feature
- this amounts to discretizing each dimension of into distinct values
- e.g by default in LightGBM

- is number of observations

#### Gradient tree boosting

The fact that the splitting procedure 2.2 above appears to require re-computing the loss functions for every dimension of and for every potential cutoff point seems like it would somewhat limit the applicability of tree boosting, espcially for large data sets. **Probably the main innovation of gradient boosting as implemented in e.g. XGBoost/LightGBM/others is how to resolve this issue by using a second-order approximation of the loss function .** Certainly, the fact that these implementations run quite quickly is a major reason for their popularity.

Letting , for some set of observations we can write

From which it follows that the optimal choice for would be

and the corresponding approximate loss

which implies that the gain in splitting a set of observations into two parts, and would purely be a function of the first and second derivatives of and .

Note that this allows the algorithm to just take a single pass through the data for each dimension of , rather than having to do so for each (dimension, cutoff point) pair. Let be the dimension and the cutpoint, and let and . Suppose we’ve calculated the corresponding sum over hessians and gradients for observations in and (from which computing the and are ). Then, when we move onto the next-largest cutpoint , the corresponding will differ from only in a few additional points, and so that the first and second derivatives can be updated by simply adding the values of these new points. As the cutoff points go from smallest to biggest, extra observations are incrementally added to , so that only a single pass through the data is required for each dimension of .

So, given that this formulation of the problem allows a single pass through the data per dimension, as opposed to every (dimesion, cutoff) pair, the set of all the splitting needed for building trees becomes instead of the above. This is significant, as .

#### LightGBM’s implementation

This is implemented in LightGBM in the `FindBestThresholdSequence()`

function.

- see lines 565 onwards for the implementation described above
`sum_left_gradient`

,`sum_left_hessian`

refer to and- lines 585 onwards iterates through all the relevant cutoff points
- lines 589-593 performs the incremental updating of the
`sum_left_gradient`

and`sum_left_hessian`

- lines 595, 599, 603 are various regularizations that terminate the algorithm when there’s not enough data
- lines 601 and 605 compute the
`sum_right_gradient`

and`sum_right_hessian`

by just subtracting the corresponding left hessian/gradient from the total sum

`CalculateSplittedLeafOutput()`

computes the best constant prediction for a given set of observations, denoted by above, though there are differences due to some regularization that we didn’t discuss above- L1 regularization, which amounts to zeroing out too small
- L2 regularization, which amounts to increasing the hessian, which shrinks towards 0
`max_delta_step`

, which prevents the model from updating too quickly by limiting the max size of

`GetSplitGains()`

computes the split gain information, corresponding to above- this calls
`GetLeafSplitGainGivenOutput()`

in order to compute the left and right losses (which correspond to and above) - the implementation of
`GetLeafSplitGainGivenOutput()`

corresponds to \eqref{gbtloss} above, with adjustments for regularization- note that this function ignores the in \eqref{gbtloss}, because when computing the gain , this ends up being canceled out

- this calls

### II. Quantile regression

Gradient boosting relies on approximating the true objective with a second-order expansion, and then picking the splits and predictions in order to optimize this approximate loss. Thus it seems plausible that if the seconr-order approximation to is bad, the quality of our predictions may suffer. This is exactly the issue with quantile regression.

In order for to be well approximated by its second-order example, the local curvature of has to contains some information about where is optimized. Unfortunately, this is not the case for the quantile loss in \eqref{quantileloss}. This loss function has uniformly zero second derivatives, which provide zero information about where it is optimized. Compare this with e.g. a quadratic loss function, where if you know the local curvature and gradient you can reconstruct the coefficients on the quadratic and thus back out exactly where the function is minimized.

However, note that the quantile loss \eqref{quantileloss} does have well-defined derivatives almost everywhere

- is either or depending on or
- is 0
- at , both derivatives are undefined (but this is measure 0 so it doesn’t matter)

As a result, you can just… literally plug these into \eqref{gbtyhat} and \eqref{gbtloss} to get the relevant predictions and losses (though you would have to add some L2 regularization so that the denominator isn’t uniformly 0).

Until early this year, LightGBM’s quantile regression was essentially this (or some slight variant). Then some people started noticing that this was resulting in poor performance, and the devs pushed some changes that appear to have improved performance significantly. **The fix was to grow the trees as above, but then when the tree is grown, actually go back and re-compute the values in each leaf so that they minimize the true loss function \eqref{quantileloss} instead of the second order approximation.**

To be a bit more precise, what LightGBM does for quantile regression is:

- grow the tree as in the standard gradient boosting case
- after a tree is grown, we have a bunch of leaves of this tree
- these leaves partition our data into a bunch of regions
- there is some constant for each partition , computed via \eqref{gbtyhat}, which minimize the second-order approximation of the true quantile loss function
- discard these constants
- now, for each leaf, find the constant that actually minimizes the loss function \eqref{quantileloss} instead of the second-order approximation (explained below)
- use these new s instead of the old ones
- the resulting is a piecewise constant with values given by these new s

Computing the that minimizes the true loss \eqref{quantileloss} over some set of observations is just a matter of finding the empirical quantile. As in, using the from \eqref{quantileloss}, we have:

so that is just the empirical -quantile of computed over the set of observations . Thus, **re-computing the optimal in a given leaf amounts to just finding an empirical quantile.**

This is a quite reasonable approach from a time-complexity perspective:

- this only adds operations per tree
- finding the constant that minimizes the true quantile loss over a set of observations can be done in time via any selection algorithm
- so, total complexity of finding the optimal values for all the leaves is just , since the leaves partition our data

- so, in total we need to perform operations over the entire tree boosting proces
- which is small relative to the complexity of all the splitting we need to do anyways
- compare this to using the true loss function for splitting, which would slow us back down to the non-gradient tree boosting case

Even absent time considerations, this is not that unreasonable

- during the tree-growing process we’re using a second-order approximate loss function instead of the true one
- this approximate loss can be seen as a noised up version of the true loss
- so, the best split under this approximate loss might not correspond to the best split under the true loss
- however, the splitting procedure is greedy, so even with the true loss it’s not going to be globally optimal anyways
- furthermore, we generally force the tree to select non-greedily-optimal splits by randomly restricting the set of observations or dimensions to split on, as a form of regularization
- thus, using the approximate loss is effectively just another form of regularization during the tree growing process
- we only optimize the true loss at the leaves, since leaves are the only places where the actual predicted values matter

#### Implementation in LightGBM:

- the
`TrainOneIter()`

function implements the logic for training one tree (so, corresponding to a single in our exposition above)- it theoretically supports training multiple trees per ‘iteration’ but that parameter (
`num_tree_per_iteration_`

) seems to be… hardcoded to 1? - this function first calls
`tree_learner_->Train()`

(line 437)`Train()`

function is implemented e.g. here, and does the tree-building using the first and second derivatives in the typical gradient tree boosting manner- Note: for quantile regression, LightGBM actually sets the second derivative equal to 1 rather than 0

- it then calls
`tree_learner_->RenewTreeOutput()`

(line 446)- this function does the re-computing of the objective at the leaves

- it theoretically supports training multiple trees per ‘iteration’ but that parameter (
- This is an implementation of
`tree_learner_->RenewTreeOutput()`

- this function just iterates through all the leaves, and calls
`obj->RenewTreeOutput()`

on each one, where`obj`

is whatever objective function we’re using, which in our cases is`RegressionQuantileloss`

- this function just iterates through all the leaves, and calls
- This is the implementation of
`obj->RenewTreeOutput()`

for quantile regression- this just calls the
`PercentileFun()`

function on each leaf in order to get the -quantile of the data in that leaf

- this just calls the
- This is the implementation of
`PercentileFun()`

- it computes the the indices of the two datapoints that would straddle the -quantile, and then does a linear interpolation to find the corresponding quantile
- this relies on the
`ArgMaxAtK()`

function, which appears to be a custom implementation of quickselect for finding the Kth largest item in some set of items

This implementation is consistent with what we verbally described above: each tree is built normally, and after that finishes, the algorithm goes through each leaf and re-computes the optimal prediction in each leaf, which is just the leaf-wise empirical -quantile.

#### Does it actually work?

- People appear to be seeing better performance
- Though there aren’t any theoretical guarantees on consistency