Skip to content
Visual explainer 3h 30m to learn 5 steps

Random forests and gradient boosting in scikit-learn

Compare a single tree, a random forest and gradient boosting on bias, variance, compute cost and interpretability.

By Invicly Tech, , in AI and Machine Learning with Python. About 12 minutes to read.

Topic 10 of 34

In short

A single decision tree is easy to read but changes a lot when the training data changes, which is high variance. A random forest averages many deep trees, each trained on a bootstrap sample with random feature choices, to cut variance. Gradient boosting builds shallow trees one after another, each fixing the errors of the ones before, which reduces bias and is often the strongest choice on tabular data.

Think of it like this: A forest is a panel of independent experts whose votes are averaged; boosting is one expert team where each new member studies the mistakes the team made so far.

Explained simply

A decision tree is a flowchart of questions learned from data. It is easy to draw and explain. Its weakness is that a small change in the training rows can produce a very different tree. That jumpiness is called high variance, and it makes single trees less reliable on new data.

A random forest fixes this by growing hundreds of trees, each on a slightly different random sample of the rows, and each looking at a random handful of features at every split. The forest averages their answers. Individual trees make different mistakes, and averaging cancels much of that noise.

Gradient boosting takes another route. It builds small trees one at a time. Each new tree looks at what the current team still gets wrong and tries to fix part of it. After a few hundred rounds the team is very accurate. Boosted trees often win on spreadsheet-style data.

There is a price. Forests and boosted models are much harder to explain than one tree, use more memory and take longer to train. Feature importance numbers help, but they can mislead. Choose the simplest model that does the job well enough for its users.

Press Play on a diagram to walk through it one step at a time.

CompareTree, forest and boosting
Single tree
  • Low bias when deep, high variance
  • Fast to train and predict
  • Can be drawn and read
  • Prune with max_depth or ccp_alpha
Random forest
  • Averages many deep trees
  • Cuts variance, rarely overfits badly
  • Trees train in parallel
  • Works well with little tuning
Gradient boosting
  • Adds shallow trees in sequence
  • Cuts bias step by step
  • Needs learning rate and early stopping
  • Often best accuracy on tables
CycleHow boosting adds one tree at a time
  1. 1
    Predict

    Current ensemble makes predictions

  2. 2
    Measure errors

    Compute the gradient of the loss for each row

  3. 3
    Fit a small tree

    New tree learns to predict those errors

  4. 4
    Add with a step size

    Scale its output by the learning rate

  5. Back to step 1
MapTuning knobs by model
Tree-based models
  • DecisionTree
    • max_depth
    • min_samples_leaf
    • ccp_alpha
  • RandomForest
    • n_estimators
    • max_features
    • min_samples_leaf
    • n_jobs
  • HistGradientBoosting
    • learning_rate
    • max_iter
    • max_leaf_nodes
    • l2_regularization
    • early_stopping

In depth

Bias and variance in plain terms

Imagine training the same kind of model on many different samples of data from the same source. Bias is how far the average prediction is from the truth: a straight line fitted to a curve is wrong in the same way every time. Variance is how much the predictions change from sample to sample: a deep tree fits each sample's quirks, so it changes a lot.

Test error comes from bias, variance and noise that no model can remove. Simple models tend to have high bias and low variance; flexible models the reverse. A shallow tree underfits; a fully grown tree overfits. Ensembles attack one side each: forests average flexible trees to cut variance, and boosting stacks simple trees to cut bias.

LayersWhere test error comes from
  1. 1
    Test error

    What you measure on new data

  2. 2
    Bias

    Model too simple; wrong in the same way each time

  3. 3
    Variance

    Model too sensitive to its training sample

  4. 4
    Irreducible noise

    Randomness no model can predict

Inside a random forest

