Sign in

LightGBM

Light Gradient Boosting Machine

Histogram gradient boosting in the style of LightGBM: binned features, trees grown leaf by leaf, and optional gradient-based sampling.

Overview

Gradient boosting adds small trees one after another, each fitted to the errors the model still makes. The slow part is finding the best split, which normally means sorting every feature at every node. LightGBM avoids this by cutting each feature into a small number of bins once, at the start. To evaluate splits it only needs, for each bin, the sum of the gradients of the rows that fall in it. That table of sums is a histogram, and scanning it is fast. The tree also grows differently: it always splits the leaf that promises the largest gain, wherever it is, so it spends its leaves where the error is largest.

A short history

Guolin Ke and colleagues at Microsoft published LightGBM at NeurIPS in 2017. Gradient boosting was already accurate, but finding splits by scanning sorted feature values was slow on large data. LightGBM bins features into histograms, grows trees leaf by leaf, and adds gradient-based one-side sampling and exclusive feature bundling to cut the work further. It became one of the standard libraries for tabular data in industry and in competitions.

How it works

  1. Cut every feature into at most max_bin bins and replace each value by its bin number. This is done once.
  2. Start with a constant prediction. For each tree, compute every row's gradient and hessian (the first and second derivative of the loss with respect to the prediction).
  3. With boosting="goss", keep the rows with the largest gradients and a reweighted random sample of the rest.
  4. Build the root's histogram: per feature and bin, the sums of gradients and hessians. Scan it for the best split.
  5. Grow leaf-wise: repeatedly split the leaf with the largest gain, until the tree has num_leaves leaves or no split qualifies.
  6. For each split, build the histogram of one child from its rows and get the other by subtracting it from the parent's.
  7. Set each leaf value to −η G/(H+λ)-\eta\, G / (H + \lambda), add the tree to the model and repeat.

Watch out for

  • Leaf-wise growth can build very deep, narrow branches that fit a handful of rows. Lower num_leaves or raise min_data_in_leaf when the validation error rises.
  • Binning limits where a split can fall. With too few bins a useful threshold inside a bin cannot be found.
  • Trees predict a constant per leaf, so the model cannot extrapolate a trend beyond the range of the training targets.
  • A large learning_rate with many trees overfits quickly, and this template has no early stopping, so check the error on held-out data yourself.
  • This is a single-threaded NumPy version without exclusive feature bundling, native categorical splits, missing-value handling or multiclass objectives.

Use cases

When to use it

The default strong model for numeric tabular data: it captures non-linear effects and interactions without feature scaling.

In industry

Web search and feeds
Learning to rank: ordering results or items with boosted trees trained on relevance or click labels.
Retail
Demand forecasting across many products and stores; LightGBM models were prominent among top entries in the M5 forecasting competition.
Banking
Credit default and fraud scoring on large tables of customer and transaction features.

Choosing it: what must hold

  • Tabular data with a supervised target.
  • Enough rows, roughly ten thousand or more, for leaf-wise growth not to overfit.
  • Limits on the number of leaves and the minimum rows per leaf, tuned on validation data.

When to choose something else

IfUse instead
The table is smallA random forest, or XGBoost with depth-wise growth and stronger regularisation
Many columns are categorical with strong signalCatBoost
The inputs are images, audio or raw textA neural network suited to that data, such as a CNN or a Transformer

