Random Forest in Python with scikit-learn
Let 200 decision trees vote, measure the accuracy and find out which features the forest relies on.
- RandomForestClassifier and n_estimators
- Reading feature_importances_
- Why many trees beat one
- 1
200 treesEach tree votes - 2
benign / malignantCount the votes - 3
benignMajority 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.
n_estimators=200👥 Ask 200 judgesbootstrap samples🎲 Each judge reads a random part of the datapredict(X_test)🗳️ The majority vote is the answerfeature_importances_🔍 Which evidence the judges used mostA 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
n_estimators=200builds 200 trees;random_state=42makes the result repeatable.- The forest classifies 95.8% of the test tumours correctly.
feature_importances_sums to 1; worst perimeter (0.146) and worst area (0.137) come first.- 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
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]])
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.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Common mistakes
Reading impurity importances as the full truth
They favour features with many distinct values; check with permutation_importance on the test set.
forest.feature_importances_ # the only check
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 challengesTools for this lesson
- Classification Basics: Softmax and k-Nearest Neighbors in PythonTurn scores into class probabilities with softmax, score them with cross-entropy and classify points with k-nearest neighbors.
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.