Each tree in a random forest is trained on a bootstrap sample: rows drawn with replacement, so some appear twice and roughly a third are left out. At every split the tree considers only a random subset of features. In scikit-learn, RandomForestClassifier defaults to the square root of the number of features, and RandomForestRegressor defaults to all features, so the regressor relies mainly on row sampling.

These two sources of randomness make the trees different from each other, which is what makes averaging work. Trees are usually grown deep and are trained independently, so n_jobs=-1 uses all CPU cores. The rows a tree did not see can score it for free: set oob_score=True to get an out-of-bag estimate without a separate validation set.

  • n_estimators: number of trees (default 100)
  • max_features: features tried per split
  • min_samples_leaf: smooths very deep trees
  • oob_score=True: free validation estimate

Gradient boosting with HistGradientBoosting

Boosting starts with a constant prediction, then repeatedly fits a small tree to the gradient of the loss, which for squared error is simply the residuals, and adds a scaled-down version of that tree. The learning rate sets the scale. Smaller rates need more trees but usually generalise better.

HistGradientBoostingClassifier and HistGradientBoostingRegressor first bucket each feature into at most 255 bins, which makes training much faster than the older GradientBoosting classes on large data. They accept missing values without imputation and can treat categorical features natively. Early stopping holds back part of the training data and stops adding trees when the validation score stops improving; by default it switches on automatically when there are more than 10,000 rows. Key settings are learning_rate, max_iter, max_leaf_nodes and l2_regularization.

  • Start with learning_rate 0.1 and early stopping
  • max_iter caps the number of trees
  • Missing values handled without imputation
  • Much faster than GradientBoostingClassifier on big data

Feature importance without fooling yourself

Tree models expose feature_importances_, the total impurity decrease each feature caused across all splits. It is computed on training data and it favours features with many distinct values, such as IDs or continuous noise, so a random column can look important.

Permutation importance is more trustworthy. You take a fitted model and a held-out set, shuffle one feature's column, and measure how much the score drops. A big drop means the model relies on that feature for good predictions on new data. Two warnings apply. If two features are strongly correlated, shuffling one barely hurts because the other carries the same information, so both can look unimportant. And importance describes the model, not the real world: it does not tell you that changing a feature would change the outcome.

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Grow and prune a decision tree~40m
  2. 2
    Bag trees into a random forest~40m
  3. 3
    Boost with HistGradientBoosting~40m
  4. 4
    Compare bias, variance and compute~40m
  5. 5
    Inspect feature importance carefully~40m

Key points

  • Bias is error from a model that is too simple; variance is error from a model that is too sensitive to its training data.
  • Random forests reduce variance by averaging; boosting reduces bias by adding trees that correct errors.
  • HistGradientBoostingClassifier and HistGradientBoostingRegressor bin features into histograms, which makes them fast on large tables and lets them handle missing values natively.
  • Impurity-based feature_importances_ favour features with many unique values; prefer permutation importance on held-out data.
  • Forests and boosted models are harder to explain than one tree, so weigh accuracy against the need to justify each prediction.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier

X, y = load_breast_cancer(return_X_y=True)
models = {
    "tree": DecisionTreeClassifier(random_state=0),
    "forest": RandomForestClassifier(n_estimators=300, n_jobs=-1, random_state=0),
    "boosting": HistGradientBoostingClassifier(learning_rate=0.1, random_state=0),
}
for name, m in models.items():
    s = cross_val_score(m, X, y, cv=5, scoring="roc_auc")
    print(f"{name:9s} {s.mean():.3f} +/- {s.std():.3f}")

The spread across folds hints at variance: the single tree usually varies the most.

Watching a tree overfit and pruning it back

Step 1: train trees with max_depth from 1 to 15 on a training set. Step 2: record training and validation accuracy for each. Step 3: plot both. Expect training accuracy to climb to 100 percent while validation accuracy peaks around depth 3 to 6 and then flattens or falls. That gap is variance. Step 4: pick the depth at the validation peak, or use cost_complexity_pruning_path to get candidate ccp_alpha values and choose one by cross-validation.

