Sub topic 13
Missing values and categorical features
This chapter assumes you can train an XGBClassifier and know what a split in a tree is. It covers how XGBoost handles missing entries and how it splits on categorical columns without one-hot encoding.
Missing values are learned, not imputed
XGBoost treats NaN as "missing" by default. You do not need to impute it first. During training, each split learns a default direction. For a candidate split, the algorithm sends all rows with a missing value left, computes the gain, then sends them right and computes the gain again. It keeps the better direction. At prediction time, a row with a missing value in that feature follows the stored direction.
Each split learns its own default, so missingness can carry signal. If "income not reported" correlates with the label, the trees can use that.
Pitfalls with missing values
- Filling gaps with a sentinel such as
-999hides them. XGBoost then treats-999as an ordinary number. - The
missingparameter changes which value counts as missing. The default isNaN. - In a scipy sparse matrix, entries that are not stored are treated as missing, not as zero. Store explicit zeros if zero is a real value.
- Training data without missing values still works. Any missing value seen at prediction time goes to the default direction, which is arbitrary in that case.
Native categorical support
Encoding a high-cardinality column as one-hot creates many sparse columns and deep trees. XGBoost can instead split on category sets directly. Use a pandas column with category dtype, set enable_categorical=True, and use a histogram-based tree method.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
rng = np.random.default_rng(0)
n = 2000
df = pd.DataFrame({
"income": rng.normal(50, 15, n),
"city": pd.Categorical(rng.choice(["a", "b", "c", "d"], n)),
})
df.loc[rng.random(n) < 0.2, "income"] = np.nan # 20% missing
y = ((df["income"].fillna(30) > 45) ^ df["city"].isin(["a", "b"])).astype(int)
X_train, X_test, y_train, y_test = train_test_split(
df, y, test_size=0.2, random_state=0
)
model = XGBClassifier(
n_estimators=100,
max_depth=3,
tree_method="hist",
enable_categorical=True,
)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))The model receives the NaN values in income as they are. It splits city on a learned subset of categories, such as {a, b} against the rest.
Gotchas with categories
- Categories must be encoded consistently. Use the same category list for training and test data, for example by fitting a
pd.CategoricalDtypeonce and reusing it. - Columns with many categories can overfit, because there are many possible subsets to split on. Raise
min_child_weightorreg_lambda, or group rare categories. - For columns with few categories, XGBoost uses one-hot style splits.
max_cat_to_onehotcontrols this threshold. - Plain
objectstring columns are not accepted. Convert them tocategoryfirst.
Exercise
A feature is missing for 30% of rows. A teammate fills it with -1 before training, and the feature is a nonnegative amount. Why can this hurt, and what do you do instead?
Show answer
The value -1 becomes a normal number, so trees must find a threshold such as "< 0" to isolate those rows. That uses up splits and mixes missingness with real ordering. Leave the values as NaN and let each split learn a default direction.