Machine LearningEnsemble Learning

Do Random Forests use L1 regularization, and how is overfitting controlled?

Question 282 of 303 · Updated

On this page

Ordinary Random Forests do not use L1 or L2 coefficient penalties. Unlike linear models, a Random Forest does not learn one coefficient per input feature and minimize an objective such as loss + λΣ|βⱼ|. It builds decision trees using split-quality criteria, then averages their predictions. Overfitting is controlled mainly through tree complexity limits, feature and sample randomness, pruning, careful feature selection, and validation.

A crucial distinction: random feature selection and bootstrap sampling are variance-reduction mechanisms, not L1/L2 coefficient regularization. They make trees less correlated; they do not shrink feature coefficients because a standard forest has no such coefficient vector.

1. What L1 regularization actually does#

In a linear model, predictions may be written as:

LaTeX

L1-regularized regression (Lasso) minimizes an objective of the form:

LaTeX

The penalty discourages large coefficients and can drive some coefficients exactly to zero. This creates a sparse coefficient vector and can perform embedded feature selection.

L2 regularization (Ridge) instead adds:

λΣⱼβⱼ²

It generally shrinks coefficients toward zero without usually making them exactly zero.

A conventional Random Forest is structurally different. Its prediction is an average of tree predictions:

LaTeX

Each tree consists of feature-based split rules and terminal leaves. There is no single βⱼ for each input feature to penalize. Therefore, saying “set L1 alpha higher to regularize a Random Forest” is not meaningful for an ordinary RandomForestClassifier or RandomForestRegressor.

Some other tree-based algorithms and custom differentiable tree models may include explicit penalties, but that does not make L1/L2 coefficient penalties a standard Random Forest control.

2. Split criteria are not L1/L2 coefficient penalties#

At each node, a tree considers candidate feature thresholds and chooses a split that improves a criterion.

For regression, common criteria include:

  • Squared error / variance reduction: favors splits that reduce within-leaf squared deviations; leaf predictions are means.
  • Absolute error: uses absolute deviations and median-valued leaves.
  • Poisson deviance: suitable for certain non-negative count targets.

For classification, common criteria include Gini impurity and entropy (log loss). These criteria measure the quality of a partition. They are not penalties on model coefficients.

A useful nuance: the absolute_error criterion uses an L1-style absolute-deviation loss for choosing regression splits and median leaf predictions. That is not the same thing as L1 coefficient regularization. It does not shrink a vector of feature weights or automatically set feature coefficients to zero.

Similarly, min_impurity_decrease can require a split to achieve a minimum improvement. This limits weak splits, but it is a tree-growth constraint rather than a coefficient penalty.

3. Why Random Forests can still overfit#

A forest averages many trees, which usually reduces variance compared with relying on one unstable tree. But averaging does not guarantee good generalization.

Overfitting can remain when:

  • Trees grow very deep and create leaves containing one or very few training examples.
  • The dataset is small, noisy, or contains many weak predictors.
  • There are leakage features that reveal the target or future information.
  • The forest is repeatedly tuned against the same validation set.
  • Training and validation data do not reflect the same entities, time periods, or production population.
  • A feature has high-cardinality or measurement artifacts that create misleading splits.

A forest with hundreds of very deep trees can still memorize local patterns. More trees usually stabilize the ensemble; they do not necessarily fix an overly flexible tree structure or a biased dataset.

4. Main controls for tree complexity#

A. max_depth#

This sets the maximum number of levels in each tree.

  • Smaller depth produces simpler trees and can reduce variance.
  • Larger depth captures more detailed interactions but can fit noise.
  • None allows trees to continue expanding until other stopping rules apply.

Numerical illustration: Suppose an unrestricted forest achieves training R² = 0.99 but validation R² = 0.72. Limiting trees to depth 8 might produce training R² = 0.91 and validation R² = 0.84. These are illustrative values, not a guaranteed outcome. The validation improvement suggests the original trees were too flexible.

B. min_samples_leaf#

This is the minimum number of training observations required in each terminal leaf. It is often one of the most useful controls for noisy regression problems.

Imagine 1,000 training rows:

  • min_samples_leaf=5 requires at least five observations in every leaf.
  • min_samples_leaf=20 requires at least twenty observations in every leaf.

Larger leaves average over more examples and make predictions smoother. Too large a value can hide genuine local patterns and underfit.

C. min_samples_split#

This is the minimum number of observations required at a node before the algorithm may split it. Raising it prevents small nodes from being divided into increasingly specific branches.

It is related to, but not interchangeable with, min_samples_leaf: a split must also leave enough observations in both resulting leaves.

D. max_leaf_nodes#

