A random forest is a machine learning model that trains hundreds of decision trees, each on a slightly different version of the data, and averages their predictions. It works well out of the box on tables of data, handles a mix of numeric and categorical columns, and needs little tuning, which is why it’s one of the most widely used models in practice.
This guide explains how a random forest works, then builds one step by step in Python with scikit-learn to predict who survived the Titanic. Every output shown is what the code printed when we ran it.
How a random forest works
A single decision tree is easy to understand but unstable: small changes in the training data can produce a very different tree, and a fully grown tree memorizes noise. A random forest fixes this by building many trees that make different mistakes and letting them average each other out. Two sources of randomness make the trees different:
- Bootstrap sampling (bagging). Each tree is trained on a random sample of the rows, drawn with replacement. Some rows appear several times and about a third are left out.
- Random feature selection. At every split, a tree only considers a random subset of the columns. This stops every tree from splitting on the same strongest column first.
To make a prediction, the forest asks every tree and averages the answers: the mean predicted probability for classification, the mean predicted value for regression.

Step 1: Load the data
pip install scikit-learn pandas seaborn matplotlibThe Titanic dataset has one row per passenger, with their ticket class, sex, age, family aboard, fare and port of embarkation, and whether they survived. Seaborn downloads it the first time you load it.
import pandas as pd
import seaborn as sns
df = sns.load_dataset("titanic")
features = ["pclass", "sex", "age", "sibsp", "parch", "fare", "embarked"]
df = df[features + ["survived"]]
print(df.shape)
print(df.isna().sum()[lambda s: s > 0])
print("survival rate:", round(df["survived"].mean(), 3))Output:
(891, 8)
age 177
embarked 2
dtype: int64
survival rate: 0.384891 passengers, 38.4% of whom survived. Age is missing for 177 of them and port of embarkation for 2.
Step 2: Prepare the features
Scikit-learn models need numbers, so turn the text columns into 0/1 columns with get_dummies. Then hold back a quarter of the passengers as a test set.
from sklearn.model_selection import train_test_split
X = pd.get_dummies(df[features], columns=["sex", "embarked"], drop_first=True, dtype=int)
y = df["survived"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
print(X.columns.tolist())
print(X_train.shape, X_test.shape)Output:
['pclass', 'age', 'sibsp', 'parch', 'fare', 'sex_male', 'embarked_Q', 'embarked_S']
(668, 8) (223, 8)Notice that the missing ages are still there. Since version 1.4, scikit-learn’s random forests handle missing values on their own: at each split, a tree learns which side to send the rows with a missing value. With older versions, fill them first, for example with the median age.
Step 3: Compare a single tree with a forest
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
tree = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
forest = RandomForestClassifier(n_estimators=300, random_state=0).fit(X_train, y_train)
for name, model in [("Decision tree", tree), ("Random forest", forest)]:
print(f"{name:14} train {model.score(X_train, y_train):.3f} test {model.score(X_test, y_test):.3f}")Output:
Decision tree train 0.982 test 0.771
Random forest train 0.982 test 0.753Both models score 98.2% on the data they were trained on, a sign that both have memorized it. On the test set, the single tree actually looks slightly better here. Does that mean a random forest isn’t worth it?
No. A test set of 223 passengers is small, and one split can easily flatter one model by a couple of points. Cross-validation gives a fairer comparison by training and testing on 10 different splits and averaging:
from sklearn.model_selection import cross_val_score
for name, model in [("Decision tree", DecisionTreeClassifier(random_state=0)),
("Random forest", RandomForestClassifier(n_estimators=300, random_state=0))]:
scores = cross_val_score(model, X, y, cv=10)
print(f"{name:14} mean {scores.mean():.3f} std {scores.std():.3f}")Output:
Decision tree mean 0.785 std 0.046
Random forest mean 0.805 std 0.047Across 10 splits, the forest is two points more accurate on average. With small datasets, always compare models with cross-validation rather than a single test score.
Look inside the forest
What bootstrap sampling does
Here’s one bootstrap sample of the 668 training rows:
import numpy as np
rng = np.random.default_rng(0)
n = len(X_train)
sample = rng.integers(0, n, size=n) # draw n rows with replacement
print("rows drawn:", n)
print("unique rows:", len(np.unique(sample)), f"({len(np.unique(sample)) / n:.1%})")Output:
rows drawn: 668
unique rows: 411 (61.5%)Drawing 668 rows with replacement picks only 411 different rows, about 62%. In theory the share approaches 63.2% for large datasets. Each tree never sees the other ~37% of rows, which is what makes the trees different from each other, and is also useful for validation, as you’ll see below.
How trees combine into one prediction
The trained trees are stored in forest.estimators_. Ask each one about the first four test passengers:
passengers = X_test.iloc[:4]
tree_probs = np.array([t.predict_proba(passengers.to_numpy())[:, 1] for t in forest.estimators_])
print("first 5 trees:")
print(tree_probs[:5].round(2))
print("average of all 300 trees:", tree_probs.mean(axis=0).round(2))
print("forest.predict_proba: ", forest.predict_proba(passengers)[:, 1].round(2))
print("actual outcome: ", y_test.iloc[:4].to_numpy())Output:
first 5 trees:
[[0. 1. 1. 0.88]
[0. 1. 1. 0.71]
[0. 1. 0. 1. ]
[0. 1. 0. 1. ]
[0. 1. 1. 1. ]]
average of all 300 trees: [0.12 0.89 0.57 0.83]
forest.predict_proba: [0.12 0.89 0.57 0.83]
actual outcome: [0 0 0 1]Individual trees are confident and often disagree: for the third passenger, some trees say certain survival and others certain death. The forest’s probability is simply the average across all 300 trees, as the last two lines show. The third passenger gets 0.57, a genuinely uncertain case, and the second gets 0.89 but in fact did not survive. Averaging reduces mistakes; it doesn’t remove them.
Step 4: Use out-of-bag accuracy instead of a validation set
Because each tree skips about a third of the rows, every training row can be predicted by the trees that never saw it. The accuracy of those predictions is the out-of-bag (OOB) score, a free estimate of how the model will do on new data, without setting aside a separate validation set.
forest_oob = RandomForestClassifier(n_estimators=300, oob_score=True, random_state=0)
forest_oob.fit(X_train, y_train)
print("OOB accuracy: ", round(forest_oob.oob_score_, 3))
print("test accuracy:", round(forest_oob.score(X_test, y_test), 3))Output:
OOB accuracy: 0.822
test accuracy: 0.753The OOB accuracy of 82.2% is close to the 80.5% cross-validated estimate. The test score is lower again, a reminder that 223 passengers is a noisy sample: its standard error is about 3 points.
Step 5: How many trees do you need?
for n_trees in [20, 50, 100, 200, 300, 500, 1000]:
rf = RandomForestClassifier(n_estimators=n_trees, oob_score=True, random_state=0)
rf.fit(X_train, y_train)
print(f"{n_trees:5} trees OOB accuracy {rf.oob_score_:.3f}")Output:
20 trees OOB accuracy 0.798
50 trees OOB accuracy 0.813
100 trees OOB accuracy 0.819
200 trees OOB accuracy 0.820
300 trees OOB accuracy 0.822
500 trees OOB accuracy 0.820
1000 trees OOB accuracy 0.823
Accuracy rises quickly and then levels off at around 100 to 200 trees. More trees never make a random forest overfit; they only cost training time and memory. A few hundred is a sensible default, and n_estimators is rarely the setting worth tuning.
Step 6: Tune the settings that matter
These are the settings that change results the most:
| Setting | What it controls | scikit-learn default |
|---|---|---|
max_features | How many columns each split may consider. Lower values make trees more different from each other. | "sqrt" for classification, 1.0 (all) for regression |
min_samples_leaf | The smallest number of rows allowed in a leaf. Higher values make smoother, simpler trees. | 1 |
max_depth | The maximum depth of each tree. | None (grow until leaves are pure) |
n_estimators | The number of trees. | 100 |
Search over combinations with 5-fold cross-validation on the training set:
from sklearn.model_selection import GridSearchCV
grid = {
"max_features": ["sqrt", 0.5, None],
"min_samples_leaf": [1, 3, 5, 10],
"max_depth": [None, 6, 10],
}
search = GridSearchCV(RandomForestClassifier(n_estimators=300, random_state=0),
grid, cv=5, n_jobs=-1)
search.fit(X_train, y_train)
print("best settings:", search.best_params_)
print("cross-validated accuracy:", round(search.best_score_, 3))
print("test accuracy:", round(search.score(X_test, y_test), 3))Output:
best settings: {'max_depth': 10, 'max_features': 'sqrt', 'min_samples_leaf': 1}
cross-validated accuracy: 0.838
test accuracy: 0.776Limiting trees to a depth of 10 gives the best cross-validated accuracy, 83.8%. Capping depth stops the trees from memorizing individual passengers.
For a final, fair comparison, score each model with 10-fold cross-validation on all 891 passengers. Logistic regression needs the missing ages filled in, so it gets a median imputer in a pipeline:
from sklearn.linear_model import LogisticRegression
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
models = {
"Decision tree": DecisionTreeClassifier(random_state=0),
"Logistic regression": make_pipeline(SimpleImputer(strategy="median"), StandardScaler(),
LogisticRegression(max_iter=1000)),
"Random forest (default)": RandomForestClassifier(n_estimators=300, random_state=0),
"Random forest (tuned)": RandomForestClassifier(n_estimators=300, random_state=0, **search.best_params_),
}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=10)
print(f"{name:24} {scores.mean():.3f}")Output:
Decision tree 0.785
Logistic regression 0.793
Random forest (default) 0.805
Random forest (tuned) 0.828| Model | 10-fold accuracy |
|---|---|
| Decision tree | 78.5% |
| Logistic regression | 79.3% |
| Random forest, default settings | 80.5% |
| Random forest, tuned | 82.8% |
Step 7: Which features matter?
Random forests report a feature importance for every column. The built-in version measures how much each column reduced impurity across all the splits in all the trees:
best = search.best_estimator_
impurity = pd.Series(best.feature_importances_, index=X.columns)
print(impurity.sort_values(ascending=False).round(3))Output:
sex_male 0.284
fare 0.250
age 0.227
pclass 0.103
sibsp 0.051
parch 0.047
embarked_S 0.028
embarked_Q 0.011
dtype: float64Fare and age rank almost as high as sex. Be careful with this: impurity-based importance is known to favor columns with many distinct values, such as fare and age, because they offer many possible split points. Permutation importance is more reliable. It shuffles one column at a time in the test set and measures how much accuracy drops:
from sklearn.inspection import permutation_importance
perm = permutation_importance(best, X_test, y_test, n_repeats=30, random_state=0)
perm_imp = pd.Series(perm.importances_mean, index=X.columns)
print(perm_imp.sort_values(ascending=False).round(3))Output:
sex_male 0.167
pclass 0.054
age 0.032
fare 0.011
embarked_Q 0.010
sibsp 0.006
parch -0.010
embarked_S -0.011
dtype: float64import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 4))
pd.DataFrame({"impurity": impurity, "permutation": perm_imp}).sort_values("permutation").plot.barh(ax=ax)
ax.set_xlabel("Importance")
plt.show()
Now the picture is clearer. Sex is by far the most important feature, followed by ticket class and age. Shuffling fare barely hurts accuracy, because most of what fare tells you is already captured by ticket class. Small negative values, like those for parch and embarked_S, mean the column made no real difference and the score moved by chance.
Step 8: Make predictions
Two hypothetical passengers, identical except for sex, class and fare:
new = pd.DataFrame([
{"pclass": 1, "age": 30, "sibsp": 0, "parch": 0, "fare": 80.0, "sex_male": 0, "embarked_Q": 0, "embarked_S": 1},
{"pclass": 3, "age": 30, "sibsp": 0, "parch": 0, "fare": 8.0, "sex_male": 1, "embarked_Q": 0, "embarked_S": 1},
])[X.columns]
print(best.predict_proba(new)[:, 1].round(2))Output:
[0.98 0.22]A 30-year-old woman in first class: 98% chance of survival. A 30-year-old man in third class: 22%. New data must have the same columns, in the same order, as the training data, which is why the code selects X.columns.
Random forests for regression
The same idea works for predicting numbers: RandomForestRegressor averages the trees’ predicted values. Here it predicts disease progression in scikit-learn’s built-in diabetes dataset, compared with linear regression:
from sklearn.datasets import load_diabetes
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
Xd, yd = load_diabetes(return_X_y=True)
for name, model in [("Linear regression", LinearRegression()),
("Random forest", RandomForestRegressor(n_estimators=300, min_samples_leaf=5, random_state=0))]:
r2 = cross_val_score(model, Xd, yd, cv=5, scoring="r2").mean()
print(f"{name:18} R^2 {r2:.3f}")Output:
Linear regression R^2 0.482
Random forest R^2 0.443Linear regression wins here. The diabetes data has only 442 patients, and the relationships are mostly linear, which is exactly where a straight-line model is hard to beat. A random forest is a strong default, not a guaranteed winner: always compare it with a simple baseline.
Random forest vs. decision tree vs. gradient boosting
| Decision tree | Random forest | Gradient boosting | |
|---|---|---|---|
| How trees are built | One tree | Many independent trees, averaged | Many trees in sequence, each fixing the last one’s errors |
| Overfitting risk | High | Low | Medium; needs early stopping |
| Tuning needed | Some | Little | More |
| Typical accuracy on tables | Lowest | High | Often highest |
| Interpretability | Easy to read | Feature importances only | Feature importances only |
| Training | Fast | Parallel, fast | Sequential, but libraries are highly optimized |
If you need the last few points of accuracy on tabular data, try XGBoost, LightGBM or CatBoost. If you want a strong model with almost no tuning, a random forest is hard to beat.
Pros and cons
- Pros: accurate with default settings; hard to overfit by adding trees; handles mixed feature types, non-linear relationships and interactions; no feature scaling needed; built-in OOB validation; trains in parallel.
- Cons: less interpretable than a single tree; large models use a lot of memory; slower to predict than a linear model; can’t predict values outside the range seen in training (for regression); usually a little less accurate than well-tuned gradient boosting.
Common mistakes
- Judging the model on one small test split. As Step 3 showed, a single split can make a worse model look better. Use cross-validation or the OOB score.
- Trusting impurity-based importance. It inflates columns with many unique values. Check permutation importance before drawing conclusions.
- Tuning the number of trees instead of tree shape.
max_features,min_samples_leafandmax_depthchange results far more thann_estimators. - Expecting it to extrapolate. A regression forest can only predict values between the smallest and largest targets it saw in training.
- Using a forest on an imbalanced problem without checking. Set
class_weight="balanced"or look beyond accuracy, at precision and recall, when one class is rare.
Keep learning
- Decision trees: the building block of a random forest
- XGBoost vs LightGBM vs CatBoost: gradient boosting, the main alternative
- AdaBoost: the original boosting method
- Build a machine learning model with scikit-learn
The scikit-learn user guide on random forests documents every parameter used in this tutorial.
FAQ
What is a random forest in simple terms?
It’s a group of decision trees, each trained on a random sample of the data and a random subset of features. The forest predicts by averaging what all the trees say, which is more accurate and more stable than any single tree.
Why is it called a random forest?
Because it’s made of many trees (a forest), and randomness is used twice when building them: each tree gets a random bootstrap sample of the rows, and each split considers a random subset of the columns.
Can a random forest overfit?
Adding more trees doesn’t cause overfitting. Individual trees can still be too complex, though, so limiting max_depth or raising min_samples_leaf can help, as it did on the Titanic data.
How many trees should a random forest have?
A few hundred is usually enough. On the Titanic data, accuracy stopped improving at around 100 to 200 trees. More trees cost time but never hurt accuracy.
Do I need to scale features for a random forest?
No. Trees split on thresholds, so scaling a column doesn’t change the result. You do need to turn text categories into numbers.
Is a random forest better than gradient boosting?
Not usually in raw accuracy; well-tuned gradient boosting often wins by a small margin on tabular data. Random forests are easier to tune and harder to break, so they’re a great first model.
Free tool: To work out precision, recall, F1 and MCC from your own model’s results, use our free confusion matrix calculator.
