Random Forests and Gradient Boosting

Updated · 5 min read
mediumPython 3.13aimachine-learningrandom-forestsgradient-boostingscikit-learn

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

Vote together, or fix each other's mistakes
MethodHow it combines treesStrength
Random forestMany independent trees voteRobust, little tuning needed
Gradient boostingTrees added in sequence, each fixing earlier errorsOften the most accurate on tables
Single treeJust oneReadable, but overfits

Example

This program uses payments_history.csv from "Supervised Learning".

Python
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}")
Output
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.006

Explanation: 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

MethodDescription
Built-in importance (feature_importances_)It is used for a quick look; it can overrate features with many distinct values
Permutation importanceIt 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:

  1. How do the trees in a random forest combine?
  2. What does gradient boosting do differently?
  3. Which feature mattered most, and how was that measured?

Quick check: ensembles

4 questions
1How does a random forest make a prediction?
2What is gradient boosting?
3What did the random forest score on the test set?
4What does permutation importance measure?

Key Takeaways

Quick reference

NeedCode
Random forestRandomForestClassifier(n_estimators=200)
Gradient boostingGradientBoostingClassifier()
Importancepermutation_importance(model, X_test, y_test)

Was this tutorial helpful?

Lesson 124 of 186