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.

By OmniAI Editorial · Nov 22, 2026 · 15 min read

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:

  1. Start with a simple prediction for every row, such as the average of the target.
  2. Measure the error of the current predictions (the gap between prediction and truth for each row).
  3. Fit a small tree whose job is to predict those errors from the features.
  4. 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.
  5. 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.

Four light panels in a row, each with a small grey tree at the top, a dotted ink target line and a solid ink line that sits lower in the first panel and closer to the target in each next one, ending with an orange dot on the target.
Each round adds a small tree that corrects what the earlier ones missed.

What the XGBoost Algorithm Adds

Plain gradient boosting already worked well. The XGBoost algorithm made it better and much faster through several changes:

FeatureWhat it doesWhy it matters
Regularized objectiveAdds a penalty for the number of leaves and for large leaf values (L2, and optionally L1)Prevents overfitting without extra tricks
Second-order optimizationUses both the gradient and the second derivative (hessian) of the loss to pick splits and leaf valuesMore accurate steps, fewer trees needed
Sparsity-aware splittingLearns a default direction for missing or zero entries at each splitHandles missing values without imputation
Histogram split findingGroups feature values into bins (256 by default) and searches splits over binsMuch faster on large data; the default method
Row and column subsamplingEach tree sees a random share of rows and featuresReduces overfitting and speeds training
Parallel, cache-aware designSorts data once into column blocks, parallelises split searchScales to very large datasets
Categorical supportSplits directly on pandas category columns when enabledLess 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) ] - gamma

where 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.

HouseSizePricePredictiong (prediction minus price)h
A50101661
B60121641
C802016-41
D902216-61

Set lambda to 1 and gamma to 0. XGBoost tries a split between each pair of neighbouring sizes:

SplitGLHLGRHRGain
Between 50 and 6061-630.5 x (36/2 + 36/4 - 0) = 13.5
Between 60 and 80102-1020.5 x (100/3 + 100/3 - 0) = 33.3
Between 80 and 9063-610.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.

Two light panels: on the left a grey tree whose root splits into two square leaves with an orange bar under the right leaf, on the right three grey bars of growing height beside a dotted outline for the next one.
One split, chosen by gain, with a leaf value shrunk by the learning rate.

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 forestXGBoost
Ensemble styleBagging: many deep trees trained independently on random samples, then averagedBoosting: many shallow trees built one after another, each correcting the last
TreesDeep, low bias, high variance eachShallow (default depth 6), high bias each
What reduces errorAveraging reduces varianceSequential fitting reduces bias; regularization controls variance
TrainingEasy to parallelise across treesTrees are sequential, but split search inside each tree is parallel
Tuning neededLittle: works well near defaultsMore: learning rate, depth, number of trees, regularization
Overfitting riskLow; more trees rarely hurtHigher; needs early stopping and regularization
Typical accuracyStrong baselineOften a few points better when tuned
Missing valuesOften needs imputationHandled 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.

XGBoostLightGBMCatBoost
Tree growthLevel-wise by default (depth-limited)Leaf-wise (best-first): grows the leaf with the biggest loss reductionSymmetric (oblivious) trees
SpeedFast, especially with histogram and GPUBuilt for speed and low memory use on large dataFast, especially on GPU
Categorical featuresSupported when enabledNative optimal splits, no one-hot neededSpecialty: ordered target statistics and ordered boosting
Small-data cautionStandard regularizationLeaf-wise growth can overfit small data; limit depth and leavesDefaults are strong out of the box
Best known forEcosystem, stability, documentationSpeed and memory efficiencyCategorical 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:

ParameterDefaultWhat it doesTurn it which way to reduce overfitting
eta (learning_rate)0.3Shrinks each tree's contributionLower (and use more trees)
max_depth6Maximum depth of each treeLower
min_child_weight1Minimum sum of hessian in a child; blocks tiny leavesHigher
gamma (min_split_loss)0Minimum loss reduction needed to splitHigher
subsample1Fraction of rows used per roundLower, such as 0.7 to 0.9
colsample_bytree1Fraction of columns used per treeLower, such as 0.5 to 0.9
lambda (reg_lambda)1L2 penalty on leaf valuesHigher
alpha (reg_alpha)0L1 penalty on leaf valuesHigher
tree_methodauto (same as hist)How splits are found: exact, approx or histNot an overfitting knob
max_bin256Number of histogram binsNot an overfitting knob
scale_pos_weight1Balances positive and negative classesSet to negatives divided by positives for imbalanced classes
objectivereg:squarederrorThe task and loss, for example binary:logisticSet 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.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog