CatBoost: Complete Guide for Gradient Boosting with Categorical Data
Summary
CatBoost (short for Category Boosting) is a gradient boosting algorithm developed by Yandex in 2017. Its revolutionary feature lies in its ability to natively handle categorical variables without requiring prior encoding such as one-hot encoding or classical target encoding. This major characteristic eliminates a tedious preprocessing step while significantly improving predictive performance on data containing many high-cardinality categorical variables.
CatBoost solves two fundamental problems of traditional gradient boosting: target leakage (leakage of target information) and distribution shift between training data and production data. These two innovations — ordered target encoding and ordered boosting — make CatBoost the algorithm of choice for machine learning competitions on tabular data and for real-world industrial applications.
In this complete guide, we will explore in depth the mathematical workings of CatBoost, its practical implementation in Python, its essential hyperparameters, as well as four concrete use cases that will illustrate its exceptional power.
Mathematical Principle of CatBoost
Ordered Target Encoding
The heart of CatBoost’s innovation lies in its ordered target encoding approach. To understand this concept, let’s first examine the problem that CatBoost solves.
In classical target encoding, each category is replaced by the mean of the target variable for that category. The problem? This creates massive target leakage: each sample “sees” its own target value in the encoding, causing catastrophic overfitting.
CatBoost gets around this problem with an elegant idea: for a sample i and a category c, the encoded value is calculated as follows:
Encoded value(i, c) = (Σj < i [xj == c] · yj + prior) / (Σj < i [xj == c] + 1)
Where:
– The sum Σj < i is taken over all samples j preceding i in a random permutation of the data
– [xj == c] is an indicator function equal to 1 if sample j has category c, 0 otherwise
– yj is the target value of sample j
– prior is a prior value (usually the global mean of the target) that regularizes the estimation, especially when few samples precede i
The random permutation is crucial: it ensures that each sample is encoded only from “previous” observations in a randomly drawn order, thus eliminating the target leakage bias. In practice, CatBoost generates multiple random permutations to build multiple trees, further strengthening the model’s robustness.
Ordered Boosting
Ordered boosting is CatBoost’s second major innovation. In classical gradient boosting, gradients (negative residuals) are computed on the entire dataset at each iteration. This global computation creates another type of target leakage: the model learns the residuals of data it has already seen.
CatBoost solves this problem by computing gradients in an ordered fashion: for each sample i in the permutation, only the model trained on samples j < i (preceding in the permutation order) is used. In other words, the prediction for sample i relies on a sub-model that has never “seen” that sample.
This approach eliminates predictive shift — the discrepancy between the distribution of predictions on training data and that on test data — which plagues other gradient boosting algorithms.
Formally, at each boosting step t:
1. A random permutation π of the data is generated
2. For each sample i in order π, the gradient is computed using the model Mt-1<i (trained only on preceding samples)
3. A new tree is fitted on these ordered gradients
Combining Categorical Features
CatBoost doesn’t just encode individual categories. The algorithm automatically creates combinations of categorical features to capture interactions between variables.
For example, if the dataset contains the categorical variables “City” (Paris, Lyon, Marseille) and “Neighborhood Type” (Center, Periphery, Suburbs), CatBoost will automatically create the combination (City, Neighborhood Type) producing categories like (Paris, Center), (Lyon, Suburbs), etc.
These combinations are generated dynamically during tree training: at each split node, the algorithm considers not only individual categories but also combinations of two categories. To limit the combinatorial explosion (the Cartesian product of two variables with 100 categories each generates 10,000 combinations), CatBoost applies a split selection mechanism: only combinations that significantly improve the loss reduction are kept.
This approach allows CatBoost to capture complex interactions between categorical variables without human intervention, while maintaining reasonable computational complexity.
Intuition: CatBoost Explained Simply
Imagine you need to predict the price of an apartment. Among your variables, you have the city (Paris, Lyon, Marseille), which is a categorical variable.
The naive approach would be to use one-hot encoding: Paris = [1, 0, 0], Lyon = [0, 1, 0], Marseille = [0, 0, 1]. But this method has several problems. First, it captures no relationship between cities — Paris and Marseille are as “distant” as Paris and Lyon even though their real estate markets may be very different. Second, if you have 500 cities, you create 500 columns, making the model slow and prone to overfitting.
Another approach would be target encoding: replace each city by the average apartment price in that city. Paris → €450,000, Lyon → €280,000, Marseille → €200,000. The problem? If apartment number 1 is in Paris and costs €500,000, its encoding will use… its own value of €500,000! It’s like a student cheating by looking at the answer before responding. This is exactly what we call target leakage.
CatBoost does something much smarter. It puts all the data in a random order — like a student answering a quiz without seeing the others’ answers. For apartment number 1 in this order, it says: “I don’t yet know the average prices by city, so I use the global average as a starting point (the prior).” For apartment number 10, also in Paris, it says: “Among the 9 previous apartments in my order, 3 were in Paris with an average price of €420,000, so I use this estimate.”
By shuffling the order multiple times and averaging the results, CatBoost obtains a reliable, cheat-free encoding that works just as well as on training data as on new data.
This is the essence of ordered boosting: each sample is evaluated by a model that has “never seen” it before, just like in a real quiz where questions are asked in a different order for each student.
Python Implementation of CatBoost
Installation and Basic Configuration
To use CatBoost, start by installing the library:
pip install catboost scikit-learn numpy pandas
Classification with CatBoostClassifier
Here is a complete example of binary classification with native categorical variable handling:
import numpy as np
import pandas as pd
from catboost import CatBoostClassifier, Pool
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, roc_auc_score
# Creating a sample dataset
np.random.seed(42)
n_samples = 5000
data = pd.DataFrame({
'ville': np.random.choice(['Paris', 'Lyon', 'Marseille', 'Toulouse', 'Bordeaux'], n_samples),
'type_bien': np.random.choice(['Appartement', 'Maison', 'Studio', 'Loft'], n_samples),
'quartier': np.random.choice(['Centre', 'Peripherie', 'Banlieue', 'Rural'], n_samples),
'surface': np.random.uniform(20, 200, n_samples),
'etage': np.random.randint(0, 15, n_samples),
'annee_construction': np.random.randint(1950, 2024, n_samples),
})
# Binary target variable (example: sold in less than 3 months)
prob_sale = (
0.3 +
0.15 * (data['ville'] == 'Paris').astype(float) +
0.10 * (data['ville'] == 'Lyon').astype(float) +
0.08 * (data['type_bien'] == 'Appartement').astype(float) -
0.05 * (data['quartier'] == 'Rural').astype(float) +
0.002 * data['surface'] +
np.random.normal(0, 0.1, n_samples)
)
data['vendu_rapide'] = (prob_sale > 0.5).astype(int)
# Train / test split
X = data.drop('vendu_rapide', axis=1)
y = data['vendu_rapide']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# Identifying categorical columns
categorical_columns = ['ville', 'type_bien', 'quartier']
numerical_columns = ['surface', 'etage', 'annee_construction']
cat_indices = [X.columns.get_loc(col) for col in categorical_columns]
# Creating the CatBoost model
model = CatBoostClassifier(
iterations=1000,
learning_rate=0.05,
depth=6,
l2_leaf_reg=3,
random_strength=1,
cat_features=cat_indices,
eval_metric='AUC',
early_stopping_rounds=50,
verbose=100,
random_seed=42
)
# Training with validation set
model.fit(
X_train, y_train,
eval_set=(X_test, y_test),
plot=False
)
# Predictions and evaluation
y_pred = model.predict(X_test)
y_proba = model.predict_proba(X_test)[:, 1]
print(f"AUC: {roc_auc_score(y_test, y_proba):.4f}")
print(classification_report(y_test, y_pred))
Using the Pool Object for Better Performance
CatBoost offers a Pool object specifically optimized for data handling:
from catboost import Pool
# Creating Pool for training and validation
train_pool = Pool(
data=X_train,
label=y_train,
cat_features=cat_indices
)
eval_pool = Pool(
data=X_test,
label=y_test,
cat_features=cat_indices
)
# Training with Pool
model.fit(train_pool, eval_set=eval_pool)
The Pool object is strongly recommended as it optimizes memory management and allows CatBoost to pre-calculate categorical encodings more efficiently.
Regression with CatBoostRegressor
For regression problems, the API is similar:
from catboost import CatBoostRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
# Regression example: price prediction
data['prix'] = (
200_000 +
80_000 * (data['ville'] == 'Paris').astype(float) +
30_000 * (data['type_bien'] == 'Maison').astype(float) +
1500 * data['surface'] -
500 * data['etage'] +
np.random.normal(0, 20_000, n_samples)
)
y_reg = data['prix']
X_reg = data.drop(['prix', 'vendu_rapide'], axis=1)
X_train_r, X_test_r, y_train_r, y_test_r = train_test_split(
X_reg, y_reg, test_size=0.2, random_state=42
)
regressor = CatBoostRegressor(
iterations=1000,
learning_rate=0.05,
depth=6,
loss_function='RMSE',
cat_features=cat_indices[:3],
early_stopping_rounds=50,
verbose=100,
random_seed=42
)
regressor.fit(X_train_r, y_train_r, eval_set=(X_test_r, y_test_r))
y_pred_r = regressor.predict(X_test_r)
print(f"R²: {r2_score(y_test_r, y_pred_r):.4f}")
print(f"MAE: {mean_absolute_error(y_test_r, y_pred_r):.2f} \u20ac")
print(f"RMSE: {np.sqrt(mean_squared_error(y_test_r, y_pred_r)):.2f} \u20ac")
Cross-Validation with CatBoost
CatBoost offers its own cross-validation function:
from catboost import cv
params = {
'iterations': 500,
'learning_rate': 0.05,
'depth': 6,
'loss_function': 'Logloss',
'cat_features': cat_indices,
'random_seed': 42,
'verbose': False
}
cv_data = cv(
params=params,
pool=train_pool,
fold_count=5,
plot=False
)
print(f"Mean AUC in CV: {cv_data['test-AUC-mean'].max():.4f}")
Interpretability: Feature Importance and SHAP Values
CatBoost offers several methods to understand model predictions:
# Classical feature importance
importance = model.get_feature_importance(prettified=True)
print(importance)
# Prediction with SHAP values
shap_values = model.get_feature_importance(
data=train_pool,
type='ShapValues'
)
# Visualization of individual sample importance
import matplotlib.pyplot as plt
# Feature importance plot
importance_df = model.get_feature_importance(prettified=True)
plt.figure(figsize=(10, 6))
plt.barh(importance_df['Feature Id'], importance_df['Importances'])
plt.xlabel('Importance')
plt.title('Feature Importance (CatBoost)')
plt.tight_layout()
plt.show()
# Learning curve
curve = model.evals_result_
plt.figure(figsize=(10, 5))
plt.plot(curve['learn']['AUC'], label='Training')
plt.plot(curve['validation']['AUC'], label='Validation')
plt.xlabel('Iteration')
plt.ylabel('AUC')
plt.legend()
plt.title('CatBoost Learning Curve')
plt.show()
Essential CatBoost Hyperparameters
Mastering CatBoost hyperparameters is essential to achieve optimal performance. Here are the most important ones:
| Hyperparameter | Description | Default Value | Recommended Range |
|---|---|---|---|
| iterations | Number of trees (boosting steps) | 1000 | 500–3000 |
| learning_rate | Learning rate (eta) | 0.03 | 0.01–0.1 |
| depth | Maximum tree depth | 6 | 4–10 |
| l2_leaf_reg | L2 regularization on leaves | 3 | 1–10 |
| rsm | Random feature fraction per split | 1.0 | 0.5–1.0 |
| random_strength | Randomization strength during splits | 1.0 | 0.5–2.0 |
| one_hot_max_size | Max size for direct one-hot encoding | 2 | 2–10 |
| bagging_temperature | Controls Bayesian bootstrap | 1.0 | 0–10 |
| min_data_in_leaf | Minimum samples per leaf | 1 | 1–50 |
| max_ctr_complexity | Max depth of categorical combinations | 4 | 1–4 |
Practical Recommendations
To get the best performance with CatBoost, follow these recommendations:
- Small datasets (fewer than 10,000 samples): use
depth=4-6,learning_rate=0.05-0.1,l2_leaf_reg=3-5 - Large datasets (more than 100,000 samples): use
depth=8-10,learning_rate=0.01-0.03,l2_leaf_reg=1-3 - Many categories: increase
max_ctr_complexityto 4 to capture more interactions - Overfitting risk: increase
l2_leaf_reg, reducedepth, enable early stopping - Systematic optimization: use grid search or Bayesian optimization to find the best hyperparameters
from catboost import CatBoostClassifier
# Grid search integrated into CatBoost
gs_model = CatBoostClassifier(
iterations=1000,
cat_features=cat_indices,
eval_metric='AUC',
verbose=False
)
grid = {
'learning_rate': [0.01, 0.05, 0.1],
'depth': [4, 6, 8],
'l2_leaf_reg': [1, 3, 5, 7]
}
gs_model.grid_search(
grid,
X_train, y_train,
cv=5,
plot=False,
refit=True
)
print(f"Best parameters: {gs_model.get_params()}")
Advantages and Limitations of CatBoost
Advantages
- Native handling of categorical variables: No prior encoding needed. CatBoost automatically handles categorical variables through ordered target encoding, which considerably simplifies preprocessing.
- Excellent robustness to overfitting: Ordered boosting and ordered target encoding eliminate target leakage, making CatBoost naturally more robust than XGBoost or LightGBM on categorical data.
- Exceptional prediction performance: On tabular data with many categorical variables, CatBoost often outperforms other gradient boosting algorithms, making it a preferred choice for Kaggle competitions.
- Fast predictions in production: The trained model can be exported in multiple formats (ONNX, C++, Python) and predictions are extremely fast thanks to tree optimization.
- GPU support: CatBoost supports GPU training (NVIDIA), which significantly accelerates training on large data volumes.
- Missing value handling: CatBoost automatically handles missing values (NaN) without prior imputation, by learning the optimal direction of each missing value in each tree.
Limitations
- Longer training time: Ordered boosting requires recalculating gradients for each sample at each iteration, making CatBoost training significantly slower than LightGBM, especially on large datasets.
- Significant memory usage: Generating multiple permutations and storing ordered gradients consumes more RAM than competing algorithms.
- Less suitable for purely numerical data: If your dataset contains only numerical variables, CatBoost offers no significant advantage over XGBoost or LightGBM.
- Difficulty interpreting combinations: Automatic categorical feature combinations, while powerful, can make model interpretation more complex.
4 Concrete Use Cases for CatBoost
Case 1: Bank Credit Scoring
In banking, categorical variables are omnipresent: profession, business sector, marital status, housing type, geographic region. CatBoost excels in this context because it naturally captures interactions between these categories.
# Simplified credit scoring example
credit_data = pd.DataFrame({
'profession': ['Cadre', 'Ouvrier', 'Employe', 'Cadre', 'Artisan'],
'secteur': ['Technologie', 'Industrie', 'Commerce', 'Sante', 'BTP'],
'region': ['Ile-de-France', 'Auvergne-Rhone-Alpes', 'PACA', 'Nouvelle-Aquitaine', 'Occitanie'],
'type_logement': ['Proprietaire', 'Locataire', 'Heberge', 'Proprietaire', 'Locataire'],
'revenu_annuel': [65000, 28000, 25000, 72000, 45000],
'duree_contrat': [36, 60, 24, 48, 36],
'defaut': [0, 1, 1, 0, 0]
})
credit_cat_cols = ['profession', 'secteur', 'region', 'type_logement']
X_credit = credit_data.drop('defaut', axis=1)
y_credit = credit_data['defaut']
credit_cat_indices = [X_credit.columns.get_loc(c) for c in credit_cat_cols]
credit_model = CatBoostClassifier(
iterations=500,
depth=5,
learning_rate=0.05,
cat_features=credit_cat_indices,
eval_metric='F1',
random_seed=42
)
credit_model.fit(X_credit, y_credit, verbose=False)
Case 2: Content Recommendation
Streaming platforms (music, video, reading) use massive categorical features: artistic genres, artists, languages, tags, regions. CatBoost can predict the probability that a user will enjoy a given piece of content.
# Music recommendation example
music_data = pd.DataFrame({
'genre': np.random.choice(['Pop', 'Rock', 'Jazz', 'Classique', 'Hip-Hop', 'Electro'], 10000),
'artiste_popularite': np.random.choice(['Inconnu', 'Emergent', 'Connu', 'Celebre'], 10000),
'langue': np.random.choice(['Francais', 'Anglais', 'Espagnol', 'Autre'], 10000),
'duree_minute': np.random.uniform(2, 8, 10000),
'heure_ecoute': np.random.randint(0, 24, 10000),
'utilisateur_age': np.random.randint(15, 70, 10000),
'aime': np.random.choice([0, 1], 10000, p=[0.6, 0.4])
})
music_cat_cols = ['genre', 'artiste_popularite', 'langue']
X_music = music_data.drop('aime', axis=1)
y_music = music_data['aime']
music_cat_indices = [X_music.columns.get_loc(c) for c in music_cat_cols]
Case 3: Customer Churn Prediction
In e-commerce and telecommunications, predicting which customers will unsubscribe is crucial for retention. Categorical variables include: subscription type, payment method, acquisition channel, customer segment.
# Churn prediction example
churn_data = pd.DataFrame({
'abonnement': np.random.choice(['Basique', 'Standard', 'Premium', 'Entreprise'], 20000),
'marche_paiement': np.random.choice(['Carte', 'Prelevement', 'Virement', 'PayPal'], 20000),
'canal_acquisition': np.random.choice(['Organique', 'Publicite', 'Parrainage', 'Partenaire'], 20000),
'segment': np.random.choice(['Particulier', 'PME', 'Grand_compte'], 20000),
'anciennete_mois': np.random.randint(1, 72, 20000),
'nb_tickets_support': np.random.randint(0, 30, 20000),
'duree_contrat_mois': np.random.choice([1, 12, 24, 36], 20000),
'parti': np.random.choice([0, 1], 20000, p=[0.85, 0.15])
})
churn_cat_cols = ['abonnement', 'marche_paiement', 'canal_acquisition', 'segment']
churn_cat_indices = [churn_data.drop('parti', axis=1).columns.get_loc(c) for c in churn_cat_cols]
Case 4: Medical Diagnosis
In healthcare, CatBoost can assist in diagnosis by analyzing patient data containing many categorical variables: family history, symptom type, treatment category, healthcare facility.
# Simplified medical diagnosis example
medical_data = pd.DataFrame({
'antecedent_familial': np.random.choice(['Aucun', 'Diabete', 'Cardiovasculaire', 'Cancer'], 8000),
'type_symptome': np.random.choice(['Douleur', 'Fievre', 'Fatigue', 'Toux', 'Vertiges'], 8000),
'categorie_traitement': np.random.choice(['Preventif', 'Curatif', 'Palliatif', 'Chirurgical'], 8000),
'etablissement': np.random.choice(['Hopital', 'Clinique', 'Cabinet', 'Urgences'], 8000),
'age_patient': np.random.randint(18, 90, 8000),
'tension_arterielle': np.random.uniform(90, 180, 8000),
'glycemie': np.random.uniform(0.7, 2.5, 8000),
'diagnostic_grave': np.random.choice([0, 1], 8000, p=[0.75, 0.25])
})
medical_cat_cols = ['antecedent_familial', 'type_symptome', 'categorie_traitement', 'etablissement']
medical_cat_indices = [medical_data.drop('diagnostic_grave', axis=1).columns.get_loc(c) for c in medical_cat_cols]
See Also
- Explore the Goldbach Conjecture in Python: Practical Guide for Programming Enthusiasts
- Solving Diophantine Equations III with Python: Complete Guide and Tips

