Sub topic 14
Training CatBoost with Pool and cat_features
This chapter assumes you know Python and pandas, what a train/validation split is, and metrics such as AUC. It also assumes you have read the earlier chapters on early stopping and on CatBoost's ordered target statistics. Here you put those ideas into a training script.
The Pool object
A Pool is CatBoost's dataset container. It holds features, labels and the list of categorical columns together. Declaring the categorical columns once in the Pool means CatBoost knows to encode them with ordered target statistics. You do not one-hot encode or label-encode them yourself.
cat_features accepts column names (with a DataFrame) or integer column indices. A categorical column must hold strings or integers. Float columns are rejected, so cast them first.
A full training run
import numpy as np
import pandas as pd
from catboost import CatBoostClassifier, Pool
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": rng.choice(["A", "B", "C", "D"], n),
"plan": 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
)
cat_features = ["city", "plan"]
train_pool = Pool(X_train, y_train, cat_features=cat_features)
valid_pool = Pool(X_valid, y_valid, cat_features=cat_features)
model = CatBoostClassifier(
iterations=1000,
learning_rate=0.1,
depth=6,
eval_metric="AUC",
verbose=100,
)
model.fit(train_pool, eval_set=valid_pool, early_stopping_rounds=50)
print(model.get_best_iteration())The script follows these steps:
- It builds two Pools with the same
cat_features. - It sets
iterationshigh and lets early stopping choose the real number of trees. - It passes the validation Pool as
eval_set. When an eval set is given, CatBoost keeps the model at the best iteration by default (use_best_model=True), so predictions use the best trees, not the last ones.
Common errors
- String column not declared. If a string column is missing from
cat_features, CatBoost fails because it cannot convert the strings to numbers. - Float categorical column. Convert with
.astype(str)or to an integer type. - Missing categories. Use
fillna("missing")on categorical columns first. CatBoost does not accept NaN in them. - Validation Pool declared differently. Both Pools must use the same
cat_features.
Exercise
Your DataFrame has a column "zip_code" stored as floats such as 94105.0. You want CatBoost to treat it as categorical. What two things must you do before calling fit?
Show answer
Convert the column to a string or integer type, for example df["zipcode"] = df["zipcode"].astype(int).astype(str). Then add "zipcode" to catfeatures when you build every Pool, including the validation Pool.