Sub topic 9
Categorical Features in LightGBM
This chapter assumes you can train a LightGBM model with lgb.train or the scikit-learn API, and that you know what early stopping does. You should also know why one-hot encoding grows wide for columns with many values. The chapter covers how LightGBM splits on categories, how to declare them, which parameters control the splitting, and the errors that come up most often.
Why categoricals need special handling
A categorical feature is a column whose values are labels with no natural order, such as city or plan. If you map labels to integers (A=0, B=1, C=2) and give the integers to a tree, every split has the form code <= t. The tree can then only group neighbouring codes, and the grouping depends on an arbitrary numbering.
One-hot encoding avoids this by giving each value its own 0/1 column. A split such as city == A isolates one value. This has two costs:
- A column with 1,000 values becomes 1,000 sparse columns.
- Each split can only separate one value from all the others. A tree needs many splits to isolate a group like {A, C, F}, and the later splits see less data.
LightGBM can instead split a categorical feature into two arbitrary subsets of values in a single split.
Declaring categorical features
LightGBM has no way to guess that an integer column is categorical. You have to declare it. The options differ by API.
| Situation | How LightGBM treats the column |
|---|---|
| pandas column with dtype `category` | Treated as categorical automatically (`categorical_feature="auto"`) |
| pandas column with dtype `object` or `str` | Raises an error. Convert it to `category` first |
| Integer column in a NumPy array | Treated as numeric unless you list it in `categorical_feature` |
| Column listed in `categorical_feature` | Treated as categorical, by name or by index |
The second example in the topic spine relies on the first row of this table. The city and plan columns are pandas category dtype, so lgb.Dataset picks them up without extra arguments.
import numpy as np
import pandas as pd
import lightgbm as lgb
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["age"] > 55)
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
)
train_set = lgb.Dataset(X_train, label=y_train)
valid_set = lgb.Dataset(X_valid, label=y_valid, reference=train_set)
params = {"objective": "binary", "metric": "auc", "verbose": -1}
booster = lgb.train(
params,
train_set,
num_boost_round=500,
valid_sets=[valid_set],
callbacks=[lgb.early_stopping(50, verbose=False)],
)
dump = booster.dump_model()
print(dump["feature_names"])
print(dump["pandas_categorical"])The last two lines show what LightGBM recorded. pandas_categorical stores the category lists seen at training time, which matters later at prediction time.
For the scikit-learn API, pass the same kind of DataFrame to fit. You can also set categorical_feature explicitly in fit, for example model.fit(X, y, categorical_feature=["city", "plan"]).
How LightGBM finds a categorical split
For a numeric feature, LightGBM tries thresholds over histogram bins. For a categorical feature, it uses a method based on the gradient statistics of each category.
- For each category value, compute the sum of gradients and the sum of hessians over the rows in the current leaf.
- Sort the categories by
sum_gradient / (sum_hessian + cat_smooth). - Scan this sorted order as if it were a numeric feature, looking for the best split point.
- The left child receives the categories before the split point, and the right child receives the rest.
Sorting by gradient statistics is an exact shortcut for finding the best two-way partition for common losses. It avoids checking all 2^(k-1) − 1 subsets of k categories. The cost is a sort per feature per leaf, which is the reason categorical splits are somewhat slower than numeric ones.
Parameters that control categorical splits
These parameters guard against overfitting on rare categories. A category seen in 3 rows has a very noisy gradient average, and a flexible tree will happily memorize it.
| Parameter | Default | Effect |
|---|---|---|
| `cat_smooth` | 10 | Adds smoothing to the sort statistic. Larger values reduce noise for rare categories |
| `min_data_per_group` | 100 | Minimum number of rows a category needs to be considered in a split |
| `cat_l2` | 10 | Extra L2 regularization on categorical splits |
| `max_cat_threshold` | 32 | Maximum number of categories in the left group of a split |
| `max_cat_to_onehot` | 4 | When a feature has this many values or fewer, LightGBM uses one-vs-rest splits instead |
Two details deserve attention.
First, max_cat_to_onehot means that low-cardinality features such as plan with three values do not use the sorted scan. LightGBM tries each value against the rest. The sorted method applies only to features with more values than the threshold.
Second, min_data_per_group is 100 by default. On a small dataset, many categories fall under that limit and are not used as split candidates. If you see a categorical feature with zero importance on a small dataset, lower this value (and cat_smooth) before concluding the feature is useless.
params = {
"objective": "binary",
"metric": "auc",
"min_data_per_group": 20,
"cat_smooth": 20,
"cat_l2": 10,
"max_cat_threshold": 16,
"verbose": -1,
}Unseen and missing categories
At prediction time you may see a category that did not appear in training. LightGBM sends unseen values to the right child at every categorical split, which behaves like "none of the categories chosen for the left group". This is deterministic but it is not informed by data, so a model's behaviour on new categories is a weak default and not a prediction you can rely on.
Missing values in a categorical column (NaN in pandas, which becomes code −1) are also routed to the right child. Negative integer codes are treated as missing. Chapter content on missing values later in the plan covers this in more detail.
Common errors
- Mismatched category lists between train and test. If you convert
citytocategoryseparately for the training and test frames, the integer codes can differ, and predictions silently go wrong. Build the category dtype once and reuse it:
cities = pd.CategoricalDtype(["A", "B", "C", "D"])
X_train["city"] = X_train["city"].astype(cities)
X_valid["city"] = X_valid["city"].astype(cities)- Integer codes that are huge or non-contiguous. LightGBM expects non-negative integers, and it allocates based on the largest value. Codes such as user IDs in the millions waste memory and produce a very large histogram. Use
categorydtype or remap to dense codes. - High-cardinality ID columns. A categorical feature with thousands of values, such as a customer ID, lets the tree memorize individual rows. Validation scores fall while training scores rise. Raise
min_data_per_groupandcat_smooth, or drop the column. - Forgetting to declare an integer column. A column of codes like
0, 1, 2, 3treated as numeric will train without any error and give a worse model than expected. - Using strings. An
objectcolumn makes LightGBM raise aValueErrorabout unsupported dtypes. Convert it with.astype("category").
Checking that it worked
Compare the same model with the column declared categorical and with it treated as numeric codes. If the categorical version does not beat the numeric one on validation AUC, the column may have little signal, or the regularization parameters may be too strict for your data size. Also inspect feature importance by split and by gain. A categorical feature with many splits but little gain is a sign of overfitting.
Exercise
You train a LightGBM model on a 2,000-row dataset with a categorical column region that has 40 values, each with about 50 rows. The feature importance for region is exactly zero, although you expect it to matter. Which parameter do you check first, and why?
Show answer
Check min_data_per_group. Its default is 100, and every region value has only about 50 rows, so none of them qualifies as a split candidate. Lowering it (for example to 20), and possibly lowering cat_smooth, lets the categories take part in splits. You should then confirm on the validation set that the change helps and does not just memorize rare categories.
Exercise
A model trained on a pandas DataFrame gives good validation scores, but accuracy drops sharply in production, where the data is converted to category dtype on each batch. What is the likely cause and the fix?
Show answer
Converting category dtype separately on each batch produces different integer codes for the same labels when the set of values differs between batches. The model learned the training code mapping, so predictions are wrong without any error. Define a fixed pd.CategoricalDtype with the full list of categories and apply it to every dataset, or rely on a pipeline that stores the training categories.