This caps the number of terminal leaves. Fewer leaves limit the number of distinct regions the tree can create. It can be useful when you want a direct cap on tree size rather than only a depth limit.

E. min_impurity_decrease#

A candidate split is accepted only if its weighted impurity reduction reaches the configured threshold. A larger threshold rejects small improvements that may reflect noise.

F. Cost-complexity pruning: ccp_alpha#

Pruning removes branches that add too little predictive value relative to their complexity. Minimal cost-complexity pruning balances terminal-node impurity against the number of leaves:

Rα(T) = R(T) + α × |leaves(T)|

Here, α is the pruning strength. At α = 0, no cost-complexity pruning is applied by this mechanism. Larger α favors smaller trees. In scikit-learn, ccp_alpha controls this pruning for each tree in the forest.

A practical approach is to inspect candidate pruning paths on training folds, then choose ccp_alpha using cross-validation. Do not choose it by repeatedly checking the final test set.

5. Randomness: bootstrap sampling and feature subsampling#

Random Forests introduce two important sources of randomness.

A. Bootstrap sampling: bootstrap=True#

Each tree is trained on a sample drawn with replacement from the training dataset.

Suppose the training set has 1,000 rows. A bootstrap sample draws 1,000 times, but some rows are selected multiple times and others are not selected.

The probability that a particular row is never selected is approximately:

LaTeX

So, for a large dataset, each tree uses about 63.2% distinct training rows on average, while roughly 36.8% are left out for that tree. These are expected proportions, not an exact count for every tree.

Different samples make the trees learn from slightly different datasets. Averaging their predictions reduces variance when their errors are not perfectly correlated.

B. Feature subsampling: max_features#

At each split, the tree considers only a random subset of available features.

For example, with 25 input features:

Smaller subsets can reduce correlation between trees, which may improve ensemble generalization. But they can also increase bias because a strong predictor may not be available at a particular split.

This is not feature-coefficient shrinkage. It changes which candidate predictors a tree can inspect at a split; it does not assign an L1 penalty to feature weights.

The best value is data-dependent. Scikit-learn's documented defaults and empirical guidance differ between regression and classification, so tune it rather than assuming one value is universally best.

6. Out-of-bag (OOB) evaluation#

When bootstrap=True, each tree has observations that were not selected for its bootstrap sample. These are its out-of-bag observations.

For a training row, an OOB prediction is formed by aggregating predictions only from trees for which that row was left out. Comparing these predictions with the known training target provides an internal estimate of generalization performance.

For example:

  • Training dataset: 10,000 rows.
  • Each tree leaves out roughly 36.8% of rows.
  • A row receives OOB predictions from the subset of trees that did not train on it.
  • Aggregate the OOB predictions and calculate an appropriate metric such as R², RMSE, accuracy, or another task-specific score.

In scikit-learn, use oob_score=True with bootstrap=True. OOB evaluation is convenient for diagnostics and model comparison, but it is not a replacement for a genuinely independent final test set. It may also be noisy when the forest has too few trees or when the data structure requires grouped or time-aware validation.

7. Feature selection: useful, but not a magic regularizer#

Feature selection can reduce noise, computation, and unnecessary complexity. Options include:

  • Domain-based removal of invalid, duplicated, leakage-prone, or unavailable-at-inference features.
  • Filter methods that rank predictors using training data only.
  • Model-based selection using tree-based importance or permutation importance.
  • Wrapper methods that compare feature subsets using cross-validation.

Be careful with impurity-based feature importance: it can favor high-cardinality variables and distribute importance unpredictably among correlated features. Permutation importance on held-out data can provide a useful complementary view, but correlated predictors can mask one another.

Feature selection must happen inside the training folds during cross-validation. Selecting features once using the full dataset before cross-validation leaks information into the validation folds and makes the estimated performance optimistic.

Also distinguish feature selection from max_features: selection removes or retains columns for the model; max_features randomizes the candidate set separately at each split.

8. A practical tuning example#

Suppose a customer-value regression dataset has 20,000 rows and 30 input features. An initial forest has:

  • Training RMSE = 4.0
  • Validation RMSE = 9.5

The gap suggests overfitting, although the split design and data quality should also be checked.

A sensible tuning experiment might compare:

  • max_depth: 6, 10, 15, and None.
  • min_samples_leaf: 1, 3, 5, 10, and 20.
  • min_samples_split: 2, 5, 10, and 20.
  • max_features: 0.4, 0.7, and 1.0.
  • max_leaf_nodes: selected caps or None.
  • ccp_alpha: 0 and a small range of values derived from pruning paths.
  • n_estimators: enough trees for stable validation/OOB estimates.

