How to choose number of features in random forest?
The max_features hyperparameter controls how many random features are evaluated at each node split in a Random Forest, governing the tradeoff between individual-tree bias and inter-tree correlation. Standard heuristics are sqrt(p) for classification and p/3 for regression, while tuning via cross-validation or Out-of-Bag (OOB) error identifies the optimal dataset-specific value.
Study Card: How to choose number of features in random forest?
Direct Answer
In a Random Forest, max_features ( out of total features) sets the size of the random feature candidate subset tested at each split. It directly controls the correlation among trees and therefore the forest’s bias-variance balance ():
- Smaller
max_features: Forces trees to pick diverse splits, strongly decreasing correlation and ensemble variance, at the cost of higher individual-tree bias if strong features are excluded too often. - Larger
max_features: Lets every tree pick the strongest predictors at each split, lowering individual-tree bias while increasing correlation and ensemble variance (atmax_features = p, Random Forest reduces to standard Bagging).
Classical heuristics recommend for classification (max_features='sqrt', scikit-learn’s classifier default) and for regression (note that scikit-learn’s RandomForestRegressor defaults to max_features=1.0—i.e., Bagging—so tuning max_features in regression is particularly impactful). In practice, tune max_features via cross-validation or Out-of-Bag (OOB) error.
Key Terms
max_features(mtry): Number (or fraction) of candidate features randomly sampled at each node split.- Bootstrap Aggregating (Bagging): Training trees on bootstrap row samples; adding random feature subsampling turns Bagging into Random Forest.
- Out-of-Bag (OOB) Score: Validation accuracy or computed on the ~36.8% of samples omitted from each tree’s bootstrap draw, giving a fast tuning signal without a separate validation split.
- Cross-Validation: -fold validation on the training split to tune
max_featuresjointly withmax_depth,min_samples_leaf, andn_estimators.
Example
Consider predicting customer churn with features, where 3 features are very strong and 22 are weak or noisy:
max_features = 1: Every split gets only 1 random feature. Trees become maximally decorrelated (low pairwise correlation ), yet most splits land on weak noise features, driving up bias and hurting accuracy.max_features = 25(all features): Equivalent to Bagging—each tree still sees a different bootstrap sample of rows, NOT identical data, so trees still differ somewhat; however, every tree greedily splits on the same top 1–2 dominant features near the root, raising correlation and limiting ensemble variance reduction.max_features = 5(): Strikes a strong balance—dominant features appear frequently enough to keep bias low while weaker correlated predictors still get opportunities to diversify tree structures.
Code Implementation
import numpy as np
import pandas as pd
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV, train_test_split
# Load wine dataset (13 features)
data = load_wine()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = data.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
# 1. Tune max_features jointly with depth via Cross-Validation
param_grid = {
'n_estimators': [100, 200],
'max_features': ['sqrt', 'log2', 0.33, 0.5, 1.0],
'max_depth': [4, 6, None],
}
rf = RandomForestClassifier(random_state=0)
grid_search = GridSearchCV(rf, param_grid=param_grid, cv=5, n_jobs=-1)
grid_search.fit(X_train, y_train)
best_model = grid_search.best_estimator_
test_acc = accuracy_score(y_test, best_model.predict(X_test))
print(f"Best CV parameters: {grid_search.best_params_}")
print(f"Test accuracy: {test_acc:.4f}")
# 2. Fast sweep across max_features = 1..p using Out-of-Bag (OOB) score
oob_scores = []
feature_counts = range(1, X.shape[1] + 1)
for m in feature_counts:
rf_oob = RandomForestClassifier(
n_estimators=150, oob_score=True, max_features=m, random_state=42, n_jobs=-1
)
rf_oob.fit(X_train, y_train)
oob_scores.append(rf_oob.oob_score_)
best_oob_m = int(np.argmax(oob_scores) + 1)
print(f"Best OOB max_features: {best_oob_m} (OOB score = {max(oob_scores):.4f})")
Related Concepts
- Bias-Variance Tradeoff: A smaller
max_featuresreduces inter-tree correlation and lowers ensemble variance (while increasing individual-tree bias if too restrictive); a largermax_featuresreduces individual-tree bias at the cost of higher tree correlation and higher ensemble variance. - High-Dimensional / Sparse Noise: When datasets contain many irrelevant features (high with few informative signals), slightly larger
max_featuresthan can help ensure each split tests at least one informative predictor. - ExtraTrees (
ExtraTreesClassifier): Takes randomization further by sampling split thresholds randomly in addition to samplingmax_features, reducing variance further at the cost of slightly higher bias. - Feature Importance Distortion: Larger
max_featuresallows strong correlated features to crowd out substitutes at top splits, altering MDI importance rankings compared to smallermax_features.