Math foundations

  1. Additive model

    Fm(x)=Fm−1(x)+η fm(x)F_m(\mathbf{x}) = F_{m-1}(\mathbf{x}) + \eta\, f_m(\mathbf{x})

    Each round adds one tree, shrunk by the learning rate, to the model built so far.

  2. Second-order view of the loss

    L≈∑i[gi f(xi)+12hi f(xi)2]+λ2∑jwj2+const\mathcal{L} \approx \sum_{i} \Big[ g_i\, f(\mathbf{x}_i) + \tfrac{1}{2} h_i\, f(\mathbf{x}_i)^2 \Big] + \frac{\lambda}{2} \sum_{j} w_j^2 + \text{const}

    The loss after adding a tree ff, approximated by a Taylor expansion around the current predictions. Here gig_i and hih_i are the first and second derivatives of the loss for row ii. For squared error gi=F−yig_i = F - y_i and hi=1h_i = 1.

  3. Best value of a leaf

    w∗=−GH+λ,G=∑i∈leafgi,H=∑i∈leafhiw^{*} = -\frac{G}{H + \lambda}, \qquad G = \sum_{i \in \text{leaf}} g_i, \quad H = \sum_{i \in \text{leaf}} h_i

    All rows of a leaf share one value ww, so the expression above is a parabola in ww. This is its minimum: a Newton step for the rows of the leaf.

  4. Gain of a split

    gain=GL2HL+λ+GR2HR+λ−G2H+λ\text{gain} = \frac{G_L^2}{H_L + \lambda} + \frac{G_R^2}{H_R + \lambda} - \frac{G^2}{H + \lambda}

    How much the approximated loss drops when a leaf is cut in two. Textbooks often carry a factor of one half, which does not change which split wins. Only sums of gg and hh are needed, and the histogram supplies exactly those.

  5. Histogram subtraction

    hist⁡(right)=hist⁡(parent)−hist⁡(left)\operatorname{hist}(\text{right}) = \operatorname{hist}(\text{parent}) - \operatorname{hist}(\text{left})

    Every row of the parent is in exactly one child, so the bin sums add up. Only one child needs a pass over its rows, which roughly halves the work.

  6. GOSS gradient estimate

    G~=∑i∈Agi+1−ab∑i∈Bgi\tilde{G} = \sum_{i \in A} g_i + \frac{1 - a}{b} \sum_{i \in B} g_i

    AA holds the share aa of rows with the largest gradients, all kept. BB is a random sample of size b nb\,n from the rest. Scaling it up by (1−a)/b(1 - a)/b makes the sum an unbiased estimate of the sum over all rows.

Symbols

FmF_m
the model after m trees
fmf_m
the m-th tree
η\eta
learning_rate
gi,hig_i, h_i
gradient and hessian of the loss for row i
G,HG, H
sums of g and h over the rows of a leaf
GL,HL,GR,HRG_L, H_L, G_R, H_R
the same sums for the left and right child of a split
λ\lambda
lambda_l2
wjw_j
the value of leaf j
a,ba, b
top_rate and other_rate of GOSS
A,BA, B
the kept large-gradient rows and the sampled remaining rows
nn
number of training rows

Worked by hand

Squared error, so every hi=1h_i = 1, with λ=0\lambda = 0 and η=0.1\eta = 0.1. A leaf holds five rows with gradients −2,−1,1,2,3-2, -1, 1, 2, 3. A candidate split sends the first two rows left and the last three right.

GL=−3,  HL=2,GR=6,  HR=3,G=3,  H=5G_L = -3, \; H_L = 2, \qquad G_R = 6, \; H_R = 3, \qquad G = 3, \; H = 5
gain=(−3)22+623−325=4.5+12−1.8=14.7\text{gain} = \frac{(-3)^2}{2} + \frac{6^2}{3} - \frac{3^2}{5} = 4.5 + 12 - 1.8 = 14.7
wL=−−32=1.5,wR=−63=−2w_L = -\frac{-3}{2} = 1.5, \qquad w_R = -\frac{6}{3} = -2
η wL=0.15,η wR=−0.2\eta\, w_L = 0.15, \qquad \eta\, w_R = -0.2

The split separates rows whose predictions are too low (negative gradient) from rows whose predictions are too high. The left leaf raises its rows by 0.15 and the right leaf lowers its rows by 0.2 after shrinkage.

Visual example

Loading the example.

Try this

  • Trees here grow one leaf at a time, wherever the gain is largest.
  • Raise the leaf count and compare the shape with XGBoost's level-by-level trees.

Code sample

import numpy as np
from impl import LightGBM
from config import LightGBMConfig

