Sub topic 14
Training CatBoost with Pool and cat_features
This chapter assumes you can train a LightGBM model with early stopping, know what a validation split is, and are comfortable with pandas and metrics such as AUC. It also assumes you have read the earlier chapters on CatBoost's ordered target statistics, ordered boosting and symmetric trees. Here the goal is to put those pieces together in a working training run and to avoid the usual mistakes.
The working model
CatBoost trains on a Pool. A Pool is a data container that holds the feature matrix, the labels, and metadata about the columns. The most important piece of metadata is cat_features, the list of columns that CatBoost must treat as categorical.
When you declare a column in cat_features, CatBoost does the following:
- It accepts the raw values, so strings need no manual encoding.
- It converts each categorical value to numeric statistics using ordered target statistics, computed over random permutations of the training rows. The statistic for a row uses only rows that come before it in the permutation, which prevents target leakage.
- It builds symmetric trees on the original numeric columns and the encoded categorical columns together.
- It applies the same encoding to new data at prediction time, using statistics computed from the full training set.
Because of step 4, the categorical handling is part of the trained model. You do not keep a separate encoder.
A complete training run
The example below builds a synthetic dataset with two string columns and one numeric column. The label depends on the plan, the age, and 10 percent random noise.
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())Points to notice:
cat_featurescan hold column names when the input is a DataFrame, or integer column positions when the input is a NumPy array.- The validation Pool uses the same
cat_featuresas the training Pool. A mismatch is an error or, worse, a silent change in how columns are read. eval_setaccepts a Pool, andearly_stopping_roundsstops training once the evaluation metric has not improved for that many iterations.verbose=100prints the metrics every 100 iterations. Useverbose=Falseor0for quiet runs.
Overfitting detector and best model
By default, when you pass an eval_set, CatBoost keeps the model from the best iteration and discards the trees after it. This is controlled by use_best_model, which defaults to True when an eval set is present. After training, model.get_best_iteration() returns the index of the best iteration (counting from 0), and model.tree_count_ tells you how many trees remain in the model.
The metric used for stopping is eval_metric. If you do not set it, CatBoost uses the loss function, such as Logloss for binary classification. Set it explicitly when the metric you care about differs from the loss you optimize, as with AUC above. When several metrics are computed, the one used for early stopping and best-model selection is the first one, which is eval_metric.
Useful Pool features
A Pool is more than a wrapper around arrays. These options come up often:
weightgives per-row sample weights.group_idmarks groups of rows, which is required for ranking objectives.baselinesupplies initial predictions that training continues from.feature_namesnames columns when the input is a NumPy array.text_featuresmarks free-text columns for CatBoost's text handling, which is outside this chapter.
You can also build a Pool from a file path with a column description file, which is useful for data that does not fit comfortably in a DataFrame.
A Pool is reusable. Create it once and pass it to several fit calls when you compare parameter settings. This avoids repeating the preprocessing, in particular the quantization of numeric features into bins.
Predicting
Prediction works on DataFrames or Pools with the same column layout.
proba = model.predict_proba(X_valid)[:, 1]
labels = model.predict(X_valid)
raw = model.predict(X_valid, prediction_type="RawFormulaVal")predict_proba returns class probabilities. RawFormulaVal returns the raw additive score before the sigmoid, which is what SHAP values add up to. The columns must have the same names and order as in training.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `CatBoostError` about a categorical value that is a float | A column in `cat_features` contains NaN or floats | Convert the column to string, or fill missing values with a placeholder such as `"missing"` |
| Strings in a column not listed in `cat_features` | CatBoost cannot convert text to numbers | Add the column to `cat_features` or encode it yourself |
| Integer category codes treated as numbers | The column was not declared | List it in `cat_features`. CatBoost only treats a column as categorical if you say so |
| Training never stops early | No `eval_set`, or `early_stopping_rounds` unset | Pass an `eval_set` and set `early_stopping_rounds` |
| Validation AUC far above test AUC | The validation set was reused for tuning and stopping | Hold out a separate test set |
| Training is slow with many categories | High-cardinality columns create many category combinations | Lower `max_ctr_complexity`, or set `one_hot_max_size` carefully |
Two parameters affect how categorical columns are encoded. one_hot_max_size sets the cardinality at or below which a column is one-hot encoded instead of target-encoded. Its default depends on the task and device. max_ctr_complexity limits how many categorical columns can be combined into one derived feature. Lower values train faster and can reduce overfitting, at some cost in accuracy when interactions matter.
Using the scikit-learn style API
CatBoostClassifier and CatBoostRegressor follow the scikit-learn estimator interface, so they work in cross_val_score and similar tools. You can also pass cat_features directly to the constructor or to fit instead of building a Pool. For anything beyond a simple run, use Pools. They make the column roles explicit and let you attach weights and groups.
When you use cross-validation with a Pipeline, avoid steps that one-hot encode categoricals before CatBoost. That removes the information that its encoding relies on and wastes the main advantage of the library.
Exercise
You train a CatBoostClassifier with a train Pool and an eval Pool, with evalmetric="AUC" and earlystoppingrounds=50. Training ends at iteration 380, and getbest_iteration() returns 330. How many trees does the final model contain by default, and why?
Show answer
It contains 331 trees. With an eval set, usebestmodel defaults to True, so CatBoost discards the trees built after the best iteration. The best iteration index is 330 and counting starts at 0, so the kept trees are iterations 0 through 330.
Exercise
A teammate declares cat_features=["city", "plan"] for the training Pool but forgets to do so for the validation Pool. Why is this a problem, and how would you prevent it?
Show answer
The validation Pool would read those columns with a different type or fail outright, so the evaluation would not match how the model was trained, and early stopping would act on a wrong metric. Prevent it by defining cat_features once in a variable and passing that same variable to every Pool, or by building all Pools in one helper function.