🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML CatBoost and a First Look at Tuning Boosting

CatBoost is a boosting library that reads text categories as they are. It needs no encoding step for columns like sex or embarked.

Categories go in as text

CatBoost takes the sex and embarked columns as words. No encoding step runs first.

import pandas as pd
import seaborn as sns
from catboost import CatBoostClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split

titanic = sns.load_dataset("titanic")
df = titanic[["pclass", "sex", "age", "fare", "embarked", "survived"]].copy()
df["age"] = df["age"].fillna(df["age"].median())
df["embarked"] = df["embarked"].fillna("S")
X = df.drop(columns=["survived"])
y = df["survived"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = CatBoostClassifier(iterations=100, random_state=42, verbose=False)
model.fit(X_train, y_train, cat_features=["sex", "embarked"])
print("Accuracy:", round(accuracy_score(y_test, model.predict(X_test)), 4))

The categories stay words

The training columns still hold the words female and male. CatBoost reads them as labels, not numbers.

print("Sex values:", sorted(X_train["sex"].unique()))
print("Embarked values:", sorted(X_train["embarked"].unique()))

Fewer trees can win

Ten rounds beat one hundred rounds on this small data. More trees can memorise the training rows.

from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
Xc_train, Xc_test, yc_train, yc_test = train_test_split(cancer.data, cancer.target, test_size=0.2, random_state=42)
for rounds in [10, 100]:
    m = CatBoostClassifier(iterations=rounds, random_state=42, verbose=False)
    m.fit(Xc_train, yc_train)
    print(rounds, "rounds:", round(accuracy_score(yc_test, m.predict(Xc_test)), 4))

Example

import pandas as pd
import seaborn as sns
from catboost import CatBoostClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split

titanic = sns.load_dataset("titanic")
cols = ["pclass", "sex", "age", "fare", "embarked", "survived"]
df = titanic[cols].copy()
df["age"] = df["age"].fillna(df["age"].median())
df["embarked"] = df["embarked"].fillna("S")
X = df.drop(columns=["survived"])
y = df["survived"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)
model = CatBoostClassifier(iterations=200, random_state=42, verbose=False)
model.fit(X_train, y_train, cat_features=["sex", "embarked"])
print("CatBoost accuracy:", round(accuracy_score(y_test, model.predict(X_test)), 4))

from sklearn.datasets import load_breast_cancer

cancer = load_breast_cancer()
Xc_train, Xc_test, yc_train, yc_test = train_test_split(
    cancer.data, cancer.target, test_size=0.2, random_state=42)
settings = [
    ("100 trees", 100, 6, 0.1),
    ("Deep trees", 100, 10, 0.1),
    ("Fast learning", 100, 6, 0.3),
]
for name, rounds, depth, rate in settings:
    tuned = CatBoostClassifier(iterations=rounds, depth=depth,
                               learning_rate=rate, random_state=42,
                               verbose=False)
    tuned.fit(Xc_train, yc_train)
    print(name, "accuracy:",
          round(accuracy_score(yc_test, tuned.predict(Xc_test)), 4))

Key points

  • CatBoost: a boosting library that handles text categories without encoding them first
  • Categorical feature: a column whose values are labels, like male and female
  • Use cat_features to name the columns that hold text labels
  • Use iterations to set how many trees CatBoost builds
  • Use depth to set how deep each tree may grow
  • Use learning_rate to set how much each tree counts

In this example, the Titanic table is cut to five features and the target. The missing ages take the median age, and the missing embarked values take S. A fifth of the rows is kept back for testing. CatBoostClassifier builds 200 trees, and fit takes cat_features=["sex", "embarked"], so those two columns stay as words. The accuracy is 0.8045, which is lower than the 100-round run in the first snippet, a sign that extra rounds memorised the training rows. The second half tunes three knobs on the breast cancer data. The plain setting scores 0.9649, while deeper trees and a faster learning rate both score 0.9737. In short, CatBoost is boosting that takes categories as words, and its three knobs are the tree count, the tree depth, and the learning rate.

Note

Tune one knob at a time. Change one knob, read the score, then change the next.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does CatBoost let you skip for text columns?