Random Forests and Gradient Boosting
An ensemble is a model made of many smaller models whose predictions are combined. A random forest trains hundreds of decision trees, each on a random sample of the data and features, and lets them vote. Gradient boosting builds trees one after another, each correcting the mistakes of the trees before it. Both usually beat a single tree, and gradient boosting is among the strongest methods for tables of data.
Many Trees, One Prediction
| Method | How it combines trees | Strength |
|---|---|---|
| Random forest | Many independent trees vote | Robust, little tuning needed |
| Gradient boosting | Trees added in sequence, each fixing earlier errors | Often the most accurate on tables |
| Single tree | Just one | Readable, but overfits |
Example
This program uses payments_history.csv from "Supervised Learning".
import pandas as pd
from sklearn.inspection import permutation_importance
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
data = pd.read_csv("payments_history.csv")
X, y = data.drop(columns="late"), data["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
models = {
"one deep tree": DecisionTreeClassifier(random_state=0),
"random forest": RandomForestClassifier(n_estimators=200, min_samples_leaf=5, random_state=0),
"gradient boosting": GradientBoostingClassifier(random_state=0),
}
for name, model in models.items():
model.fit(X_train, y_train)
print(f"{name:18} train {model.score(X_train, y_train):.1%}, test {model.score(X_test, y_test):.1%}")
forest = models["random forest"]
# How much does test accuracy drop when each feature is shuffled?
result = permutation_importance(forest, X_test, y_test, n_repeats=20, random_state=0)
print("Accuracy lost when a feature is shuffled (random forest):")
for name, value in sorted(zip(X.columns, result.importances_mean), key=lambda p: -p[1]):
print(f" {name:16} {value:.3f}")one deep tree train 98.3%, test 83.2%
random forest train 90.7%, test 88.8%
gradient boosting train 92.8%, test 87.6%
Accuracy lost when a feature is shuffled (random forest):
past_late 0.040
amount 0.031
autopay 0.023
months_enrolled 0.008
opened_reminder 0.006Explanation: One unlimited tree memorizes (98.3% train, 83.2% test). The random forest averages 200 trees, so individual trees' mistakes cancel out: 88.8% on the test set with a much smaller gap. Gradient boosting reaches 87.6%. Permutation importance shuffles one feature at a time and measures how much test accuracy drops: shuffling past late payments costs the most, matching the rule hidden in the data.
Feature Importance
| Method | Description |
|---|---|
Built-in importance (feature_importances_) | It is used for a quick look; it can overrate features with many distinct values |
| Permutation importance | It is used to measure how much accuracy drops when a feature is shuffled; more reliable |
Common Mistakes
Assuming the most complex model wins. Always compare with simpler ones.
Trusting built-in importance blindly. Check with permutation importance.
Reading importance as cause. It shows what the model uses, not what causes late payments.
Interview Corner
What is the difference between a random forest and gradient boosting?
A random forest trains many trees independently on random samples and averages them; gradient boosting trains trees sequentially, each one fitting the errors of the ensemble so far.
Why does a random forest overfit less than one tree?
Each tree sees a different random sample of data and features, so their errors differ, and averaging their votes cancels much of the noise.
Practice
Exercise: tune the forest. Try n_estimators of 10, 50 and 500, and min_samples_leaf of 1 and 20. Which setting changes test accuracy most?
Check your understanding:
- How do the trees in a random forest combine?
- What does gradient boosting do differently?
- Which feature mattered most, and how was that measured?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Random forest | RandomForestClassifier(n_estimators=200) |
| Gradient boosting | GradientBoostingClassifier() |
| Importance | permutation_importance(model, X_test, y_test) |
Was this tutorial helpful?