AI
XGBoost Explained: Why It Wins on Tabular Data
XGBoost explained: how gradient-boosted trees work, a split worked by hand, the key parameters and when to pick it over random forest.
XGBoost is an open-source library that trains gradient-boosted decision trees: it builds many small trees one after another, and each new tree is fitted to correct the mistakes of the trees before it. The name stands for eXtreme Gradient Boosting. It became the default tool for prediction on tables of data (customer records, sensor readings, transactions, anything that fits in a spreadsheet) because it is accurate, fast, handles missing values and resists overfitting through built-in regularization.
This guide gives you XGBoost explained in plain language: how boosting works, what the XGBoost algorithm adds to ordinary gradient boosting, one split calculated by hand so the formulas make sense, the XGBoost parameters that matter, a short Python example, a comparison of XGBoost vs random forest, LightGBM and CatBoost, and when not to use it.
What Is XGBoost?
XGBoost was created by Tianqi Chen and Carlos Guestrin and described in their 2016 paper "XGBoost: A Scalable Tree Boosting System". It's a system for supervised learning: you give it labelled rows (features and a known outcome), and it learns to predict the outcome for new rows, either a number (regression) or a class (classification, ranking). It runs on a single machine or a cluster, supports GPUs and has interfaces for Python, R, Java, Julia and more.
The paper's own evidence for how widely it was adopted is worth quoting: of the 29 challenge-winning solutions published on Kaggle's blog during 2015, 17 used XGBoost, eight of them using XGBoost alone, and every team in the top 10 of KDD Cup 2015 used it. Deep neural nets, the second most popular method, appeared in 11 of those solutions. That was a decade ago, but the pattern has held for tabular data, as the next section explains.
How Gradient Boosting Works
Boosting builds a strong model from many weak ones. Each weak learner is a small decision tree, only a few levels deep, and on its own it predicts poorly. The trick is how they are combined:
- Start with a simple prediction for every row, such as the average of the target.
- Measure the error of the current predictions (the gap between prediction and truth for each row).
- Fit a small tree whose job is to predict those errors from the features.
- Add that tree's output to the running prediction, scaled down by a small number called the learning rate (
eta), so each tree only nudges the answer. - Repeat for hundreds or thousands of rounds, with each tree targeting what is still wrong.
The final prediction is the sum of all the trees' outputs. "Gradient" refers to how the error is defined: each new tree is fitted to the negative gradient of the loss function, which for squared error is just the residual (truth minus prediction). It's gradient descent, but instead of adjusting numbers, each step adds a whole tree. Our guide to the learning rate explains why a small step size helps; in boosting it's the shrinkage that makes each tree a gentle correction.
What the XGBoost Algorithm Adds
Plain gradient boosting already worked well. The XGBoost algorithm made it better and much faster through several changes:
| Feature | What it does | Why it matters |
|---|---|---|
| Regularized objective | Adds a penalty for the number of leaves and for large leaf values (L2, and optionally L1) | Prevents overfitting without extra tricks |
| Second-order optimization | Uses both the gradient and the second derivative (hessian) of the loss to pick splits and leaf values | More accurate steps, fewer trees needed |
| Sparsity-aware splitting | Learns a default direction for missing or zero entries at each split | Handles missing values without imputation |
| Histogram split finding | Groups feature values into bins (256 by default) and searches splits over bins | Much faster on large data; the default method |
| Row and column subsampling | Each tree sees a random share of rows and features | Reduces overfitting and speeds training |
| Parallel, cache-aware design | Sorts data once into column blocks, parallelises split search | Scales to very large datasets |
| Categorical support | Splits directly on pandas category columns when enabled | Less manual encoding |
The paper reports that its sparsity-aware algorithm ran about 50 times faster than a naive version on a sparse test dataset (Allstate-10K). The point isn't any single trick but the combination: accuracy comes from regularization and second-order information, speed from the system engineering.
The Objective in One Line
At each round XGBoost minimises the training loss plus a penalty for tree complexity:
objective = sum of losses + gamma * (number of leaves) + 0.5 * lambda * (sum of squared leaf values)gamma charges a fixed cost for each extra leaf, and lambda shrinks leaf values toward zero. When both are zero, this collapses to ordinary gradient tree boosting. The paper then approximates the loss with a second-order Taylor expansion, using for each row the gradient g and the hessian h of the loss. For a leaf containing a set of rows, the best leaf value is:
leaf value = - (sum of g) / (sum of h + lambda)and splitting a node is worth doing when its gain is positive:
gain = 0.5 * [ GL^2/(HL + lambda) + GR^2/(HR + lambda) - (GL + GR)^2/(HL + HR + lambda) ] - gammawhere GL and HL are the sums of g and h for rows going left, and GR and HR for rows going right. That is the whole XGBoost algorithm for choosing a split: try candidate thresholds, compute this gain, take the best.
Worked Example: One Split by Hand
Take four houses, with one feature (size in square metres) and the target price in thousands. We start every house at the average price, 16, and use squared error, for which g is prediction minus truth and h is 1 for each row.
| House | Size | Price | Prediction | g (prediction minus price) | h |
|---|---|---|---|---|---|
| A | 50 | 10 | 16 | 6 | 1 |
| B | 60 | 12 | 16 | 4 | 1 |
| C | 80 | 20 | 16 | -4 | 1 |
| D | 90 | 22 | 16 | -6 | 1 |
Set lambda to 1 and gamma to 0. XGBoost tries a split between each pair of neighbouring sizes:
| Split | GL | HL | GR | HR | Gain |
|---|---|---|---|---|---|
| Between 50 and 60 | 6 | 1 | -6 | 3 | 0.5 x (36/2 + 36/4 - 0) = 13.5 |
| Between 60 and 80 | 10 | 2 | -10 | 2 | 0.5 x (100/3 + 100/3 - 0) = 33.3 |
| Between 80 and 90 | 6 | 3 | -6 | 1 | 0.5 x (36/4 + 36/2 - 0) = 13.5 |
The middle split wins: small houses on one side, big ones on the other. The leaf values are -GL/(HL + lambda) = -10/3 = -3.33 for the left leaf and +3.33 for the right. With a learning rate of 0.3, the predictions move by 0.3 x 3.33 = 1.0: the two small houses go from 16 to 15, the two large ones to 17. Both moved in the right direction, but only a little, which is exactly the point of boosting.
Two things to notice. First, if lambda were 0, the leaf values would be -5 and +5, the plain average residual. Lambda = 1 shrinks them to 3.33, which is how regularization keeps individual trees modest. Second, if gamma were 40, the best gain of 33.3 would be below the cost of a split, and the split would be pruned. That is how gamma stops weak splits.
Why XGBoost Wins on Tabular Data
For rows-and-columns data, trees plus boosting remain very hard to beat. A 2022 study by Grinsztajn, Oyallon and Varoquaux tested tree-based models and deep networks on 45 datasets and concluded that tree-based models remain state-of-the-art on medium-sized data (around 10,000 samples), even before counting their speed advantage. Their analysis points to three things deep networks struggle with on tables, which also describe where trees are strong:
- Uninformative features. Real tables often contain columns that mean nothing for the target. Trees simply ignore them; neural networks tend to be distracted.
- Axis alignment. In a table, each column has its own meaning (age, price, count), and rotating them together would destroy it. Trees split one feature at a time and respect that.
- Irregular functions. Tabular targets often jump (a discount threshold, a legal age) instead of changing smoothly. Trees represent steps naturally.
Add the practical side: XGBoost trains in seconds to minutes on a laptop, needs little preprocessing (no scaling, native missing-value handling) and gives feature importances. It's not magic, though, and the next sections cover where it loses.
XGBoost vs Random Forest
Both are ensembles of decision trees, which is why people ask "is XGBoost better than random forest?" The difference is how the trees are built and combined.
| Random forest | XGBoost | |
|---|---|---|
| Ensemble style | Bagging: many deep trees trained independently on random samples, then averaged | Boosting: many shallow trees built one after another, each correcting the last |
| Trees | Deep, low bias, high variance each | Shallow (default depth 6), high bias each |
| What reduces error | Averaging reduces variance | Sequential fitting reduces bias; regularization controls variance |
| Training | Easy to parallelise across trees | Trees are sequential, but split search inside each tree is parallel |
| Tuning needed | Little: works well near defaults | More: learning rate, depth, number of trees, regularization |
| Overfitting risk | Low; more trees rarely hurt | Higher; needs early stopping and regularization |
| Typical accuracy | Strong baseline | Often a few points better when tuned |
| Missing values | Often needs imputation | Handled natively |
Is XGBoost better than random forest? Usually slightly more accurate when tuned, but not always, and random forest is harder to get wrong. A sensible workflow is to start with a random forest as a sturdy baseline, then try XGBoost and keep it only if it wins on a proper validation set. The related trade-off between a model that is too simple and one that is too flexible is covered in our bias-variance tradeoff guide.
XGBoost vs LightGBM vs CatBoost
XGBoost has two close relatives, and any of the three is a good choice for tabular data.
| XGBoost | LightGBM | CatBoost | |
|---|---|---|---|
| Tree growth | Level-wise by default (depth-limited) | Leaf-wise (best-first): grows the leaf with the biggest loss reduction | Symmetric (oblivious) trees |
| Speed | Fast, especially with histogram and GPU | Built for speed and low memory use on large data | Fast, especially on GPU |
| Categorical features | Supported when enabled | Native optimal splits, no one-hot needed | Specialty: ordered target statistics and ordered boosting |
| Small-data caution | Standard regularization | Leaf-wise growth can overfit small data; limit depth and leaves | Defaults are strong out of the box |
| Best known for | Ecosystem, stability, documentation | Speed and memory efficiency | Categorical data and good defaults |
LightGBM's documentation notes that leaf-wise growth can reach lower loss than level-wise growth for the same number of leaves but may overfit when the data is small. CatBoost's paper introduced ordered boosting to remove a prediction shift caused by target leakage in standard boosting. In practice, pick one, tune it properly and compare only if the result matters; the differences between well-tuned libraries are usually smaller than the gains from better features.
XGBoost Parameters Explained
Most XGBoost parameters fall into three groups: how big each tree is, how strongly to regularize and how fast to learn. These are the defaults from the official parameter documentation:
| Parameter | Default | What it does | Turn it which way to reduce overfitting |
|---|---|---|---|
eta (learning_rate) | 0.3 | Shrinks each tree's contribution | Lower (and use more trees) |
max_depth | 6 | Maximum depth of each tree | Lower |
min_child_weight | 1 | Minimum sum of hessian in a child; blocks tiny leaves | Higher |
gamma (min_split_loss) | 0 | Minimum loss reduction needed to split | Higher |
subsample | 1 | Fraction of rows used per round | Lower, such as 0.7 to 0.9 |
colsample_bytree | 1 | Fraction of columns used per tree | Lower, such as 0.5 to 0.9 |
lambda (reg_lambda) | 1 | L2 penalty on leaf values | Higher |
alpha (reg_alpha) | 0 | L1 penalty on leaf values | Higher |
tree_method | auto (same as hist) | How splits are found: exact, approx or hist | Not an overfitting knob |
max_bin | 256 | Number of histogram bins | Not an overfitting knob |
scale_pos_weight | 1 | Balances positive and negative classes | Set to negatives divided by positives for imbalanced classes |
objective | reg:squarederror | The task and loss, for example binary:logistic | Set per task |
The number of trees is set with n_estimators in the scikit-learn interface (or the number of boosting rounds in the native one). Don't tune it directly: set a large number and use early stopping on a validation set so training stops when the score stops improving. For a full step-by-step search recipe, see our hyperparameter tuning guide, which includes an XGBoost section.
A Minimal Python Example
The scikit-learn style interface looks like this. Early stopping is set in the constructor and the validation data is passed to fit, as in the official documentation:
import xgboost as xgb
from sklearn.model_selection import train_test_split
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, random_state=0
)
clf = xgb.XGBClassifier(
tree_method="hist",
learning_rate=0.05,
max_depth=4,
n_estimators=1000, # a ceiling; early stopping picks the real number
early_stopping_rounds=50,
)
clf.fit(X_train, y_train, eval_set=[(X_val, y_val)])XGBoost does not split the data for you, so you create the validation set yourself. With early stopping enabled, predict uses the best iteration automatically. For categorical columns, mark them with the pandas category dtype and pass enable_categorical=True to the estimator.
When Not to Use XGBoost
- Images, audio and text. These need neural networks, which learn their own features. Tree models need hand-made features, which is why deep learning dominates those areas.
- Very small datasets. With a few dozen rows, a regularized linear model is usually safer and easier to explain.
- Extrapolation. A tree predicts an average of training rows in a leaf, so it can never predict above the highest value it has seen. If prices will rise beyond your training range, a linear component or a different model is better.
- When you must explain every decision in plain words. A single decision tree or a linear model is easier to audit than hundreds of boosted trees, although importance scores and SHAP values help.
- Very high-dimensional sparse data with simple structure. Linear models are often as good and far cheaper.
Common Mistakes
- Tuning on the test set. Use a separate validation set for early stopping and keep the test set for one final check.
- Not using early stopping. A fixed 1,000 trees at a high learning rate almost always overfits.
- Leaking the target. A column built from the outcome (or from the future) gives spectacular scores that vanish in production. Check feature importance for suspiciously strong columns.
- Judging an imbalanced problem by accuracy. If 1% of rows are positive, a model that always says "negative" is 99% accurate. Use precision, recall or PR-AUC and consider
scale_pos_weight. - One-hot encoding a column with thousands of categories. It bloats the data. Use native categorical support or target-aware encoding with proper cross-validation.
- Chasing hyperparameters before fixing the data. Better features beat a finer grid almost every time.
FAQ
What is XGBoost used for?
XGBoost is used for prediction on structured, tabular data: fraud detection, churn and credit scoring, demand forecasting, ranking and click-through prediction, and as a strong entry in data science competitions. It supports regression, classification and learning to rank.
Is XGBoost supervised or unsupervised?
Supervised. It learns from labelled examples, where each row has a known target value, and then predicts targets for new rows.
Is XGBoost better than random forest?
Often a little more accurate after tuning, but it needs more tuning and can overfit if you skip early stopping. A random forest works well with defaults, so many practitioners start with it as a baseline and move to XGBoost for the last few points of accuracy.
Does XGBoost need feature scaling?
No. Trees split on thresholds, so scaling or normalising features doesn't change the result. XGBoost can also handle missing values directly by learning a default direction at each split.
What are the most important XGBoost parameters?
The learning rate (eta), the number of trees (use early stopping), max_depth, min_child_weight, subsample, colsample_bytree and the regularization terms lambda, alpha and gamma. Start with a low learning rate and tune depth and sampling first.