Sub topic 9
Categorical features in LightGBM
This chapter assumes you can train a LightGBM model with early stopping, as covered in the previous chapter. It also assumes you know pandas dtypes and why one-hot encoding widens a table.
Why not one-hot encode?
One-hot encoding turns a column with 1,000 categories into 1,000 sparse columns. Each column can only split off one category at a time, so trees must grow deep to group categories. LightGBM instead splits on a whole subset of categories in a single node.
How the split works
For a categorical feature, LightGBM computes the gradient statistic sum_gradient / (sum_hessian + cat_smooth) for each category. It sorts the categories by that value and scans the sorted list for the best split point, as it does for a numeric feature. The categories on one side of the split go left, and all others go right.
The sorting step means the search checks about k candidate splits instead of 2^k. The cost is that the statistic uses training targets, so rare categories can overfit.
Declaring categorical columns
With pandas, give the column the category dtype. LightGBM detects it automatically.
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 5000
df = pd.DataFrame({
"age": rng.integers(18, 70, n),
"city": pd.Categorical(rng.choice(["A", "B", "C", "D"], n)),
"plan": pd.Categorical(rng.choice(["free", "basic", "pro"], n)),
})
signal = (df["plan"] == "pro") | (df["city"].isin(["A", "C"]))
flip = rng.random(n) < 0.1
y = (signal ^ flip).astype(int)
X_train, X_valid, y_train, y_valid = train_test_split(
df, y, test_size=0.2, random_state=0
)
model = lgb.LGBMClassifier(
n_estimators=500,
learning_rate=0.05,
cat_smooth=10,
min_data_per_group=50,
verbose=-1,
)
model.fit(
X_train,
y_train,
eval_set=[(X_valid, y_valid)],
eval_metric="auc",
callbacks=[lgb.early_stopping(50, verbose=False)],
)
pred = model.predict_proba(X_valid)[:, 1]
print(model.best_iteration_, roc_auc_score(y_valid, pred))If your data is not in pandas, pass categorical_feature=[...] to fit or to lgb.Dataset. The columns must hold non-negative integers.
Parameters that control overfitting
| Parameter | Default | Effect |
|---|---|---|
| `cat_smooth` | 10 | Smooths the statistic for categories with few rows. Raise it for noisy, rare categories. |
| `min_data_per_group` | 100 | Minimum rows per category group in a split. |
| `max_cat_threshold` | 32 | Maximum number of categories on one side of a split. |
| `cat_l2` | 10 | Extra L2 regularization on categorical splits. |
| `max_cat_to_onehot` | 4 | At or below this many categories, LightGBM uses one-vs-rest splits instead. |
Common errors
- Integer codes that are negative are treated as missing values.
- Large integer codes waste memory. Use contiguous codes starting at 0.
- Validation data must share the training categories. With
lgb.Dataset, passreference=train_set. With pandas, use the same category lists. - Categories unseen during training are never in a split's left group, so they go right.
- High-cardinality columns such as user IDs overfit easily. Raise
cat_smoothandmin_data_per_group, or drop the column.
Exercise
A categorical column has 5,000 distinct values, and most appear fewer than 10 times. Validation AUC is far below training AUC. Name two parameters to change and the direction for each.
Show answer
Raise cat_smooth and raise min_data_per_group. Both make splits on rare categories harder to justify, which reduces overfitting. Raising cat_l2 or lowering max_cat_threshold also helps.