python
from sklearn.model_selection import validation_curve
from sklearn.tree import DecisionTreeClassifier

depths = list(range(1, 16))
train_s, val_s = validation_curve(
    DecisionTreeClassifier(random_state=0), X_tr, y_tr,
    param_name="max_depth", param_range=depths, cv=5)
for d, t, v in zip(depths, train_s.mean(1), val_s.mean(1)):
    print(f"depth {d:2d} train {t:.3f} val {v:.3f}")

Comparing accuracy, training time and importance

You must recommend a model for a churn table with 50,000 rows. Step 1: time fit for a pruned tree, a random forest and HistGradientBoosting. Step 2: compute ROC-AUC on a validation set. Step 3: run permutation_importance on the validation set for the best model. Step 4: write a short table: score, fit time, prediction time and how easy each is to explain. A typical outcome is boosting slightly ahead on score, the forest close behind and the tree far easier to explain. Your recommendation should name the trade-off, not just the top score.

python
import time
from sklearn.inspection import permutation_importance
from sklearn.metrics import roc_auc_score

for name, m in models.items():
    t0 = time.perf_counter(); m.fit(X_fit, y_fit)
    fit_s = time.perf_counter() - t0
    auc = roc_auc_score(y_val, m.predict_proba(X_val)[:, 1])
    print(f"{name:9s} auc {auc:.3f} fit {fit_s:.2f}s")

r = permutation_importance(models["boosting"], X_val, y_val,
                           scoring="roc_auc", n_repeats=10, random_state=0)
print(r.importances_mean.round(4))

Quick reference

  • Single tree: readable, high variance; prune with max_depth or ccp_alpha
  • Random forest: bootstrap rows plus random features per split, then average
  • RandomForestClassifier max_features default is sqrt; the regressor default is all features
  • HistGradientBoosting: binned features, native missing values, fast on large data
  • Boosting: smaller learning_rate needs more trees; use early stopping
  • Prefer permutation_importance on held-out data over feature_importances_
  • Correlated features share importance, so both can look weak

Common mistakes

  • Reading feature_importances_ as cause and effect, or trusting them when features are correlated.
  • Turning up the number of boosting iterations without early stopping or a validation check, which overfits.
  • Choosing the ensemble without checking whether a simpler, explainable model is nearly as good.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is the main way a random forest improves on a single deep tree?

Question 2

2In gradient boosting, what does each new tree try to predict?

Question 3

3Why can impurity-based feature_importances_ mislead?

Question 4

4Two features carry nearly the same information. What does permutation importance tend to show?

Question 5

5Which change usually makes a boosted model less likely to overfit?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Train a RandomForestClassifier with oob_score=True on the breast cancer data and print the out-of-bag score next to the test accuracy.

  2. Exercise 2medium

    Add a column of random numbers to the data, train a random forest, and compare its impurity importance with its permutation importance on the test set.

  3. Exercise 3hard

    Compare a pruned tree, a random forest and HistGradientBoostingClassifier with 5-fold cross-validated ROC-AUC, and record mean, standard deviation and total fit time for each. Write two sentences recommending one.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Random forest or gradient boosting: which should I try first?
A random forest works well with almost no tuning, so it is a good first ensemble. Gradient boosting often scores a bit higher but needs learning rate and early stopping set sensibly.
Do I need to scale features for tree models?
No. Trees split on thresholds of one feature at a time, so scaling does not change the splits.
What about XGBoost, LightGBM and CatBoost?
They are separate gradient boosting libraries with similar ideas and extra features. HistGradientBoosting in scikit-learn was inspired by LightGBM and is a good starting point without extra installs.
How many trees should a random forest have?
More trees rarely hurt accuracy, only time and memory. A few hundred is usually enough; check that the score has stopped changing as you add more.

Go deeper

ShareXLinkedInWhatsApp