rng = np.random.default_rng(0)
X = rng.uniform(-2, 2, size=(1500, 4))
y = np.sin(2 * X[:, 0]) + X[:, 1] ** 2 + X[:, 2] * X[:, 3]
model = LightGBM(LightGBMConfig(n_estimators=150, num_leaves=15)).fit(X[:1000], y[:1000])
print(np.mean((model.predict(X[1000:]) - y[1000:]) ** 2).round(3), "test MSE; target variance", y.var().round(2))
print(model.feature_importances_.round(2))
Read the implementation (226 lines)
"""LightGBM-style gradient boosting: histogram splits, leaf-wise tree growth, optional GOSS sampling.

NumPy only. The three ideas that make LightGBM fast are implemented:

1. Histograms. Every feature is cut into at most `max_bin` bins once. A split is then found from per-bin sums
   of gradients and hessians instead of from sorted raw values.
2. Leaf-wise growth. The tree always splits the leaf with the largest gain (best-first), up to `num_leaves`
   leaves, instead of growing level by level. The histogram of one child is built from its rows and the
   other is obtained by subtracting it from the parent's.
3. GOSS (gradient-based one-side sampling). Each tree can be fitted on the rows with the largest gradients
   plus a reweighted random sample of the rest.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import LightGBMConfig
except ImportError:  # run from the template's own folder
    from config import LightGBMConfig


def _sigmoid(z: np.ndarray) -> np.ndarray:
    return 1.0 / (1.0 + np.exp(-np.clip(z, -60.0, 60.0)))


def find_bin_edges(x: np.ndarray, max_bin: int) -> np.ndarray:
    """Upper edges of the bins of one feature, without the last (open) bin.

    x: (n,) values. A value v falls in bin `searchsorted(edges, v, side="left")`, that is the first bin whose
    edge is >= v. With at most `max_bin` distinct values every value gets its own bin; otherwise the edges
    are quantiles, so the bins hold about the same number of rows. Returns at most max_bin - 1 edges.
    """
    values = np.unique(x)
    if len(values) <= max_bin:
        return (values[1:] + values[:-1]) / 2.0
    return np.unique(np.quantile(x, np.linspace(0, 1, max_bin + 1)[1:-1]))


class LightGBM:
    """Histogram gradient boosting. objective "regression": squared error. "binary": log-loss on 0/1 labels."""

    def __init__(self, config: LightGBMConfig | None = None) -> None:
        self.config = config or LightGBMConfig()
        self.bin_edges_: list[np.ndarray] = []
        self.trees_: list[list[dict]] = []      # each tree is a list of nodes; node 0 is the root
        self.base_ = 0.0
        self.feature_importances_: np.ndarray | None = None  # total split gain per feature, normalised to sum 1
        self.loss_history: list[float] = []     # training loss after each tree

    # ---- binning and histograms ------------------------------------------------------------------------
    def _bin(self, X: np.ndarray) -> np.ndarray:
        """Raw features (n, d) -> bin indices (n, d)."""
        X = np.asarray(X, dtype=float)
        if X.ndim != 2 or X.shape[1] != len(self.bin_edges_):
            raise ValueError(f"X must have shape (n, {len(self.bin_edges_)}), got {X.shape}")
        return np.column_stack([np.searchsorted(e, X[:, j], side="left") for j, e in enumerate(self.bin_edges_)])

    def _histogram(self, B: np.ndarray, rows: np.ndarray, g: np.ndarray, h: np.ndarray) -> np.ndarray:
        """Per-feature, per-bin sums over `rows`. Returns (3, d, n_bins): gradient sum, hessian sum, row count."""
        d = B.shape[1]
        flat = (B[rows] + self._bin_offsets[None, :]).ravel()
        size = d * self._n_bins
        return np.stack([
            np.bincount(flat, weights=np.repeat(g[rows], d), minlength=size),
            np.bincount(flat, weights=np.repeat(h[rows], d), minlength=size),
            np.bincount(flat, minlength=size).astype(float),
        ]).reshape(3, d, self._n_bins)

    def _best_split(self, hist: np.ndarray, features: np.ndarray):
        """Best split of a leaf from its histogram: (gain, feature, bin) or None. Rows with bin <= `bin` go left."""
        cfg = self.config
        G, H, N = hist[0].sum(axis=1)[0], hist[1].sum(axis=1)[0], hist[2].sum(axis=1)[0]
        GL, HL, NL = (np.cumsum(hist[k][features], axis=1)[:, :-1] for k in range(3))
        GR, HR, NR = G - GL, H - HL, N - NL
        gain = GL**2 / (HL + cfg.lambda_l2 + 1e-12) + GR**2 / (HR + cfg.lambda_l2 + 1e-12) - G**2 / (H + cfg.lambda_l2 + 1e-12)
        ok = (NL >= cfg.min_data_in_leaf) & (NR >= cfg.min_data_in_leaf)
        gain = np.where(ok, gain, -np.inf)
        f, b = np.unravel_index(int(gain.argmax()), gain.shape)
        if not gain[f, b] > 1e-12:
            return None
        return float(gain[f, b]), int(features[f]), int(b)

    # ---- one tree --------------------------------------------------------------------------------------
    def _grow_tree(self, B: np.ndarray, rows: np.ndarray, g: np.ndarray, h: np.ndarray, rng) -> list[dict]:
        """Grow one tree leaf-wise on the rows `rows` of the binned data. Returns the list of nodes."""
        cfg = self.config
        d = B.shape[1]
        n_use = max(1, int(round(cfg.feature_fraction * d)))
        features = np.sort(rng.choice(d, size=n_use, replace=False)) if n_use < d else np.arange(d)

        def leaf_value(hist: np.ndarray) -> float:
            return float(-hist[0, 0].sum() / (hist[1, 0].sum() + cfg.lambda_l2 + 1e-12) * cfg.learning_rate)

        root_hist = self._histogram(B, rows, g, h)
        nodes = [{"value": leaf_value(root_hist), "depth": 0}]
        open_leaves = {0: (rows, root_hist, self._best_split(root_hist, features))}
        n_leaves = 1
        while n_leaves < cfg.num_leaves:
            candidates = [(s[0], i) for i, (_, _, s) in open_leaves.items()
                          if s is not None and (cfg.max_depth is None or nodes[i]["depth"] < cfg.max_depth)]
            if not candidates:
                break
            _, i = max(candidates)  # the leaf whose best split has the largest gain
            leaf_rows, hist, (gain, f, b) = open_leaves.pop(i)
            go_left = B[leaf_rows, f] <= b
            left_rows, right_rows = leaf_rows[go_left], leaf_rows[~go_left]
            # Build the histogram of the smaller child; the other one is parent minus that.
            if len(left_rows) <= len(right_rows):
                left_hist = self._histogram(B, left_rows, g, h)
                right_hist = hist - left_hist
            else:
                right_hist = self._histogram(B, right_rows, g, h)
                left_hist = hist - right_hist
            left_id, right_id = len(nodes), len(nodes) + 1
            depth = nodes[i]["depth"] + 1
            nodes[i].update(feature=f, bin=b, threshold=float(self.bin_edges_[f][b]), left=left_id, right=right_id, gain=gain)
            nodes.append({"value": leaf_value(left_hist), "depth": depth})
            nodes.append({"value": leaf_value(right_hist), "depth": depth})
            open_leaves[left_id] = (left_rows, left_hist, self._best_split(left_hist, features))
            open_leaves[right_id] = (right_rows, right_hist, self._best_split(right_hist, features))
            self._gain[f] += gain
            n_leaves += 1
        return nodes

    @staticmethod
    def _tree_predict(nodes: list[dict], B: np.ndarray) -> np.ndarray:
        """Leaf value of every row of the binned data B (n, d). Returns (n,)."""
        out = np.empty(len(B))
        stack = [(0, np.arange(len(B)))]
        while stack:
            i, rows = stack.pop()
            node = nodes[i]
            if "feature" not in node:
                out[rows] = node["value"]
                continue
            go_left = B[rows, node["feature"]] <= node["bin"]
            stack.append((node["left"], rows[go_left]))
            stack.append((node["right"], rows[~go_left]))
        return out

    # ---- loss and sampling -----------------------------------------------------------------------------
    def _grad_hess(self, y: np.ndarray, pred: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """Gradient and hessian of the loss with respect to the raw prediction."""
        if self.config.objective == "regression":
            return pred - y, np.ones_like(y)
        p = _sigmoid(pred)
        return p - y, np.maximum(p * (1.0 - p), 1e-12)

    def _loss(self, y: np.ndarray, pred: np.ndarray) -> float:
        if self.config.objective == "regression":
            return float(np.mean((y - pred) ** 2))
        return float(np.mean(np.logaddexp(0.0, pred) - y * pred))

    def goss_sample(self, g: np.ndarray, rng) -> tuple[np.ndarray, np.ndarray]:
        """Gradient-based one-side sampling.

        Keeps the `top_rate` share of rows with the largest |gradient| and a random `other_rate` share of the
        rest, whose weight is raised to (1 - top_rate) / other_rate so the gradient sums stay unbiased.
        Returns (row indices, weight of each of those rows).
        """
        cfg = self.config
        n = len(g)
        n_top = int(np.ceil(cfg.top_rate * n))
        n_other = min(int(np.ceil(cfg.other_rate * n)), n - n_top)
        order = np.argsort(-np.abs(g), kind="stable")
        other = rng.choice(order[n_top:], size=n_other, replace=False)
        rows = np.concatenate([order[:n_top], other])
        weights = np.concatenate([np.ones(n_top), np.full(n_other, (1.0 - cfg.top_rate) / cfg.other_rate)])
        return rows, weights

    # ---- public API ------------------------------------------------------------------------------------
    def fit(self, X: np.ndarray, y: np.ndarray) -> "LightGBM":
        """Train. X: (n, d) numeric features. y: (n,) values (regression) or 0/1 labels (binary)."""
        cfg = self.config
        X = np.asarray(X, dtype=float)
        y = np.asarray(y, dtype=float)
        n, d = X.shape
        rng = np.random.default_rng(cfg.seed)
        self.bin_edges_ = [find_bin_edges(X[:, j], cfg.max_bin) for j in range(d)]
        self._n_bins = max(len(e) for e in self.bin_edges_) + 1
        self._bin_offsets = np.arange(d) * self._n_bins
        B = self._bin(X)
        if cfg.objective == "regression":
            self.base_ = float(y.mean())
        else:
            p = np.clip(y.mean(), 1e-6, 1 - 1e-6)
            self.base_ = float(np.log(p / (1 - p)))
        pred = np.full(n, self.base_)
        self._gain = np.zeros(d)
        self.trees_, self.loss_history = [], []
        all_rows = np.arange(n)
        for _ in range(cfg.n_estimators):
            g, h = self._grad_hess(y, pred)
            rows = all_rows
            if cfg.boosting == "goss":
                rows, weights = self.goss_sample(g, rng)
                g, h = g.copy(), h.copy()
                g[rows] *= weights
                h[rows] *= weights
            tree = self._grow_tree(B, rows, g, h, rng)
            pred += self._tree_predict(tree, B)
            self.trees_.append(tree)
            self.loss_history.append(self._loss(y, pred))
        total = self._gain.sum()
        self.feature_importances_ = self._gain / total if total > 0 else self._gain
        return self

    def decision_function(self, X: np.ndarray) -> np.ndarray:
        """Raw model output: the value for regression, the log-odds for binary. Returns (n,)."""
        B = self._bin(X)
        out = np.full(len(B), self.base_)
        for tree in self.trees_:
            out += self._tree_predict(tree, B)
        return out

    def predict_proba(self, X: np.ndarray) -> np.ndarray:
        """Probability of class 1, (n,). Only for objective='binary'."""
        if self.config.objective != "binary":
            raise ValueError("predict_proba is only defined for objective='binary'")
        return _sigmoid(self.decision_function(X))

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Predicted values (regression) or 0/1 labels (binary), (n,)."""
        raw = self.decision_function(X)
        return raw if self.config.objective == "regression" else (raw >= 0).astype(int)
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Fit LightGBM on the README regression data and plot loss_history. Repeat with num_leaves set to 4, 15 and 63 and compare the training loss with the error on the 500 held-out rows. Then switch to boosting="goss" and see how much the held-out error changes when each tree sees about 30 percent of the rows.