Imagine one candidate gives training RMSE = 6.2 and validation RMSE = 7.1. It has a slightly worse training fit but better validation performance. That is often preferable because the objective is performance on unseen data, not memorization of the training set. These numbers are illustrative.

Do not tune every parameter blindly in one huge grid. Start with tree-size controls such as min_samples_leaf and max_depth, then test max_features, pruning, and the number of trees. Use randomized search or another efficient search strategy when the parameter space is large.

9. Correct validation strategy#

  1. Define the prediction task and split correctly. Use random splits only when observations are plausibly independent and identically distributed. Use time-based splits for forecasting and group-based splits when customers, patients, devices, or other entities can appear more than once.
  2. Keep a final test set untouched. Do not use it to choose depth, features, pruning strength, or any other hyperparameter.
  3. Tune on training data with cross-validation. Put preprocessing and feature selection inside a pipeline so each fold learns transformations and selected features from its own training portion.
  4. Compare the right metrics. For regression, consider RMSE, MAE, and R²; for classification, consider metrics aligned with class imbalance and business costs, such as precision, recall, F1, ROC-AUC or PR-AUC.
  5. Inspect the train-validation gap and learning behavior. A large gap may indicate high variance; poor performance on both sets may indicate underfitting, weak features, or a data-quality problem.
  6. Refit the selected configuration on all permitted training data. Evaluate once on the untouched test set.
  7. Validate production relevance. Check temporal stability, segment performance, leakage, missingness, latency, memory, and the availability of every feature at prediction time.

For time-dependent data, ordinary shuffled cross-validation can leak future information into the past. For grouped data, rows from the same entity should not be split across training and validation if that would make the evaluation unrealistically easy.

10. A compact scikit-learn example#

from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import RandomizedSearchCV

forest = RandomForestRegressor( n_estimators=500, bootstrap=True, oob_score=True, random_state=42, n_jobs=-1 )

param_distributions = { "max_depth": [6, 10, 15, None], "min_samples_leaf": [1, 3, 5, 10, 20], "min_samples_split": [2, 5, 10, 20], "max_features": [0.4, 0.7, 1.0], "max_leaf_nodes": [None, 50, 100, 250], "ccp_alpha": [0.0, 0.0001, 0.001, 0.01], }

search = RandomizedSearchCV( estimator=forest, param_distributions=param_distributions, n_iter=40, scoring="neg_root_mean_squared_error", cv=5, random_state=42, n_jobs=-1 )

search.fit(X_train, y_train)

best_forest = search.best_estimator_ print("Best parameters:", search.best_params_) print("Best CV RMSE:", -search.best_score_) print("OOB score:", best_forest.oob_score_)

This example assumes X_train and y_train have already been prepared without leakage. For grouped or temporal data, replace ordinary cv=5 with a suitable group-aware or time-aware splitter. If preprocessing or feature selection is needed, place it in a pipeline and tune the full pipeline.

11. Common misconceptions#

  • “Random Forests use L1 to remove unimportant features.” No. Standard forests do not have L1-penalized feature coefficients. Use a separate feature-selection procedure if needed.
  • “A smaller max_features is L1 regularization.” No. It injects split-level randomness and can reduce tree correlation.
  • “Bootstrap sampling prevents overfitting by itself.” No. It helps decorrelate trees, but trees can still be too complex or learn leakage.
  • “More trees always solve overfitting.” More trees can stabilize the average, but cannot necessarily correct systematic bias, leakage, or overly flexible trees.
  • “OOB score is the final test score.” No. It is an internal estimate derived from training rows and bootstrap exclusions.
  • “Feature importance proves causality.” No. Importance measures model reliance or split contribution under a particular setup; it does not establish causal effect.

12. When should you use which control?#

  • Start with min_samples_leaf when predictions are noisy or individual leaves contain too few examples.
  • Use max_depth or max_leaf_nodes when trees are excessively large.
  • Use max_features when trees are highly correlated and you want more diversity; watch for increased bias.
  • Use ccp_alpha when post-pruning can simplify trees without sacrificing validation performance.
  • Use bootstrap and OOB evaluation for ensemble diversity and a convenient internal diagnostic.
  • Use feature selection when predictors are invalid, redundant, expensive, or noisy; perform it inside cross-validation.
  • Use cross-validation and an untouched test set to decide whether any change genuinely improves generalization.

Bottom line: Ordinary Random Forests do not use L1/L2 coefficient penalties. They control complexity through tree-growth and pruning parameters, while bootstrap sampling and feature subsampling reduce correlation among trees. Tune these mechanisms against correctly structured validation data, and reserve the final test set for one independent assessment.

Related questions

Explore other topics:Deep LearningMLOps