# Random Forest Classifier in Python: A Complete Example

> A complete random forest classifier example in Python with scikit-learn, covering RandomForestClassifier, ROC and confusion matrix plots, out-of-bag error, grid search tuning, and plotting a tree.

Source: https://www.pythoncharts.com/machine-learning/random-forest-classifier-python/ | Published: 2026-11-26 | Author: Alex Scott | Category: Machine Learning | Tags: machine learning, scikit-learn, random forest, classification, hyperparameter tuning, model evaluation, matplotlib

To train a random forest classifier in Python, fit `RandomForestClassifier()` from scikit-learn on training data with `model.fit(X_train, y_train)`, then call `model.predict()` for labels or `model.predict_proba()` for probabilities. The defaults, 100 trees with a random subset of features tried at each split, are a reasonable starting point.

## Quick Example

This example makes up sensor readings for 3,000 industrial pumps and predicts which ones fail within a month. Failures depend on combinations of readings: heat matters most when vibration is also high.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(54)
n = 3000
pumps = pd.DataFrame({
    "temperature": rng.normal(65, 9, n).round(1),
    "vibration": rng.gamma(4, 0.8, n).round(2),
    "pressure": rng.normal(30, 4, n).round(1),
    "hours_since_service": rng.uniform(0, 2000, n).round(),
    "age_years": rng.integers(0, 15, n),
})
hot_and_shaking = (pumps.temperature > 70) & (pumps.vibration > 3.5)
overdue = pumps.hours_since_service > 1400
low_pressure = pumps.pressure < 25
log_odds = (-3.6 + 3.2 * hot_and_shaking + 1.5 * overdue
            + 1.8 * low_pressure + 0.4 * (pumps.vibration - 3.2))
failed = rng.binomial(1, 1 / (1 + np.exp(-log_odds)))

X_train, X_test, y_train, y_test = train_test_split(
    pumps, failed, test_size=0.3, stratify=failed, random_state=54)

forest = RandomForestClassifier(n_estimators=300, min_samples_leaf=5,
                                random_state=54, n_jobs=-1)
forest.fit(X_train, y_train)
probability = forest.predict_proba(X_test)[:, 1]
print("failure rate:", failed.mean().round(3))
print("accuracy:", round(accuracy_score(y_test, forest.predict(X_test)), 3))
print("ROC AUC: ", round(roc_auc_score(y_test, probability), 3))

fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
bins = np.linspace(0, 1, 31)
for value, label, color in [(0, "Kept running", "#0369a1"),
                            (1, "Failed", "#ea580c")]:
    ax.hist(probability[y_test == value], bins=bins, color=color, alpha=0.65,
            density=True, label=label)
ax.set(title="Predicted failure probability on the test set",
       xlabel="Predicted probability of failure", ylabel="Density", xlim=(0, 1))
ax.legend()
plt.show()
```

![Histograms of predicted failure probability, with healthy pumps piled near zero and failed pumps spread across the range up to about 0.93](https://www.pythoncharts.com/machine-learning/random-forest-classifier-python/images/random-forest-quick-example.png)

About 14% of pumps fail. Most healthy pumps get a probability near zero (the median is 0.05), while failed pumps spread out with a median of 0.36. About 17% of the failures still score below 0.1, so the readings don't give every failure away.

## Evaluate a Random Forest with a Confusion Matrix and ROC Curve

Accuracy alone says little when most pumps keep running. Predicting "no failure" for every pump would score 86% on this test set, against the forest's 89%. Look at the errors and at the ranking.

```python
from sklearn.metrics import (ConfusionMatrixDisplay, RocCurveDisplay,
                             classification_report)

print(classification_report(y_test, forest.predict(X_test),
                            target_names=["running", "failed"]))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4.3), layout="constrained")
ConfusionMatrixDisplay.from_estimator(
    forest, X_test, y_test, display_labels=["Running", "Failed"],
    cmap="Oranges", colorbar=False, ax=ax1)
ax1.set_title("Confusion matrix (threshold 0.5)")
RocCurveDisplay.from_estimator(
    forest, X_test, y_test, plot_chance_level=True, ax=ax2,
    curve_kwargs={"color": "#ea580c", "lw": 2})
ax2.set_title("ROC curve")
plt.show()
```

![Confusion matrix with 758 true negatives, 15 false positives, 82 missed failures and 45 caught failures, next to a ROC curve with AUC 0.86](https://www.pythoncharts.com/machine-learning/random-forest-classifier-python/images/random-forest-evaluation.png)

At the default threshold of 0.5, the forest catches 45 of 127 failures and raises 15 false alarms. The ROC curve shows that lower thresholds catch many more: it reaches about 80% of failures at a false positive rate near 20%. If a missed failure costs much more than an inspection, lower the threshold.

## How Many Trees Does a Random Forest Need?

Each tree trains on a bootstrap sample, so some rows are left out of it. `oob_score=True` scores every row using only the trees that never saw it, which estimates test performance without touching the test set. `warm_start=True` adds trees to an existing forest instead of starting over.

```python
tree_counts = range(25, 501, 25)
errors = {}
for leaf in [1, 5, 25]:
    model = RandomForestClassifier(min_samples_leaf=leaf, warm_start=True,
                                   oob_score=True, random_state=54, n_jobs=-1)
    errors[leaf] = []
    for count in tree_counts:
        model.set_params(n_estimators=count).fit(X_train, y_train)
        proba = model.oob_decision_function_[:, 1]
        errors[leaf].append(1 - roc_auc_score(y_train, proba))

fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
for (leaf, values), color in zip(errors.items(), ["#94a3b8", "#0f766e", "#7c3aed"]):
    ax.plot(tree_counts, values, color=color, lw=2,
            label=f"min_samples_leaf={leaf}")
