Written and maintained by CASRAI Editorial Board
Published
On this page
RandomForestRegressor is scikit-learn’s random forest for a continuous target: it fits many decision trees on bootstrap samples of the training rows and returns the average of their predictions. You import it from sklearn.ensemble, call fit(X, y) and then predict(X_new); the documentation for scikit-learn 1.9.1 lists 100 trees, squared-error splitting and max_features=1.0 as the defaults. This guide covers the regressor only, with a worked example on the California housing data, how to read R², the out-of-bag estimate and permutation importance, and the errors people hit most. For the classifier see scikit-learn random forest (RandomForestClassifier).
What RandomForestRegressor is used for in research
Researchers use it to predict a numeric outcome from several measured predictors when the relationship may be non-linear or involve interactions, and when they want a strong baseline before trying more elaborate models. Typical outputs are a predicted value per row, a held-out R² and a ranking of which predictors the fitted model relies on. The scikit-learn user guide describes a random forest as an averaging ensemble: each tree is built on a bootstrap sample, and averaging reduces variance compared with a single tree. A single tree is covered in scikit-learn decision trees; R users can find the equivalent workflow in random forests in R.
It is a prediction tool. The importances it produces describe what the fitted model uses, not causal effects, and the documentation’s own caveats on importances (below) apply before you report them in a paper.
Install or access
The official installation page for scikit-learn 1.9.1 gives this command for a pip environment:
pip install -U scikit-learn
and, for conda, conda create -n sklearn-env -c conda-forge scikit-learn followed by conda activate sklearn-env. The class then imports as:
from sklearn.ensemble import RandomForestRegressor
Step-by-step: fit and evaluate a random forest regressor
The steps below use the California housing dataset that ships with scikit-learn. fetch_california_housing returns 20,640 samples with 8 numeric features (MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude); the target is the median house value in units of $100,000. The first call downloads the data and caches it in ~/scikit_learn_data, so it needs network access once.
1. Load the data and hold out a test set
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
2. Create the model
from sklearn.ensemble import RandomForestRegressor
rf = RandomForestRegressor(
n_estimators=100, # the default
min_samples_leaf=5, # limits tree size; an illustrative choice, not a tuned value
oob_score=True, # out-of-bag R2, requires bootstrap=True (the default)
n_jobs=-1, # use all cores
random_state=0, # reproducible trees
)
Every argument after n_estimators is keyword-only. The data table below lists the main parameters with their documented defaults.
3. Fit and predict
rf.fit(X_train, y_train)
pred = rf.predict(X_test)
4. Score it on held-out data
print(rf.score(X_test, y_test)) # R2 on the test set
print(rf.oob_score_) # out-of-bag R2 from the training data
5. Rank the predictors with permutation importance
from sklearn.inspection import permutation_importance
result = permutation_importance(rf, X_test, y_test, n_repeats=5, random_state=0, n_jobs=-1)
for name, mean, std in zip(X.columns, result.importances_mean, result.importances_std):
print(f"{name}: {mean:.3f} +/- {std:.3f}")
As a minimal check that the API behaves as documented, the scikit-learn reference example fits RandomForestRegressor(max_depth=2, random_state=0) on make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) and gets [-8.32987858] from predict([[0, 0, 0, 0]]).
Output and how to read it
R² from score()
score() returns the coefficient of determination R² = 1 − u/v, where u is the residual sum of squares and v the total sum of squares. The best value is 1.0, and it can be negative, because a model can be arbitrarily worse than a baseline. A constant model that always predicts the mean of the training targets scores 0.0. Report the test-set value, not the value on the data the forest was trained on: fully grown trees fit their own training rows very closely, so a training R² near 1 says little.
Out-of-bag estimate
With oob_score=True and bootstrap=True, the forest scores each training row using only the trees whose bootstrap sample left that row out. oob_score_ then holds that score (R² unless you pass your own metric callable) and oob_prediction_ holds the per-row predictions. Both attributes exist only when oob_score is set. The scikit-learn user guide presents this as a generalisation-error estimate that needs no separate validation split, though a held-out test set remains the cleaner final check.
Importances: impurity-based versus permutation
The fitted forest also exposes feature_importances_. The user guide warns that these impurity-based importances are computed from training statistics and favour high-cardinality features, and it points to permutation importance as the alternative. Permutation importance, as documented, should be computed on held-out data; it returns importances_mean, importances_std and the raw importances. Correlated predictors can lower each other’s reported importance, and a feature with low importance for a poor model may matter for a good one.
Parameters that behave differently in the regressor
Most tutorials copy classifier advice. Three details differ for regression.
| Setting | Regressor behaviour (scikit-learn 1.9.1 docs) |
|---|---|
max_features |
Default is 1.0, meaning all features are considered at each split, which makes the ensemble a set of bagged trees. The user guide calls max_features=1.0 (or None) an empirical good default for regression and "sqrt" the good default for classification; it also notes 0.3 as a typical value in the literature. The default changed from "auto" in version 1.1. |
criterion='squared_error' |
Default. Minimises mean squared error, and each leaf predicts the mean of its training targets. |
criterion='absolute_error' |
Minimises mean absolute error, and each leaf predicts the median. |
criterion='poisson' |
Poisson deviance splitting, with leaves using the mean. friedman_mse is deprecated in 1.9. |
monotonic_cst |
Added in 1.4. Takes 1, 0 or -1 per feature to force an increasing, free or decreasing relationship; not supported for multioutput targets. |
Because each leaf predicts a mean or median of training targets, predictions stay within the range of the training targets and the forest cannot extrapolate beyond it (this follows from the leaf rule above, so check it against your data if your new rows lie outside the training range).
Reporting the model reproducibly
Defaults and options in this class have changed between releases: the max_features default moved from "auto" to 1.0 in version 1.1, monotonic_cst arrived in 1.4, and friedman_mse is deprecated in 1.9. For that reason a methods section or code repository should record the scikit-learn version, every non-default argument, the random_state value and how the train and test rows were split. Report the held-out R² alongside the out-of-bag R² if you computed both, state whether importances are impurity-based or permutation-based, and say which data the permutation importances were computed on. These details let a reader rerun the fit and obtain comparable numbers, and they keep the claim in the paper tied to what the documentation actually guarantees.
If you also tune settings, keep the test set out of the search: the cross-validation workflow in GridSearchCV in scikit-learn selects parameters on training folds only, so the final test score stays an unbiased check of the chosen model.
Troubleshooting
Memory use and slow fitting
With the defaults (max_depth=None, min_samples_leaf=1) the trees are grown fully and the documentation warns that they can be very large. Control size with max_depth, min_samples_leaf, max_leaf_nodes or ccp_alpha. More trees help with diminishing returns and cost more compute; n_jobs=-1 uses all cores, though the speed-up is not linear.
AttributeError on oob_score_ or oob_prediction_
These attributes exist only when the model was created with oob_score=True (default False) and bootstrap sampling is on. Refit with oob_score=True.
A negative R²
The model predicts worse on that data than a constant mean would, which scores 0.0. Check that the evaluation rows come from the same distribution as the training rows and that the target was not leaked or shuffled in splitting.
Results change from run to run
Bootstrap sampling and feature sampling are random. Set random_state to an integer to make the fit reproducible.
Old code using max_features=’auto’
The documentation records that the default changed in 1.1 from "auto" to 1.0; use max_features=1.0 explicitly.
Free alternatives and related estimators
| Option | What the documentation says |
|---|---|
| ExtraTreesRegressor (scikit-learn) | Chooses split thresholds at random; the user guide states this lowers variance at the cost of slightly more bias. |
| Single decision tree | Covered in the decision tree guide linked above; easy to inspect but the forest averages many such trees. |
| R randomForest workflow | The equivalent workflow in R is in the R random forest guide linked above. |
| Wider scikit-learn workflow | See the scikit-learn tutorial for splitting, pipelines and metrics. |
scikit-learn itself is free, open-source software.
Frequently asked questions
Is sklearn random forest regressor the same as RandomForestRegressor?
Yes. The phrase refers to sklearn.ensemble.RandomForestRegressor, the regression counterpart of RandomForestClassifier.
What does RandomForestRegressor return when you call predict?
An array with one numeric prediction per input row, the average over all trees, where each tree predicts the mean (or median, with absolute_error) of the training targets in its leaf.
What is the default number of trees?
n_estimators=100.
Which score does score() report?
R², where 1.0 is best, a mean-only predictor scores 0.0 and negative values are possible.
Sources
- scikit-learn 1.9.1: sklearn.ensemble.RandomForestRegressor (read 2026-11-15)
- scikit-learn user guide: Ensembles, random forests (read 2026-11-15)
- scikit-learn user guide: Permutation feature importance (read 2026-11-15)
- scikit-learn: fetch_california_housing (read 2026-11-15)
- scikit-learn: Installing (read 2026-11-15)
Data: RandomForestRegressor main parameters and defaults (scikit-learn 1.9.1)
Main constructor parameters of sklearn.ensemble.RandomForestRegressor with their documented default values and purpose, compiled from the scikit-learn 1.9.1 API reference and the ensemble user guide.
| Parameter | Default value | What it controls |
|---|---|---|
| n_estimators | 100 | Number of trees in the forest |
| criterion | squared_error | Split quality measure; absolute_error and poisson also allowed |
| max_depth | None | Maximum tree depth; None grows trees until leaves are pure or too small |
| min_samples_split | 2 | Minimum samples needed to split a node |
| min_samples_leaf | 1 | Minimum samples in a leaf; raise it to shrink trees |
| max_features | 1.0 | Share of features considered per split; 1.0 means all features |
| bootstrap | True | Whether each tree is trained on a bootstrap sample |
| oob_score | False | Whether to compute the out-of-bag score; needs bootstrap=True |
| max_samples | None | Bootstrap sample size; None draws X.shape[0] rows |
| ccp_alpha | 0.0 | Cost-complexity pruning parameter |
| monotonic_cst | None | Per-feature monotonic constraint (added in 1.4) |
Sources
- scikit-learn 1.9.1: sklearn.ensemble.RandomForestRegressor (accessed 2026-11-15)
- scikit-learn user guide: Ensembles (accessed 2026-11-15)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