Check on learning

  1. Finding the best split on raw values needs a sort per feature at every node. Why is a histogram with 63 bins enough in practice, and what is given up?
    A way to think about it

    Ask how much the loss can differ between two thresholds that lie in the same narrow bin. Then consider a feature whose useful cut sits between two values that share a bin.

  2. Leaf-wise growth with 15 leaves and level-wise growth to depth 4 (16 leaves) use almost the same number of leaves. Why can the leaf-wise tree reach a lower training loss, and why is that also a risk?
    A way to think about it

    Leaf-wise growth is free to put all its splits on one side of the tree. Think about how many rows end up in the deepest leaves.

  3. GOSS keeps all rows with large gradients and only a sample of the rest. Why are the large-gradient rows the ones worth keeping?
    A way to think about it

    A small gradient means the model already predicts that row well. Look at which rows contribute most to the sums in the gain formula.

  4. Why must the sampled small-gradient rows be multiplied by (1−a)/b(1 - a)/b? What would happen to the splits without that factor?
    A way to think about it

    Count how many rows the sample stands for. Without the correction the gradient sums would be dominated by the large-gradient rows, as if the easy rows hardly existed.

  5. The model is trained on house prices up to one million and asked about a house that should cost three million. What will it predict, and why?
    A way to think about it

    Every prediction is a sum of leaf values learned from training rows. Find the largest value such a sum can reach.