Sub topic 13
Missing values and categorical features
This chapter assumes you can train an XGBClassifier with the scikit-learn API and know what a split in a decision tree is. It also assumes you have read the earlier chapters on the regularized objective and on split finding. You will see how XGBoost handles gaps in your data without imputation, how it splits on categorical columns directly, and which mistakes cause silent errors.
How XGBoost treats missing values
XGBoost does not require you to fill in missing values. Each split in a tree stores a default direction, left or right. A row whose value for the split feature is missing follows that direction.
The default direction is learned during training. For each candidate split, XGBoost computes the gain twice: once with all missing rows sent left, once with them sent right. It keeps the better option. Because the gradient and hessian sums of the missing rows are included in that calculation, the choice is data-driven. It is not a fixed rule such as "missing goes left".
This has two practical consequences:
- Missingness can carry signal. If missing values correlate with the label, for example applicants who skip an income field, the trees can use that. Imputing with the mean would hide the pattern.
- Each split decides separately. Missing values can go left in one tree and right in another.
If a feature had no missing values during training, a missing value at prediction time still follows a default child. Nothing in training told the model what that case means, so treat the result as a guess. Check for this kind of drift before you deploy.
What counts as "missing"
By default, XGBoost treats NaN as missing. The missing parameter changes the marker value. In the scikit-learn API you pass it to the estimator. In the native API you pass it to DMatrix.
Two cases can surprise you:
- Sparse matrices. When you build a
DMatrixfrom a SciPy sparse matrix, entries that are not stored are treated as missing, not as zero. If a zero is meaningful in your data, such as a count of zero, convert it with care. One option is to store explicit zeros. Another is to use a dense array. - Sentinel values. Some datasets encode missing as
-999or0. If you do not setmissing=-999, XGBoost reads-999as a real, very small number. The model still trains, but it splits on the number and no longer treats the row as missing.
Categorical features
Tree models usually need categories turned into numbers. One-hot encoding creates one column per category. Integer coding imposes a false order. XGBoost can instead split on a categorical column directly. A categorical split sends a set of categories to one child and the remaining categories to the other. For example: "city is in {lima, pune} goes left".
To use this:
- Store the column with the pandas
categorydtype. - Pass
enable_categorical=True. - Use a tree method that supports it.
histis the usual choice. In current XGBoost it is the default, but setting it explicitly makes the code clearer.
Columns with an integer dtype are treated as numeric, even if the numbers are labels. Convert them to category first.
A worked example with both features
The example below builds a dataset with a missing-at-random-looking income column. Missingness is more likely for positive rows, so it carries signal. It also has a categorical city column. The code trains with early stopping, then reports AUC on a held-out test set.
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
rng = np.random.default_rng(0)
n = 6000
income = rng.normal(50, 15, n)
city = rng.choice(["berlin", "lagos", "lima", "oslo", "pune"], n)
city_effect = pd.Series(city).map(
{"berlin": 0.0, "lagos": 0.8, "lima": -0.8, "oslo": 0.0, "pune": 0.8}
).to_numpy()
logit = 0.05 * (income - 50) + city_effect
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
# Missingness is informative: positives lose their income value more often.
mask = rng.random(n) < np.where(y == 1, 0.4, 0.1)
income[mask] = np.nan
X = pd.DataFrame({"income": income, "city": pd.Categorical(city)})
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.2, stratify=y_train, random_state=0
)
model = XGBClassifier(
n_estimators=1000,
learning_rate=0.05,
max_depth=3,
tree_method="hist",
enable_categorical=True,
eval_metric="auc",
early_stopping_rounds=30,
)
model.fit(X_fit, y_fit, eval_set=[(X_val, y_val)], verbose=False)
proba = model.predict_proba(X_test)[:, 1]
print("best iteration:", model.best_iteration)
print("test AUC:", round(roc_auc_score(y_test, proba), 3))The data has three splits. The fitting part trains the trees, the validation part drives early stopping, and the test part gives an unbiased score.
You could try the same data with the mean imputed into income. Imputing removes the missingness signal, so the AUC usually drops.
The native API equivalent
In the native API, DMatrix takes the same two switches:
import xgboost as xgb
dtrain = xgb.DMatrix(X_fit, label=y_fit, enable_categorical=True)
dval = xgb.DMatrix(X_val, label=y_val, enable_categorical=True)
params = {"objective": "binary:logistic", "eval_metric": "auc",
"eta": 0.05, "max_depth": 3, "tree_method": "hist"}
booster = xgb.train(params, dtrain, num_boost_round=1000,
evals=[(dval, "val")], early_stopping_rounds=30,
verbose_eval=False)
print(booster.best_iteration)If your data is a NumPy array, there is no dtype to carry the category information. Pass feature_types to DMatrix, using "c" for categorical and "q" for numeric columns. The categorical values must be non-negative integers starting at 0.
Controlling categorical splits
Two parameters shape how categorical splits are built:
| Parameter | Effect |
|---|---|
| `max_cat_to_onehot` | If a feature has fewer categories than this value, XGBoost uses one-vs-rest splits ("this category versus all others"). Above it, XGBoost searches for a good partition of the categories. |
| `max_cat_threshold` | Caps how many categories can be placed on one side of a partition split. This limits the cost and the overfitting risk of the partition search. |
Partition search is powerful but easy to overfit when a column has hundreds of levels, and many of them are rare. Each rare category gives the tree another way to memorize a few rows. Useful safeguards are a larger min_child_weight, a nonzero gamma, stronger reg_lambda, and grouping rare levels into an "other" category before training.
Common errors
- Forgetting
enable_categorical=True. With a pandascategorycolumn, XGBoost raises an error asking you to enable it. With integer-coded columns there is no error, and the model treats them as ordered numbers. - Encoding train and test separately. If you build category codes independently on each set, the same code can mean different cities. Define the categories once, for example with
pd.Categorical(values, categories=known_levels), and reuse them at inference time. - Unseen categories at prediction time. Test how your XGBoost version handles a level absent from training before you rely on it. Do not assume it behaves like a known level.
- Imputing by habit. Imputation is sometimes right, for example when the missing value is a data-entry error and carries no information. Decide per column. Do not apply it everywhere.
- Using a tree method that lacks support. If categorical training fails with a message about the tree method, set
tree_method="hist".
Exercise
A feature age encodes missing values as -1. You train an XGBClassifier with default settings and a pandas DataFrame. What goes wrong, and how do you fix it?
Show answer
XGBoost only treats NaN as missing by default, so -1 is read as a real numeric value, and the model may split on it as if it were a very young age. The model trains without any error. Fix it by passing missing=-1 to XGBClassifier (or to DMatrix), or by replacing -1 with np.nan before training. If a real age of -1 is impossible, as it is here, either fix is safe.
Exercise
A column zip_group holds the integers 0 to 11, which are labels for areas. You train with enable_categorical=True and see no categorical splits in the trees. Why, and what should you change?
Show answer
Integer columns are treated as numeric, so enable_categorical=True has no effect on them. Convert the column with X["zip_group"] = X["zip_group"].astype("category") before training, and make sure the same category definition is used for the test data.