Sub topic 15
Handling missing values
This chapter assumes you can train a LightGBM or CatBoost model with a validation set, as covered in the earlier training chapters. It also assumes you know pandas NaN and basic imputation. It covers how each library treats missing values, how to check that behavior, and where it fails.
Why trees can skip imputation
Linear models and neural networks need a number in every cell, so you must impute. A decision tree only asks whether a feature is above or below a threshold. Both libraries add a rule for rows where the feature is missing, so they can learn from NaN directly.
This matters because missingness often carries signal. A blank income field on a loan application can mean something different from a low income. Mean imputation hides that difference. Native handling keeps it.
How LightGBM handles missing values
LightGBM treats NaN as missing by default (use_missing=true). Missing values are left out of the sorted histogram bins. At each candidate split, LightGBM evaluates two options:
- Send all missing rows to the left child.
- Send all missing rows to the right child.
It keeps the direction with the higher gain. That direction is stored in the tree as the default direction for that split. Different splits on the same feature can choose different directions.
Three parameters change this behavior:
| Parameter | Default | Effect |
|---|---|---|
| `use_missing` | `true` | If `false`, LightGBM does not learn a missing direction and treats missing values as zero. |
| `zero_as_missing` | `false` | If `true`, zeros and `NaN` are both treated as missing. |
| `feature_pre_filter` | `true` | Drops features that cannot be split. This can remove a feature that is nearly all missing. |
Be careful with zero_as_missing=true. It is meant for sparse data, where zero means "not recorded". On dense data it merges genuine zeros with missing values.
A feature with no missing values in training is a special case. LightGBM records that it saw none. At prediction time a NaN in that feature is converted to zero and follows whatever path zero takes. It does not get a learned direction.
How CatBoost handles missing values
CatBoost controls numeric missing values with the nan_mode parameter:
| `nan_mode` | Behavior |
|---|---|
| `Min` (default) | Missing is treated as smaller than every observed value. |
| `Max` | Missing is treated as larger than every observed value. |
| `Forbidden` | Training and prediction raise an error if a missing value appears. |
Min and Max do not learn a direction per split. Missing values are placed at one end of the feature's ordering, and every split on that feature treats them the same way. A split such as x > 3.2 therefore always sends missing rows to the same side. CatBoost can still separate missing rows from the rest by splitting at a border just above the missing group. In practice the two designs perform similarly, but you cannot rely on CatBoost to place missing values differently in different parts of the tree.
Forbidden is useful in pipelines where a NaN means an upstream bug and you want training to fail.
Categorical features need explicit handling in CatBoost
Numeric NaN is fine. Categorical columns are different. CatBoost requires cat_features to hold strings or integers, and a missing value in a categorical column can raise an error about real number or NaN values. Behavior varies by version, so do not depend on it. Fill the column with an explicit label:
import pandas as pd
from catboost import Pool
df = pd.DataFrame({
"city": ["A", None, "B", "A"],
"age": [30, 41, None, 25],
})
df["city"] = df["city"].fillna("missing").astype(str)
pool = Pool(df, label=[0, 1, 0, 1], cat_features=["city"])
print(pool.shape)The label "missing" becomes an ordinary category with its own target statistic. The model can learn that this category behaves differently. Keep the numeric column age as it is.
LightGBM treats NaN and negative integer codes in categorical columns as missing, so no special fill is required. In pandas, category columns store missing values as code -1, which LightGBM reads as missing. Missing categorical values in LightGBM are grouped with categories not seen in training.
Comparing native handling with imputation
The script below builds data where the chance of a missing value depends on the label. This is the case where native handling should help. It trains three models and prints validation AUC.
import numpy as np
import pandas as pd
import lightgbm as lgb
from catboost import CatBoostClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 6000
x = rng.normal(size=n)
z = rng.normal(size=n)
y = (x + 0.5 * z + rng.normal(scale=0.5, size=n) > 0).astype(int)
# Positives lose x much more often than negatives.
is_missing = rng.random(n) < np.where(y == 1, 0.4, 0.1)
df = pd.DataFrame({"x": np.where(is_missing, np.nan, x), "z": z})
X_train, X_valid, y_train, y_valid = train_test_split(
df, y, test_size=0.2, random_state=0
)
def lgb_auc(train, valid):
model = lgb.LGBMClassifier(n_estimators=300, learning_rate=0.05, verbose=-1)
model.fit(train, y_train)
return roc_auc_score(y_valid, model.predict_proba(valid)[:, 1])
print("LightGBM native NaN:", lgb_auc(X_train, X_valid))
mean_x = X_train["x"].mean()
print(
"LightGBM mean-imputed:",
lgb_auc(X_train.fillna({"x": mean_x}), X_valid.fillna({"x": mean_x})),
)
cb = CatBoostClassifier(iterations=300, learning_rate=0.05, nan_mode="Min", verbose=0)
cb.fit(X_train, y_train)
print("CatBoost nan_mode=Min:", roc_auc_score(y_valid, cb.predict_proba(X_valid)[:, 1]))The imputation statistic comes from the training split only. Computing it on the full dataset leaks validation information, which matches the validation rules from the first chapter. Exact scores depend on library versions, so compare the three numbers on your machine instead of expecting fixed values.
Common errors
- Imputing with a sentinel such as -999. Trees can handle it, but it hides the missing signal inside a numeric range. It can also fall in the same bin as other low values. Use
NaN. - Sentinels that look like real values. Fields like
0,-1or9999often mean "unknown". Convert them toNaNbefore training, or LightGBM and CatBoost will treat them as real numbers. - Missingness that differs between training and production. A learned missing direction is only useful if the missing pattern stays similar. If a source system starts sending zeros instead of blanks, predictions degrade without any error.
- Dropping the missing indicator mentally. If you impute for another model in an ensemble, add an
is_missingcolumn so the signal is not lost. - Mixing
zero_as_missingbetween training and prediction. Set it inparamsonce and keep it with the saved model.
Checklist
- Convert placeholder values to
NaN. - Leave numeric
NaNin place for both libraries, and usenan_mode="Forbidden"in CatBoost if gaps should never occur. - Fill categorical
NaNwith an explicit string for CatBoost. - Fit any imputer on training data only.
- Compare missing rates between training and serving data.
Exercise
A CatBoost model raises an error when Pool is created with cat_features=["city"], and the city column contains NaN. What should you change, and why is the same step not required for a numeric column such as age?
Show answer
Replace the missing city values with an explicit string, for example df["city"] = df["city"].fillna("missing").astype(str). CatBoost requires categorical features to be strings or integers, and the filled label then becomes its own category with its own target statistic. Numeric columns are handled by nan_mode, which by default (Min) places NaN below every observed value, so no fill is needed.