ax.set(title="Out-of-bag error as trees are added", xlabel="Number of trees",
       ylabel="Out-of-bag error (1 − ROC AUC)")
ax.legend()
plt.show()
```

![Out-of-bag error against number of trees for three leaf sizes, flattening early for min_samples_leaf of 25 and still falling slowly for 1](https://www.pythoncharts.com/machine-learning/random-forest-classifier-python/images/random-forest-oob-error.png)

With `min_samples_leaf=25`, the error stops improving after roughly 75 to 125 trees. With fully grown trees (`min_samples_leaf=1`) it is still creeping down at 500, and stays the worst of the three. Adding trees doesn't make a random forest overfit; past the flat part it only costs time. Pick a count where your curve has leveled off.

## Tune Random Forest Hyperparameters

The two settings most worth searching are `max_features`, the number of columns tried at each split, and `min_samples_leaf`, the smallest group a leaf may hold. `GridSearchCV` tries each combination with cross-validation on the training set.

```python
import seaborn as sns
from sklearn.model_selection import GridSearchCV

search = GridSearchCV(
    RandomForestClassifier(n_estimators=300, random_state=54),
    {"max_features": [1, 2, 3, 5], "min_samples_leaf": [1, 5, 15, 40, 100]},
    scoring="roc_auc", cv=5, n_jobs=-1)
search.fit(X_train, y_train)
print(search.best_params_, round(search.best_score_, 4))
print("test AUC:", round(roc_auc_score(
    y_test, search.predict_proba(X_test)[:, 1]), 4))

grid = pd.DataFrame(search.cv_results_["params"])
grid["auc"] = search.cv_results_["mean_test_score"]
table = grid.pivot(index="min_samples_leaf", columns="max_features", values="auc")

fig, ax = plt.subplots(figsize=(7, 4.5), layout="constrained")
sns.heatmap(table, annot=True, fmt=".3f", cmap="mako", ax=ax,
            cbar_kws={"label": "Cross-validated ROC AUC"})
ax.set_title("Grid search results")
plt.show()
```

![Heatmap of cross-validated ROC AUC by max_features and min_samples_leaf, best at 0.868 for 2 features and a leaf size of 40](https://www.pythoncharts.com/machine-learning/random-forest-classifier-python/images/random-forest-tuning-heatmap.png)

The best cross-validated AUC is 0.868, with `max_features=2` and `min_samples_leaf=40`, and the tuned model scores 0.874 on the test set against 0.864 for the first forest. Leaf size matters far more than `max_features` here. A difference of 0.01 on 900 test rows with 127 failures is small enough to be partly luck, so don't expect large gains from tuning a forest.

For larger searches, see how [learning and validation curves](https://www.pythoncharts.com/machine-learning/learning-curve-validation-curve-python/) show the effect of one setting at a time.

## Look Inside the Forest

A forest is a list of decision trees in `forest.estimators_`. `plot_tree` draws one of them. Limit `max_depth` in the plot, because the full tree is too large to read.

```python
from sklearn.tree import plot_tree

fig, ax = plt.subplots(figsize=(12, 5), layout="constrained")
plot_tree(forest.estimators_[0], max_depth=2, feature_names=list(pumps.columns),
          class_names=["running", "failed"], filled=True, impurity=False,
          proportion=True, rounded=True, fontsize=9, ax=ax)
ax.set_title("Top of the first tree in the forest")
plt.show()
```

![Top levels of one decision tree from the forest, splitting first on vibration, then on pressure and hours since service](https://www.pythoncharts.com/machine-learning/random-forest-classifier-python/images/random-forest-tree.png)

This tree splits on vibration first: 34% of its training samples with vibration above 3.775 failed, against 5% below. Each tree sees a different bootstrap sample and random columns, so the others can start differently. No single tree explains the forest's prediction.

To rank features across the whole forest, compare `forest.feature_importances_` with permutation importance, as shown in [feature importance in Python](https://www.pythoncharts.com/machine-learning/feature-importance-python/). [SHAP plots](https://www.pythoncharts.com/machine-learning/shap-plots-python/) explain individual predictions.

## Random Forest Settings Reference

| Parameter | Default | What it controls |
|---|---|---|
| `n_estimators` | 100 | Number of trees. More trees cost time and steady the result |
| `max_features` | `"sqrt"` | Columns tried at each split. Lower values make trees differ more |
| `min_samples_leaf` | 1 | Smallest leaf. Higher values smooth the predictions |
| `max_depth` | `None` | Depth limit. `None` grows trees until leaves are pure or too small |
| `class_weight` | `None` | `"balanced"` gives the rare class more weight |
| `n_jobs` | `None` | Cores used. `-1` uses all of them |

For regression, use `RandomForestRegressor`. It averages the trees' numeric predictions, and its default `max_features` is `1.0` (every column).

## Practical Tips

- Random forests don't need feature scaling.
- Set `random_state` to get the same forest on each run.
- A forest can't predict beyond the range of values it saw in training, which matters for regression on trends.
- Probabilities from a forest are often pulled away from 0 and 1. Check a [calibration curve](https://www.pythoncharts.com/machine-learning/calibration-curve-python/) if you use them as real chances.
- Encode text columns first, for example with `OrdinalEncoder` or `OneHotEncoder` in a pipeline.

## Similar Topics

- [Feature Importance in Python: Impurity vs Permutation Importance](https://www.pythoncharts.com/machine-learning/feature-importance-python/)
- [How to Plot a Decision Tree in Python with scikit-learn](https://www.pythoncharts.com/machine-learning/plot-decision-tree-python/)
- [How to Plot a ROC Curve and Calculate AUC in Python](https://www.pythoncharts.com/machine-learning/roc-curve-auc-python/)
