Sub topic 15
Handling missing values
This chapter assumes you can train a LightGBM or CatBoost model with a validation set, as shown in the earlier training chapters. It covers how each library treats missing values and which preprocessing mistakes to avoid.
Trees can use missing values directly
Both libraries accept NaN in numeric columns. You usually don't need to impute. Imputing with the mean or a sentinel such as -999 can hide a useful signal, because "this value is missing" is often informative. A missing income field, for example, may correlate with the label.
How LightGBM handles them
During split finding, LightGBM evaluates each candidate threshold twice. In one pass the missing rows go left, and in the other they go right. It keeps the direction with the higher gain and stores it as the node's default direction. At prediction time, a missing value follows that stored direction.
Two parameters control this:
use_missing=True(default) turns the behavior on.zero_as_missing=False(default) means onlyNaNcounts as missing. If you set it toTrue, zeros are also treated as missing. Use that only when zeros in your data really mean "absent", as in some sparse matrices.
How CatBoost handles them
CatBoost's nan_mode parameter decides where NaN goes in a numeric feature:
| Value | Behavior |
|---|---|
| `"Min"` (default) | `NaN` is treated as smaller than every observed value |
| `"Max"` | `NaN` is treated as larger than every observed value |
| `"Forbidden"` | Training raises an error if `NaN` appears |
Because missing rows sit at one end of the feature's range, a single split can always separate them from the rest.
Comparing the two
The synthetic data below makes missingness informative: rows with a missing x get a higher target.
import numpy as np
import pandas as pd
import lightgbm as lgb
from catboost import CatBoostRegressor
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 4000
x = rng.normal(size=n)
missing = rng.random(n) < 0.3
y = 2 * x + 3 * missing + rng.normal(scale=0.3, size=n)
X = pd.DataFrame({"x": np.where(missing, np.nan, x)})
X_train, X_valid, y_train, y_valid = train_test_split(
X, y, test_size=0.2, random_state=0
)
lgb_model = lgb.LGBMRegressor(n_estimators=200, verbose=-1)
lgb_model.fit(X_train, y_train)
cb_model = CatBoostRegressor(iterations=200, nan_mode="Min", verbose=0)
cb_model.fit(X_train, y_train)
print("LightGBM R2:", r2_score(y_valid, lgb_model.predict(X_valid)))
print("CatBoost R2:", r2_score(y_valid, cb_model.predict(X_valid)))Both models score well without any imputation, because each can isolate the missing rows with a split.
Categorical columns
Treat categorical columns separately from numeric ones.
- In LightGBM,
NaNin a pandascategorycolumn is treated as missing. Negative integer codes are also treated as missing. - In CatBoost, fill missing values in
cat_featurescolumns with an explicit string such as"missing". This avoids version-dependent errors and makes the missing group its own category with its own target statistic.
Common errors
- Fitting an imputer on all the data. Compute imputation statistics on the training split only, or you leak validation information.
- Missingness that differs between training and production. If a field was always filled in training but is often empty in production, the model never learned a default direction for it. Check the missing rate per feature in both datasets.
- Setting
zero_as_missing=Trueby accident. Real zeros then get routed like missing values. - Using
nan_mode="Forbidden"and being surprised by errors. That mode is for catching unexpectedNaN, not for handling it.
Exercise
A numeric column in your LightGBM model contains many real zeros that mean "none purchased", plus some NaN values meaning "not recorded". Should you set zeroasmissing=True? Why or why not?
Show answer
No. With zeroasmissing=True, the real zeros would be treated as missing and share a default direction with the NaN rows, so the model could no longer tell "none purchased" from "not recorded". Keep the default (False) so only NaN is treated as missing.