Sub topic 13
Limitations and when to choose something else
Random forests are a strong default for tabular data. They also have structural weaknesses, and knowing them tells you when to reach for another model. This chapter assumes you have read the earlier chapters on bagging, feature subsampling, out-of-bag (OOB) estimates, and feature importance. It also assumes you can fit and score a scikit-learn estimator.
Trees cannot extrapolate
A regression tree predicts the mean of the training targets in a leaf. A forest averages those leaf means. So every prediction is a value that lies inside the range of the training targets, and the model is piecewise constant. Outside the range of the training features, it repeats the value from the nearest edge.
The following code trains a forest and a linear model on a straight-line relationship, then asks both for predictions beyond the training range.
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
X_train = rng.uniform(0, 10, size=(500, 1))
y_train = 2 * X_train[:, 0] + rng.normal(0, 0.5, size=500)
forest = RandomForestRegressor(n_estimators=200, random_state=0, n_jobs=-1)
forest.fit(X_train, y_train)
linear = LinearRegression().fit(X_train, y_train)
X_new = np.array([[5.0], [10.0], [15.0], [20.0]])
for x, f, l in zip(X_new[:, 0], forest.predict(X_new), linear.predict(X_new)):
print(f"x={x:>4.1f} truth={2 * x:>5.1f} forest={f:>5.1f} linear={l:>5.1f}")The forest's predictions at x=15 and x=20 stay near 20, the largest target it saw. The linear model follows the trend. This matters in practice for:
- Time series with a trend, such as sales that grow year over year.
- Prices or quantities that drift upward after the training period ends.
- Any deployment where new inputs are systematically larger or smaller than the training inputs.
Common fixes are to model the trend with a linear model and fit the forest to the residuals, to difference the target (predict the change instead of the level), or to use a model that extrapolates.
Axis-aligned splits and smooth structure
Each split tests one feature against one threshold, so decision boundaries are made of rectangles. A diagonal boundary such as x1 > x2 needs many small steps to approximate. Averaging many trees smooths the staircase but does not remove it.
Forests therefore do poorly when the signal is a smooth combination of many features:
- A linear or nearly linear relationship across many features. Logistic or ridge regression is usually more accurate and far smaller.
- Very high-dimensional sparse data, such as bag-of-words text. Most features are zero in most rows, so random feature subsets often contain no useful feature, and a linear model with regularization is typically better.
- Raw perceptual data such as pixels or audio samples. The useful structure lives in combinations of neighboring values, which convolutional or transformer networks learn and trees do not.
If you suspect rotated structure in numeric data, adding rotated or combined features (for example, differences or ratios) can help a forest. This is feature engineering, and it can cost more effort than switching models.
Size, memory, and prediction speed
Fully grown trees have roughly one leaf per training sample, and a forest stores hundreds of them. Training parallelizes well, but the fitted model can be large, and each prediction must traverse every tree.
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
X, y = make_classification(n_samples=20000, n_features=20, n_informative=8,
flip_y=0.05, random_state=0)
for leaf in [1, 20]:
clf = RandomForestClassifier(n_estimators=100, min_samples_leaf=leaf,
n_jobs=-1, random_state=0).fit(X, y)
nodes = sum(t.tree_.node_count for t in clf.estimators_)
print(f"min_samples_leaf={leaf:<3} total nodes across trees: {nodes:,}")Raising min_samples_leaf shrinks the model by a large factor, often with little loss of accuracy. Other levers are max_depth, max_leaf_nodes, and fewer trees. Pickled forests of hundreds of megabytes are common with default settings on large datasets, which matters for serverless functions, mobile devices, and low-latency services.
Probabilities are not calibrated
predict_proba returns the fraction of trees voting for each class (or the average of leaf class fractions). These numbers rank examples well but are not true probabilities. Because averaging pulls estimates toward the middle, a forest tends to be underconfident near 0 and 1. If you need probabilities to compute expected costs, set risk thresholds, or combine with other models, check a reliability curve with sklearn.calibration.calibration_curve and wrap the model in CalibratedClassifierCV.
Class imbalance
Each tree is grown to reduce overall impurity, and the majority class dominates that measure. With a 1% positive rate, a forest can reach 99% accuracy while finding few positives. Options, roughly in order of effort:
- Evaluate with precision, recall, or average precision instead of accuracy.
- Move the decision threshold on
predict_probaaway from 0.5. - Set
class_weight="balanced_subsample", which reweights classes inside each bootstrap sample. - Resample the training data, for example by undersampling the majority class.
Where the OOB estimate misleads
The OOB score assumes rows are independent. If rows are grouped (several records per patient, customer, or device) or ordered in time, a bootstrap sample puts near-duplicates of an out-of-bag row into the trees that "did not see" it. The OOB score then looks better than real performance. Use GroupKFold for grouped data and TimeSeriesSplit for temporal data, and keep any final test set separate from tuning.
Interpretability and importance caveats
A single shallow tree can be read as rules. A forest of 300 deep trees cannot. You get summaries instead: feature importances, partial dependence plots, and SHAP values. These tools describe the model, but they do not make it transparent.
The importance measures also have known flaws. Impurity-based importance favors features with many distinct values or continuous scale, and it is computed on training data, so a noise feature can score high. Permutation importance on held-out data is more reliable, but correlated features share credit: permuting one leaves the other to carry the signal, so both look unimportant. Treat importances as a guide for investigation, not as causal evidence.
Categorical features and missing values
Scikit-learn forests need numeric input, so categorical columns must be encoded first. One-hot encoding a column with thousands of levels creates thousands of sparse binary features, and each split can isolate only one level. Ordinal or target encoding is more compact but brings its own leakage risks, so fit encoders inside a pipeline. Recent scikit-learn versions handle missing values natively in random forests, and older versions need imputation. Check the version you deploy.
Choosing something else
The table maps common situations to alternatives.
| Situation | Why a forest struggles | Better choice |
|---|---|---|
| Tabular data, accuracy is the top priority | Averaging reduces variance but not bias | Gradient boosting (`HistGradientBoostingClassifier`, XGBoost, LightGBM, CatBoost) |
| Extrapolating trends | Predictions stay inside the training range | Linear or additive models, or a forest on residuals |
| Sparse, high-dimensional text | Random subsets miss rare useful features | Regularized logistic regression, linear SVM |
| Images, audio, raw text | Axis-aligned splits on raw values | Neural networks |
| Strict interpretability or auditing | Hundreds of deep trees | Linear models, a single shallow tree, or an explainable boosting machine |
| Tight memory or latency budget | Large model, many traversals per prediction | Small linear model, shallow boosted trees |
| Very noisy small data | Forests are fine, but extra tuning gains little | Keep the forest and spend effort on features |
Gradient boosting deserves a closer look because it is the usual rival. Boosting builds shallow trees sequentially, each one correcting the errors of the previous ones, so it mainly reduces bias. With careful tuning of learning rate, tree count, and depth, it often beats a forest on tabular benchmarks. In exchange, it is more sensitive to hyperparameters and can overfit noisy labels. A forest is more forgiving: its defaults are usually reasonable, and adding trees does not cause overfitting.
A practical habit
Fit a forest early as a baseline. It needs little preprocessing, tolerates unscaled features, and gives an OOB estimate for free. Then compare it against a linear model and a boosted model under the same cross-validation scheme, one that respects groups and time. If a simpler model matches the forest, ship the simpler one. If boosting wins clearly, the forest has still told you what accuracy is easy to reach.
Exercise
You trained a RandomForestRegressor on house prices from 2015 to 2019 and now predict prices for 2024 listings. Offline cross-validation (random splits) shows a small error, but predictions for 2024 are consistently too low. Give two reasons the validation was misleading and one fix.
Show answer
First, random splits mix years, so the validation rows always have training rows from the same period. The model never faces the case of predicting beyond the training period, which is how it is used. Second, trees cannot extrapolate. If prices rose after 2019, a forest predicts values near the highest prices it saw, which makes its predictions too low. A fix is to validate with TimeSeriesSplit (train on earlier years, test on later ones) and to model the trend explicitly, for example by predicting price relative to a year or regional baseline, or by fitting a linear trend and training the forest on the residuals.
Exercise
A fraud model has 0.5% positive cases. A random forest scores 99.5% accuracy but flags almost no fraud. Name two changes within scikit-learn that address this, and the metric you would report instead of accuracy.
Show answer
Set classweight="balancedsubsample" in RandomForestClassifier, and lower the decision threshold on predict_proba so more cases are flagged (choose the threshold on validation data, not the test set). Report recall and precision at the chosen threshold, or average precision (the area under the precision-recall curve), since accuracy is dominated by the majority class.