Find the best split with the XGBoost gain formula

Why it matters This gain formula is the heart of XGBoost and LightGBM style boosters that dominate tabular ML competitions and production risk models.

Gradient boosted trees choose splits using sums of gradients and Hessians, with lambda shrinking leaf weights and gamma charging for each new leaf.

Write best_split_gain(x, g, h, lam, gamma). x holds one feature's values, g and h the per-row gradients and Hessians. Consider every threshold halfway between consecutive distinct sorted x values; rows with x < threshold go left. With G, H the sums over a node, gain = 0.5 * (G_L^2 / (H_L + lam) + G_R^2 / (H_R + lam) - G^2 / (H + lam)) - gamma. Return (threshold, gain) for the largest gain (smallest threshold on ties) as floats. If no threshold has gain > 0 (or x has one distinct value) return (None, 0.0).

Signaturedef best_split_gain(x, g, h, lam, gamma)

Example

x [1, 2, 3, 4], g [-1, -1, 1, 1], h [1, 1, 1, 1], lam 1, gamma 0 gives (2.5, 1.333333).

Understand the idea

In gradient boosting each row has a gradient g (which direction the loss wants the prediction to move) and a Hessian h (how curved the loss is). A leaf that holds rows with sums G and H gets the best weight w = -G / (H + lam), and that weight lowers the loss by G^2 / (2 (H + lam)). Lambda acts like extra Hessian and shrinks weights.

A split is worth it if the two children together lower the loss more than the parent alone, by more than gamma, the cost of adding a leaf.

Worked example: g = -1, -1, 1, 1, h = 1 each, lam = 1. The parent has G = 0, so its score is 0. Splitting at 2.5 gives G_L = -2, H_L = 2 and G_R = 2, H_R = 2. Gain = 0.5 * (4/3 + 4/3 - 0) = 1.333. With gamma = 2 the gain is negative, so we do not split.

Rule: gain = 0.5 * [G_L^2/(H_L + lam) + G_R^2/(H_R + lam) - G^2/(H + lam)] - gamma.

XGBoost style libraries evaluate exactly this for every candidate threshold.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplebest_split_gain([1, 2, 3, 4], [-1, -1, 1, 1], [1, 1, 1, 1], 1.0, 0.0)
  • Sample 2: gamma blocks splitbest_split_gain([1, 2, 3, 4], [-1, -1, 1, 1], [1, 1, 1, 1], 1.0, 2.0)
  • Test 3: ties in xbest_split_gain([3, 1, 3, 2, 5], [0.5, -2, 0.4, -1, 1.5], [0.25, 0.2, 0.25, 0.2, 0.1], 0.5, 0.1)
  • Test 4: one valuebest_split_gain([7, 7, 7], [1, -1, 2], [1, 1, 1], 1.0, 0.0)