CatBoost
CatBoost handles categorical and text features natively, with no manual encoding. It uses ordered boosting, which reduces the target leakage that plagues ordinary target encoding. This page walks a full workflow on a mixed-type clinical dataset.
Every code block runs in a container in the companion repository, so the numbers and figure are real.
The data
Section titled “The data”A dataset with numeric, categorical, and free-text (diagnosis) columns, and a target
that depends on age, BMI, glucose, cholesterol, smoking, exercise, and one diagnosis
keyword, myocardial. The block simulates 2000 patients with a fixed seed.
from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom catboost import CatBoostClassifier, Pool, cv as catboost_cvfrom sklearn.metrics import classification_report, roc_auc_scorefrom sklearn.model_selection import train_test_split
out = Path("outputs")out.mkdir(exist_ok=True)
np.random.seed(42)n = 2000diagnoses = [ "Type 2 diabetes with peripheral neuropathy", "Hypertension stage 2 uncontrolled", "Chronic kidney disease stage 3a", "Acute myocardial infarction anterior wall", "Heart failure with reduced ejection fraction", "Chronic obstructive pulmonary disease exacerbation", "Atrial fibrillation with rapid ventricular response", "Deep vein thrombosis left lower extremity", "Pneumonia community acquired bacterial", "Urinary tract infection complicated",]departments = ["cardiology", "endocrinology", "nephrology", "pulmonology", "general"]df = pd.DataFrame({ "age": np.random.normal(55, 15, n).astype(int), "bmi": np.random.normal(27, 5, n).round(1), "glucose": np.random.lognormal(4.6, 0.3, n).round(1), "cholesterol": np.random.normal(200, 40, n).round(0), "blood_pressure": np.random.normal(130, 20, n).astype(int), "smoking": np.random.choice(["never", "former", "current"], n), "exercise": np.random.choice(["none", "moderate", "heavy"], n), "family_history": np.random.choice(["yes", "no"], n), "diagnosis": np.random.choice(diagnoses, n), "department": np.random.choice(departments, n),})# Only the myocardial infarction diagnosis raises the score.infarction = df["diagnosis"].str.contains("myocardial")score = (0.02 * df["age"] + 0.05 * df["bmi"] + 0.01 * df["glucose"] - 0.005 * df["cholesterol"] + (df["smoking"] == "current").astype(float) * 0.5 + (df["exercise"] == "none").astype(float) * 0.3 + infarction.astype(float) * 0.4 + np.random.normal(0, 0.5, n))df["target"] = (score > 2.0).astype(int)
cat_features = ["smoking", "exercise", "family_history", "department"]features = df.drop(columns=["target", "diagnosis"]) # hold text out for nowy = df["target"]x_train, x_test, y_train, y_test = train_test_split(features, y, test_size=0.2, random_state=42, stratify=y)Native categorical features
Section titled “Native categorical features”Just name the categorical columns; no one-hot or label encoding. Use CatBoost’s own
cross-validation with Pool for correct categorical handling. logging_level="Silent"
keeps the per-fold log quiet, and allow_writing_files=False stops CatBoost from
writing a catboost_info/ folder of training logs next to the script.
train_pool = Pool(x_train, y_train, cat_features=cat_features)params = { "iterations": 200, "depth": 6, "learning_rate": 0.1, "loss_function": "Logloss", "eval_metric": "AUC", "random_seed": 42, "logging_level": "Silent", "allow_writing_files": False,}cvr = catboost_cv(train_pool, params, fold_count=5, stratified=True, seed=42, verbose=False)cv_mean = cvr["test-AUC-mean"].iloc[-1]cv_std = cvr["test-AUC-std"].iloc[-1]print(f"Cross-validated ROC-AUC: {cv_mean:.4f} (+/- {cv_std:.4f})")
model = CatBoostClassifier(iterations=200, depth=6, learning_rate=0.1, cat_features=cat_features, random_seed=42, verbose=0, allow_writing_files=False)model.fit(x_train, y_train)y_prob = model.predict_proba(x_test)[:, 1]print(f"Test ROC-AUC: {roc_auc_score(y_test, y_prob):.4f}")print(classification_report(y_test, model.predict(x_test), target_names=["Negative", "Positive"]))Cross-validated ROC-AUC: 0.8580 (+/- 0.0147)Test ROC-AUC: 0.8618 precision recall f1-score support
Negative 0.57 0.44 0.50 62 Positive 0.90 0.94 0.92 338
accuracy 0.86 400 macro avg 0.74 0.69 0.71 400weighted avg 0.85 0.86 0.85 400Internally CatBoost uses ordered target encoding: for each sample it computes the category’s mean target from earlier samples only, in a randomized order. This avoids both the leakage of ordinary target encoding and the width of one-hot encoding.
Native text features
Section titled “Native text features”CatBoost tokenizes text columns and builds bag-of-words features automatically.
x_train_full, x_test_full, y_train_full, y_test_full = train_test_split( df.drop(columns=["target"]), y, test_size=0.2, random_state=42, stratify=y)model_text = CatBoostClassifier(iterations=200, depth=6, learning_rate=0.1, cat_features=cat_features, text_features=["diagnosis"], random_seed=42, verbose=0, allow_writing_files=False)model_text.fit(x_train_full, y_train_full)y_prob_text = model_text.predict_proba(x_test_full)[:, 1]text_auc = roc_auc_score(y_test_full, y_prob_text)print(f"ROC-AUC with text features: {text_auc:.4f}")ROC-AUC with text features: 0.8694Adding the diagnosis text lifted the test ROC-AUC from 0.8618 to 0.8694, because the target partly depends on one diagnosis keyword.
Hyperparameter tuning
Section titled “Hyperparameter tuning”CatBoost has strong defaults; usually you only tune depth, learning_rate, and
l2_leaf_reg. Use its native cv so categoricals are handled correctly.
best_score, best_params = 0, {}for depth in [4, 6, 8]: for lr in [0.05, 0.1]: for l2 in [1, 3, 5]: p = { **params, "depth": depth, "learning_rate": lr, "l2_leaf_reg": l2 } auc = catboost_cv(train_pool, p, fold_count=5, stratified=True, seed=42, verbose=False)["test-AUC-mean"].iloc[-1] if auc > best_score: best_score, best_params = auc, { "depth": depth, "learning_rate": lr, "l2_leaf_reg": l2 }print(f"Best ROC-AUC: {best_score:.4f}")print(f"Best parameters: {best_params}")
best_model = CatBoostClassifier(iterations=200, cat_features=cat_features, random_seed=42, verbose=0, allow_writing_files=False, **best_params)best_model.fit(x_train, y_train)y_prob_tuned = best_model.predict_proba(x_test)[:, 1]print(f"Tuned Test ROC-AUC: {roc_auc_score(y_test, y_prob_tuned):.4f}")Best ROC-AUC: 0.8664Best parameters: {'depth': 4, 'learning_rate': 0.05, 'l2_leaf_reg': 3}Tuned Test ROC-AUC: 0.8743Feature importance
Section titled “Feature importance”importance = pd.DataFrame({ "feature": x_train.columns.tolist(), "importance": best_model.feature_importances_,}).sort_values("importance", ascending=False)print(importance.head(6).to_string(index=False)) feature importance bmi 19.932746 glucose 19.755517 age 19.272631cholesterol 14.189801 smoking 13.797002 exercise 6.259204fig, ax = plt.subplots(figsize=(6, 5))ordered = importance.iloc[::-1]ax.barh(ordered["feature"], ordered["importance"], color="#c44e52")ax.set_xlabel("Importance")ax.set_title("CatBoost feature importance")fig.tight_layout()fig.savefig(out / "catboost-feature-importance.png", dpi=150)plt.close(fig)
BMI, glucose, and age lead, matching how the target was built. The categorical
smoking ranks fifth, so CatBoost extracts real signal from the categorical columns.
CatBoost vs XGBoost on categorical data
Section titled “CatBoost vs XGBoost on categorical data”This comparison gives XGBoost one-hot encoded columns, while CatBoost takes the raw
categories. XGBoost can also split on pandas category columns directly when you pass
enable_categorical=True, but this page does not use that option.
import xgboost as xgbfrom sklearn.compose import ColumnTransformerfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import OneHotEncoder
numeric = ["age", "bmi", "glucose", "cholesterol", "blood_pressure"]encode = ColumnTransformer([ ("num", "passthrough", numeric), ("cat", OneHotEncoder(drop="first", handle_unknown="ignore"), cat_features),])xgb_pipe = Pipeline([ ("pre", encode), ("clf", xgb.XGBClassifier(n_estimators=200, max_depth=6, learning_rate=0.1, random_state=42, eval_metric="logloss")),])xgb_pipe.fit(x_train, y_train)xgb_auc = roc_auc_score(y_test, xgb_pipe.predict_proba(x_test)[:, 1])print(f"XGBoost (one-hot): ROC-AUC = {xgb_auc:.4f}")print("CatBoost (native cats): ROC-AUC = " f"{roc_auc_score(y_test, y_prob_tuned):.4f}")print(f"CatBoost (cats + text): ROC-AUC = {text_auc:.4f}")XGBoost (one-hot): ROC-AUC = 0.8394CatBoost (native cats): ROC-AUC = 0.8743CatBoost (cats + text): ROC-AUC = 0.8694The tuned CatBoost model scores 0.8743 against 0.8394 for one-hot XGBoost. The gap
does not show that ordered target encoding beats one-hot encoding. CatBoost was tuned
and XGBoost was not, the categorical columns have only two to five levels, and CatBoost
itself one-hot encodes the two-level family_history column under its default
one_hot_max_size. The text model keeps the untuned depth of 6 and learning rate of
0.1, so its row is not a like-for-like comparison with the tuned model.
Early stopping
Section titled “Early stopping”x_train_es, x_validation, y_train_es, y_val = train_test_split( x_train, y_train, test_size=0.2, random_state=42, stratify=y_train)model_es = CatBoostClassifier(iterations=1000, depth=6, learning_rate=0.05, cat_features=cat_features, random_seed=42, verbose=0, early_stopping_rounds=20, allow_writing_files=False)model_es.fit(x_train_es, y_train_es, eval_set=Pool(x_validation, y_val, cat_features=cat_features))es_auc = roc_auc_score(y_test, model_es.predict_proba(x_test)[:, 1])print(f"Best iteration: {model_es.best_iteration_}")print(f"Test ROC-AUC with early stopping: {es_auc:.4f}")Best iteration: 260Test ROC-AUC with early stopping: 0.8799Choosing between them
Section titled “Choosing between them”| Feature | CatBoost | XGBoost | LightGBM |
|---|---|---|---|
| Categoricals | Native (ordered) | Native with enable_categorical=True, or one-hot |
Native (integer) |
| Text | Native | Manual (TF-IDF) | Manual (TF-IDF) |
| Defaults | Strong | Needs tuning | Needs tuning |
| Speed | Medium | Fast | Very fast |
Reach for CatBoost when you have many categorical or text features and want strong results with little preprocessing.
Next steps
Section titled “Next steps”The next pages cover ensembling, where you combine several models to beat any single one.
Scientific references
Section titled “Scientific references”Prokhorenkova and colleagues, 2018 describe CatBoost and its unbiased boosting with categorical features.
Chen and Guestrin, 2016 describe XGBoost, a scalable system for gradient tree boosting.
Further reading
Section titled “Further reading”-
The official guide describes one-hot processing and categorical statistics with conditional defaults. These details explain why categorical columns do not all receive the same treatment.
-
The cv reference explains Pool inputs, fold construction, and the mean and standard deviation returned at each iteration. It also distinguishes early stopping across folds from a single training run.
-
The guide separates tokenizers, dictionaries, and feature calculators. These components determine which numeric features CatBoost derives from a diagnosis string.