Machine Learning with scikit-learn

Random Forest in Python with scikit-learn

Let 200 decision trees vote, measure the accuracy and find out which features the forest relies on.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • RandomForestClassifier and n_estimators
  • Reading feature_importances_
  • Why many trees beat one
One prediction
  1. 1200 treesEach tree votes
  2. 2benign / malignantCount the votes
  3. 3benignMajority wins

Many trees, one vote

The problem

A single decision tree is easy to read but changes a lot with small changes in the data, and it overfits easily. You want the accuracy and stability of many models without tuning much.

Think of it like this

A random forest is like asking 200 people who each read a different random part of the evidence, then taking a vote. Individual opinions can be wrong, but their mistakes point in different directions and the majority is usually right.

From a panel of judges to code
n_estimators=200👥 Ask 200 judges
bootstrap samples🎲 Each judge reads a random part of the data
predict(X_test)🗳️ The majority vote is the answer
feature_importances_🔍 Which evidence the judges used most
Each tree sees a different random sample.
In one sentence

A random forest trains many decision trees, each on a random sample of the rows and with a random subset of features at every split, and predicts by majority vote.

Key points

  1. n_estimators=200 builds 200 trees; random_state=42 makes the result repeatable.
  2. The forest classifies 95.8% of the test tumours correctly.
  3. feature_importances_ sums to 1; worst perimeter (0.146) and worst area (0.137) come first.
  4. Trees do not need scaled features, so there is no StandardScaler.

When should you use it?

  • A strong default model for tabular data.
  • Finding which features matter most.
  • Problems with non-linear patterns and feature interactions.

When not to use it

  • When the model must be small, fast or easy to explain step by step.
  • Predicting far outside the training range: trees cannot extrapolate.

Example code

Open in editor →
main.py
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
    data.data, data.target, test_size=0.25, random_state=42, stratify=data.target
)

# 200 decision trees, each trained on a random sample of rows and features
forest = RandomForestClassifier(n_estimators=200, random_state=42)
forest.fit(X_train, y_train)
print(f"Test accuracy: {forest.score(X_test, y_test):.3f}")

# Which features did the trees rely on most?
ranked = sorted(zip(forest.feature_importances_, data.feature_names), reverse=True)
print("Top 5 features:")
for importance, name in ranked[:5]:
    print(f"  {name:<22} {importance:.3f}")

print("Prediction for the first test tumour:", data.target_names[forest.predict(X_test[:1])[0]])
Get a Run button for this example

Result of running the code

Test accuracy: 0.958
Top 5 features:
  worst perimeter        0.146
  worst area             0.137
  worst concave points   0.107
  mean concave points    0.104
  worst radius           0.076
Prediction for the first test tumour: benign

Code explanation

n_estimators=200 builds 200 trees, each on a bootstrap sample of the training rows and a random subset of features at every split; random_state=42 makes the result repeatable. The forest classifies 95.8% of the test tumours correctly. feature_importances_ adds up how much each feature improved the splits across all trees, and sorting it shows that the "worst" (largest) perimeter and area matter most. data.target_names turns the predicted class number back into the word benign.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Run in the Python compiler →

Common mistakes

Reading impurity importances as the full truth

They favour features with many distinct values; check with permutation_importance on the test set.

Problem
forest.feature_importances_  # the only check
Fix
permutation_importance(forest, X_test, y_test, random_state=0)

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges

Tools for this lesson