A Random Forest Classifier combines hundreds of decision trees, each trained on random rows and features, and lets them vote. It is one of the most reliable “works out of the box” classifiers.
Prerequisites
Decision Tree Classification and Random Forest Regression.
How It Votes
Each tree predicts a class; the forest averages the trees’ class probabilities and picks the most likely class. Because each tree sees different data and features, their mistakes are partly independent and cancel out.
Step 1: Data
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import pandas as pd
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
print(X.shape, y.value_counts().to_dict())
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
def evaluate(name, model):
model.fit(X_train, y_train)
p = model.predict(X_test)
print(f'{name:26s} acc={accuracy_score(y_test, p):.3f}')
return model, p
Explanation: We use the built-in Breast Cancer Wisconsin dataset: 569 tumour samples, 30 numeric measurements each, and a label 0 = malignant or 1 = benign. stratify=y keeps the same class balance in the train and test sets. Every classification tutorial in this series uses this exact split, so you can compare algorithms fairly.
(569, 30) {1: 357, 0: 212}
Step 2: Train
from sklearn.ensemble import RandomForestClassifier
rf, prf = evaluate('RF 300', RandomForestClassifier(n_estimators=300, random_state=42, n_jobs=-1))
print(confusion_matrix(y_test, prf))
RF 300 acc=0.947 [[39 3] [ 3 69]]
Rows are the true class, columns the predicted class. Top-left: malignant correctly found. Top-right: malignant tumours wrongly called benign (the most dangerous mistake here). Bottom-left: benign wrongly called malignant. Bottom-right: benign correctly found.
The forest beats a single tree (0.912 unrestricted, 0.939 at depth 3). On this particular dataset scaled logistic regression (0.982) and SVM do even better, because the classes are close to linearly separable. Always compare several models.
Step 3: Feature Importance
print(pd.Series(rf.feature_importances_, index=X.columns).sort_values(ascending=False).round(3).head(5))
Explanation: Size (perimeter, area, radius) and shape (concave points) measurements matter most.
worst perimeter 0.137 worst area 0.137 worst concave points 0.116 mean concave points 0.092 worst radius 0.084 dtype: float64
Useful Parameters
| Parameter | Meaning |
|---|---|
| n_estimators | Number of trees |
| max_depth, min_samples_leaf | Limit tree size |
| max_features | Features per split (‘sqrt’ default for classification) |
| class_weight=’balanced’ | For imbalanced classes |
| oob_score=True | Free validation estimate |
Practice Exercises
- Tune n_estimators and max_features with GridSearchCV.
- Compare permutation importance with feature_importances_.
Interview Questions
Q: How does a random forest reduce overfitting?
By averaging many decorrelated trees, which reduces variance.
Summary
Random forests vote across many randomised trees, need little tuning, and give feature importances, but compare them with simpler models too.
Next: Naive Bayes · XGBoost Classifier
Machine Learning Tutorials, Courses and Certifications