A Random Forest trains many decision trees, each on a random sample of rows and features, and averages their predictions. The averaging cancels out much of the individual trees’ noise, giving a stronger and more stable model.
What You Will Learn
- Bagging and random feature selection
- Training a RandomForestRegressor
- Feature importance
- Out-of-bag (OOB) evaluation
Prerequisites
How It Works
1. Draw a random sample of training rows with replacement (a bootstrap sample).
2. Grow a tree on it, but at each split consider only a random subset of features.
3. Repeat for many trees (e.g. 300).
4. Predict by averaging all trees.
Step 1 is called bagging. The random feature choice makes the trees different from each other, which is what makes averaging work.
Step 1: Data and Helper
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
X, y = load_diabetes(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
def evaluate(name, model):
model.fit(X_train, y_train)
p = model.predict(X_test)
print(f'{name:22s} R2={r2_score(y_test, p):.3f} RMSE={np.sqrt(mean_squared_error(y_test, p)):.1f} MAE={mean_absolute_error(y_test, p):.1f}')
return model
Explanation: We use scikit-learn’s built-in diabetes dataset: 442 patients, 10 features (age, sex, BMI, blood pressure and six blood measurements, already scaled), and a target measuring disease progression one year later. It is a genuinely hard problem, so do not expect R² close to 1. The helper function trains a model and prints its test scores.
Step 2: Train the Forest
from sklearn.ensemble import RandomForestRegressor
rf = evaluate('RF 300', RandomForestRegressor(n_estimators=300, random_state=42, n_jobs=-1))
Explanation: The forest (R²=0.434) is far better than a single fully grown tree (0.061 on the same split) and close to linear regression (0.453). On this small dataset the relationship is mostly linear, so linear regression is hard to beat. That is a useful lesson: always compare with a simple baseline.
RF 300 R2=0.434 RMSE=54.8 MAE=44.6
Step 3: Feature Importance
print(pd.Series(rf.feature_importances_, index=X.columns).sort_values(ascending=False).round(3).head(5))
Explanation: BMI and s5 drive most of the predictions. Impurity-based importance can favour features with many unique values; for a more reliable check use sklearn.inspection.permutation_importance.
bmi 0.346 s5 0.245 bp 0.088 s6 0.068 s2 0.059 dtype: float64
Step 4: Out-of-Bag Score
rf2 = RandomForestRegressor(n_estimators=300, oob_score=True, min_samples_leaf=5,
random_state=42, n_jobs=-1).fit(X_train, y_train)
print('oob', round(rf2.oob_score_, 3), 'test', round(rf2.score(X_test, y_test), 3))
Explanation: Each tree never sees about a third of the rows. Scoring each row only with trees that did not train on it gives the OOB score, a free estimate of test performance. Here it (0.452) closely matches the real test score (0.459). Setting min_samples_leaf=5 also improved the test score slightly.
oob 0.452 test 0.459
Key Parameters
| Parameter | Meaning |
|---|---|
| n_estimators | Number of trees (more is better up to a point, but slower) |
| max_features | Features tried per split (1.0 = all for regression by default) |
| max_depth / min_samples_leaf | Limit each tree |
| bootstrap | Sample rows with replacement |
| n_jobs=-1 | Use all CPU cores |
Pros and Cons
| Advantages | Disadvantages |
|---|---|
| Accurate with little tuning | Larger and slower than one tree |
| Resistant to overfitting | Hard to interpret as rules |
| No scaling needed | Cannot extrapolate beyond the training target range |
Practice Exercises
- Plot test R² against n_estimators from 10 to 500.
- Compute permutation importance and compare with feature_importances_.
- Compare with XGBoost on the same split.
Interview Questions
Q: What is bagging?
Training models on bootstrap samples and averaging them to reduce variance.
Q: Why random feature subsets?
To decorrelate trees so averaging is more effective.
Q: What is the OOB score?
Validation using the rows each tree did not see during training.
Summary
Random forests average many decorrelated trees. Train with RandomForestRegressor, check OOB and test scores, read feature importances, and always compare with a simple baseline.
Next: XGBoost · Decision Tree Classification
Machine Learning Tutorials, Courses and Certifications