XGBoost › Formula
Machine Learning from ScratchAll chapters XGBoost › FormulaOne section · Sections in this chapter2 / 10 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
The mathematical foundation of XGBoost is rooted in the general gradient boosting framework, but XGBoost introduces several innovations that make it both more powerful and more efficient. To understand how XGBoost works under the hood, let's break down its formulation step by step, carefully explaining the meaning and purpose of each component.
1. The Objective Function
At each boosting iteration , XGBoost seeks to minimize an objective function that balances two goals:
- Fitting the data well (minimizing prediction error)
- Controlling model complexity (to avoid overfitting)
The general form of the objective function at iteration is:
- is the number of training examples.
- is a differentiable loss function (e.g., squared error for regression, log-loss for classification).
- is the true label for instance .
- is the prediction for after trees (i.e., the current ensemble's output).
- is the output of the new tree being added at iteration .
- is a regularization term that penalizes the complexity of the new tree.
At each step, XGBoost adds a new tree to the ensemble, aiming to improve predictions while keeping the model as simple as possible.
2. Second-Order Taylor Expansion
A key innovation in XGBoost is the use of a second-order Taylor expansion to approximate the loss function. This allows XGBoost to use both the gradient (first derivative) and the curvature (second derivative, or Hessian) of the loss, leading to more accurate and stable optimization compared to traditional gradient boosting, which uses only the first derivative.
Note: The second-order Taylor expansion is a mathematical technique that approximates a function near a point using both its slope (first derivative) and curvature (second derivative). This provides a more accurate approximation than using only the slope, especially when the function has significant curvature. In XGBoost, this translates to better optimization steps and faster convergence.
For each data point , we expand the loss function around the current prediction :
where:
- is the first-order gradient (how much the loss would change with a small change in prediction).
- is the second-order gradient (how the gradient itself changes; i.e., the curvature).
This is important because:
- The first-order term () tells us the direction to move to reduce the loss.
- The second-order term () tells us how confident we are in that direction (steepness/curvature).
- Using both allows for more precise and stable updates, especially for complex loss functions.
To understand why second-order information is valuable, consider how gradient and Hessian guide optimization differently:


The visualization demonstrates a key advantage of using second-order information: the Hessian allows XGBoost to adapt step sizes based on local curvature. In the contour plot, notice how the loss surface has different curvature in different directions (the elliptical contours). The first-order method (blue) uses a fixed step size and overshoots in the steep direction, while the second-order method (green) uses curvature information to take a more appropriate step, achieving a lower loss value. This curvature-aware optimization is why XGBoost converges faster and more reliably than traditional gradient boosting.
3. Approximated Objective Function
Plugging the Taylor expansion into the original objective, and noting that is constant with respect to , we get:
- The sum over encourages the new tree to correct the errors of the current model.
- The sum over penalizes large updates, especially where the loss curve is steep (high curvature).
4. Regularization Term
XGBoost's regularization term is more sophisticated than in standard boosting. It penalizes both the complexity of the tree structure and the magnitude of the leaf weights:
Note: Regularization in XGBoost serves multiple purposes: it prevents overfitting by controlling model complexity, encourages sparsity in leaf weights (L1), and provides smooth shrinkage (L2). The structural regularization () specifically controls tree complexity by penalizing the number of leaves, encouraging simpler trees that generalize better.
- is the number of leaves in the tree .
- is the score (weight) assigned to leaf .
- penalizes having too many leaves (encourages simpler trees).
- is the L2 regularization parameter (shrinks large leaf weights).
- is the L1 regularization parameter (encourages sparsity in leaf weights).
This regularization helps prevent overfitting by discouraging overly complex trees and large leaf values.
5. Rewriting the Objective in Terms of Leaves
Let's break down how the objective function is rewritten in terms of the leaves of a tree, step by step.
Partitioning the Data by Leaves
When we build a decision tree, each data point ends up in exactly one leaf. Suppose the tree has leaves. For each leaf (where ), define:
- : the set of indices of data points that fall into leaf . Here, is a function that tells us which leaf belongs to.
- : the score or weight assigned to leaf . Every data point in leaf gets the same output from the tree.
Expanding the Objective Function
Let's expand in detail how the objective function is rewritten in terms of the leaves of the tree.
Recall the approximated objective function after the second-order Taylor expansion:
where:
- is the first derivative (gradient) of the loss with respect to the prediction for ,
- is the second derivative (Hessian) of the loss with respect to the prediction for ,
- is the output of the new tree for ,
- is the regularization term for the tree.
Grouping by Leaves
A decision tree partitions the data into leaves. Each data point falls into exactly one leaf, say leaf . Let:
- be the set of indices of data points assigned to leaf ,
- be the score (weight) assigned to leaf .
By the definition of a tree, for all , the output of the tree is the same:
- for all .
This allows us to rewrite the sums over all data points as sums over leaves, grouping together all points in the same leaf.
Expanding the First-Order Term (Step-by-Step)
Let's break down how to rewrite the first-order term by grouping data points according to the leaves they fall into:
-
Start with the original first-order term:
-
Group data points by their assigned leaf: Each data point is assigned to a leaf , so we can rewrite the sum over all data points as a sum over leaves and, within each leaf, a sum over the data points in that leaf:
-
Substitute the leaf weight for the tree output: For all in leaf , , so we can replace with :
-
Factor out terms that do not depend on : is constant for all in , so we can factor it out of the inner sum:
-
Write the final grouped form: This shows that the first-order term for the whole tree is the sum, over all leaves, of the sum of gradients in each leaf times the leaf's weight:
This step-by-step grouping is important because it allows us to efficiently compute the contribution of each leaf to the objective function.
Expanding the Second-Order Term
Let's break down how to rewrite the second-order term by grouping data points according to the leaves they fall into:
-
Start with the original second-order term:
-
Group data points by their assigned leaf: Each data point is assigned to a leaf , so we can rewrite the sum over all data points as a sum over leaves and, within each leaf, a sum over the data points in that leaf:
-
Substitute the leaf weight for the tree output: For all in leaf , , so we can replace with :
-
Factor out terms that do not depend on : is constant for all in , so we can factor it out of the inner sum:
-
Write the final grouped form: This shows that the second-order term for the whole tree is the sum, over all leaves, of the sum of Hessians in each leaf times the square of the leaf's weight (with a factor of ):
This step-by-step grouping is important because it allows us to efficiently compute the contribution of each leaf to the objective function.
Putting It Together
So, the original sum over all data points can be rewritten as a sum over leaves, where each leaf's contribution depends on the sum of gradients and Hessians of the data points it contains, and the leaf's weight:
This grouping allows XGBoost to efficiently compute the optimal weights for each leaf and to evaluate the quality of different tree structures.
Adding Regularization
The regularization term for the tree is:
- penalizes the number of leaves (to discourage overly complex trees).
- and penalize large or non-sparse leaf weights.
Note: This is basically the L1 and L2 regularization covered in the Ridge and LASSO regularization chapters, but applied to the leaf weights.
Putting It All Together
Let's carefully combine the grouped sums from the objective and the regularization terms, step by step.
Recall from above that, after grouping by leaves, the second-order Taylor-approximated objective (before regularization) is:
Now, let's add the regularization term for the tree:
So, the total objective at step is:
Let's write all terms involving together, grouping by leaf :
Now, notice that the two quadratic terms in can be combined for each leaf :
So, the objective simplifies to:
Or, written out for clarity:
This is the final grouped and regularized form of the objective for a single boosting step in XGBoost.
What does this mean?
- For each leaf , we sum up all the gradients () and Hessians () of the data points that fall into that leaf.
- The objective for the whole tree is now just a sum over the leaves, where each leaf's contribution depends on its weight , the total gradient and Hessian in that leaf, and the regularization terms.
- This form makes it possible to analytically solve for the best for each leaf, and to efficiently evaluate how good a particular tree structure is.
By grouping the data by leaves, we turn a sum over all data points into a sum over leaves, where each leaf's effect on the objective depends only on the data points it contains. This is the key step that allows XGBoost to efficiently optimize tree structures and leaf values.
6. Finding the Optimal Leaf Weights
To determine the best value for each leaf weight , we take the derivative of the objective with respect to and set it to zero (for simplicity, let's ignore the L1 term for now):
Note: The L1 regularization term () is non-differentiable at zero, which complicates the analytical solution. In practice, XGBoost uses soft thresholding techniques to handle L1 regularization, but for this derivation, we focus on the L2 case to demonstrate the core mathematical principle.
Start with the grouped objective for a single leaf :
where
- (sum of gradients in leaf )
- (sum of Hessians in leaf )
Take the derivative with respect to :
Set the derivative to zero to find the minimum:
Solve for :
Substituting back the definitions:
- The optimal weight for each leaf is determined by the sum of gradients (how much the model is under- or over-predicting) and the sum of Hessians (how "confident" we are in those gradients), regularized by .
- This formula is used to assign the value to each leaf during tree construction.
To visualize how this optimization works, consider how the objective function for a single leaf varies with the leaf weight :


The visualization reveals how XGBoost finds optimal leaf weights through a simple quadratic optimization. The left plot shows how different gradient and Hessian values shift the location of the minimum.negative gradients push the optimum to positive weights (and vice versa), while larger Hessians create steeper curves that concentrate the optimum. The right plot demonstrates regularization's effect: as increases, the optimal weight is pulled toward zero, preventing overfitting by penalizing large leaf values. This analytical solution is one of XGBoost's key advantages.rather than iteratively searching for good weights, it can compute the exact optimum for each leaf given the tree structure.
7. The Structure Score (Split Gain)
When building the tree, XGBoost evaluates possible splits by computing the "gain" or "quality score" for a given tree structure. This is the improvement in the objective function if we use a particular split:
- The numerator rewards splits that group together data points with similar gradients (i.e., similar errors).
- The denominator penalizes splits where the model is less confident (low Hessian sum) or where regularization is strong.
- The term penalizes having too many leaves.
How is this used?
- During tree construction, XGBoost greedily chooses splits that maximize the reduction in this score (i.e., the largest gain).
- This process continues recursively, subject to constraints like maximum depth or minimum gain.
To understand how XGBoost evaluates and selects splits, consider a concrete example with multiple candidate splits:

This visualization demonstrates XGBoost's greedy split selection process in action. The algorithm evaluates each possible split point by calculating how much the objective function would improve if that split were made. The gain formula balances three components: the quality of the left child (how well grouped its gradients are), the quality of the right child, and the cost of adding complexity (the penalty). Notice how some splits have negative gain.these would make the model worse and are rejected. The split with the highest positive gain (highlighted in dark green) is selected, and the process repeats recursively for each child node. This greedy approach, combined with the analytical gain formula, allows XGBoost to efficiently build effective tree structures without exhaustive search.
In summary, the structure score is used to guide the tree construction process:
- XGBoost's formula starts from the general gradient boosting objective, but uses a second-order Taylor expansion for more accurate optimization.
- It incorporates advanced regularization to control model complexity.
- The optimal leaf weights and split decisions are derived analytically using the gradients and Hessians of the loss function.
- This mathematical machinery enables XGBoost to build accurate tree ensembles that train efficiently.

Mathematical properties
The second-order approximation in XGBoost provides several important mathematical advantages. By incorporating the Hessian matrix (second derivatives), the algorithm can make more informed decisions about the direction and magnitude of updates, leading to faster convergence and better final performance. This is particularly beneficial when the loss function has significant curvature, as the second-order information captures this curvature more accurately than first-order methods alone.
Note: The mathematical presentation here focuses on the key concepts and simplified formulations. In practice, XGBoost's implementation includes additional optimizations such as approximate algorithms for split finding, handling of missing values, and various computational optimizations that are beyond the scope of this mathematical overview.
The regularization terms in XGBoost serve multiple purposes. The L2 regularization () helps prevent overfitting by penalizing large leaf weights, while the L1 regularization () can lead to sparsity in the leaf weights, effectively performing feature selection. The structural regularization () controls the complexity of the tree by penalizing the number of leaves, encouraging simpler trees that are less likely to overfit.




