Random Forest Algorithm: Meaning, How-to, Examples

A random forest builds many decision trees and lets them vote. Learn how it works, how to run it in Python and when to pick something else.

Smiling data analyst at a laptop reviewing charts from a random forest model
Photo: Pexels

The random forest algorithm is a machine learning method that builds many decision trees and then combines their answers. For a yes or no question, each tree casts a vote and the forest picks the class with the most votes. For a number, such as a house price, the forest takes the average of all the trees.

Random forest is the right first model for most table data, the kind you keep in a spreadsheet or a SQL table. It works well with almost no tuning, it does not need scaled inputs, and it is hard to overfit badly. However, XGBoost and LightGBM usually win once you have time to tune them. A plain linear model is the better choice when you must explain every coefficient to a regulator.

Next, you will see what the method means and how a forest makes a prediction. After that come the scikit-learn settings, a Python example with real test results, and tuning tips. The post ends with real use cases and the limits to know before you ship one.

What the Random Forest Algorithm Means

A single decision tree asks a chain of yes or no questions about your data. For example, the single tree in the Python test further down first asks if a tumor’s worst radius is above 16.8. If not, it then asks if its worst concave points score is above 0.136. Each path ends in a leaf that gives an answer. The trouble is that one deep tree learns the training data too closely, so small changes in the data give you a very different tree.

So a random forest grows many trees and makes each one a little different on purpose. Leo Breiman set out the method in his 2001 paper Random Forests in the journal Machine Learning. The idea behind it fits in one line: many trees that make different mistakes will cancel out each other’s errors when they vote.

The forest adds randomness in two places. First, each tree trains on a bootstrap sample, which is a random draw of rows taken with replacement. Second, each split inside a tree looks at only a random subset of the columns. As a result, no single dominant column can control every tree.

How a Random Forest Makes a Prediction, Step by Step

The training loop is short. Here are the steps for a forest of 100 trees on a table with 426 rows and 30 columns.

  1. Draw 426 rows at random with replacement. Some rows appear twice and about a third are left out.
  2. Grow a decision tree on those rows. At each split, pick a random set of about 5 columns (the square root of 30) and choose the best split among only those.
  3. Keep splitting until the leaves are pure, with no pruning.
  4. Repeat steps 1 to 3 until you have 100 trees.
  5. To predict a new row, send it down all 100 trees and count the votes, or take the average for a number.

A worked voting example with five trees

Say five trees look at one patient record. Three trees say benign and two say malignant. The forest predicts benign, with a vote share of 3 out of 5, or 60%.

In fact, scikit-learn goes one step further. It averages each tree’s class probabilities, then picks the class with the highest average. In the Python test further down, one record got a 0.70 score for benign and 0.30 for malignant. That tells you the forest was far less sure about it than about a record that scored 0.98.

Out-of-bag rows give a free test score

Each tree never sees the rows left out of its bootstrap sample. So you can test each row on only the trees that did not train on it. This out-of-bag (OOB) score works like a built-in validation set. In scikit-learn, you turn it on with oob_score=True.

Random Forest Settings in scikit-learn

Most people run random forests through scikit-learn. The defaults in the RandomForestClassifier docs for version 1.9.1 are a sound place to begin.

scikit-learn documentation page for the RandomForestClassifier class
Screenshot: scikit-learn.org
SettingDefaultWhat it controlsWhen to change it
n_estimators100How many trees you growRaise it if scores still move between runs
max_featuressqrt for classifiers, 1.0 for regressorsHow many columns each split can look atLower it to make trees more different
max_depthNoneHow deep each tree can growSet it to cut memory and training time
min_samples_leaf1Fewest rows allowed in a leafRaise it to 5 or 10 on noisy data
bootstrapTrueEach tree gets a random row sampleRarely changed
oob_scoreFalseBuilt-in test score on left-out rowsTurn it on for a quick check
n_jobsNone, which means 1 coreHow many CPU cores to useSet -1 to use all cores
class_weightNoneExtra weight for rare classesUse balanced for rare events like fraud

Note the regressor default. RandomForestRegressor uses every column at each split, so its trees are more alike than a classifier’s trees. If your regression forest overfits, try max_features=0.33 or "sqrt".

Read also: Data Annotations: Meaning, Examples and Guide

How to Build a Random Forest in Python

The example uses the breast cancer data set that ships with scikit-learn. It has 569 tumor records, 30 measured features and two classes: 212 malignant and 357 benign. The code sets aside 25% of the rows for testing.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, confusion_matrix

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y)

tree = DecisionTreeClassifier(random_state=42).fit(X_train, y_train)
print("One tree:", accuracy_score(y_test, tree.predict(X_test)))

forest = RandomForestClassifier(n_estimators=100, oob_score=True,
                                random_state=42, n_jobs=-1)
forest.fit(X_train, y_train)
pred = forest.predict(X_test)
print("Forest:", accuracy_score(y_test, pred))
print("OOB score:", forest.oob_score_)
print(confusion_matrix(y_test, pred))

Results from the Python example

Running that code on scikit-learn 1.9.1 gives these numbers on the 143 test rows:

ModelTest accuracyWrong answers out of 143Five-fold cross-validation
One decision tree92.3%1191.7%
Random forest, 100 trees95.8%695.6%

The forest’s OOB score was 96.2%, close to its 95.8% test score. So the OOB check gave a fair preview without a separate test set. Also, the confusion matrix showed 4 malignant tumors labeled benign and 2 benign tumors labeled malignant. In a medical setting, those 4 misses matter more than the 2 false alarms. That is why you would tune the decision threshold before anyone relied on a model like this.

How Many Trees a Random Forest Needs

More trees never make a random forest worse on average, but the gains flatten fast. On the same data, the test score climbed from 92.3% with one tree to 95.1% with 10 trees. It then reached 95.8% at 100 trees and stayed there at 200 and 500.

Bar chart of random forest test accuracy on breast cancer data from 92.3 percent with one tree to 95.8 percent with 100 to 500 trees
Chart: Bizolaunch

In practice, 100 to 300 trees is enough for most table data. Beyond that, you pay for each extra tree in training time, memory and prediction speed. The 100-tree forest here had 3,388 nodes in total, and its trees reached an average depth of 7.

How to Tune a Random Forest Without Wasting Hours

Tuning a random forest is mostly about three settings: max_features, min_samples_leaf and max_depth. So a small grid search with five-fold cross-validation covers most of the ground.

from sklearn.model_selection import GridSearchCV

grid = {"max_features": ["sqrt", 0.5],
        "min_samples_leaf": [1, 3, 5],
        "max_depth": [None, 8]}
search = GridSearchCV(
    RandomForestClassifier(n_estimators=200, random_state=42, n_jobs=-1),
    grid, cv=5, n_jobs=-1)
search.fit(X_train, y_train)
print(search.best_params_, search.best_score_)

On the tumor data, this search tried 12 setting combos. It picked max_features="sqrt", min_samples_leaf=1 and no depth cap, which are the defaults. Its cross-validation score was 96.0%, and the test score stayed at 95.8%.

That result is common for random forests. The defaults are hard to beat, so spend your time on better columns and cleaner labels first. Then tune if you have a large data set where a deeper search can find a real gain.

How to Read Random Forest Feature Importance

A fitted forest gives you feature_importances_, which scores how much each column cut impurity across all splits. In the example, the top five were worst area, worst concave points, mean concave points, worst radius and worst perimeter.

Bar chart of the top five impurity-based feature importances in a 100-tree random forest, led by worst area at 0.150
Chart: Bizolaunch

Be careful with these scores, though. Impurity-based importance favors columns with many unique values, and it spreads credit across columns that carry the same signal. For instance, worst area, worst radius and worst perimeter all measure tumor size, so they share the credit.

For a fairer view, use permutation_importance from sklearn.inspection. It shuffles one column at a time on the test set and measures how much the score drops. On the same forest, the top permutation scores went to concave points error, worst texture and mean texture instead. Both rankings are correct answers to different questions, so report which one you used.

Random Forest Examples in Real Work

Random forests show up wherever data comes in rows and columns. Common uses include these, each, with the kind of columns the model reads.

  • Credit scoring. A lender predicts default from income, loan size, past late payments and account age.
  • Fraud checks. A card issuer flags odd charges from amount, merchant type, time of day and distance from home. Set class_weight="balanced" because fraud is rare.
  • Customer churn. A telecom or SaaS firm predicts who will cancel from logins, support tickets and plan changes.
  • Medical risk. A hospital team scores risk from lab values and heart rate readings, like the tumor data in the example.
  • Land cover maps. Remote sensing teams label each pixel as water, forest, crop or city from satellite band values.
  • Price estimates. A property site estimates home prices with RandomForestRegressor from size, rooms, location and age.

If you work in one of these fields, the same Python steps apply. Only the columns and the cost of each kind of error change.

Random Forest vs Decision Tree vs XGBoost

Choosing a model is mostly about your data size, your time and how much you must explain. So the table compares random forest with its two closest options.

QuestionDecision treeRandom forestXGBoost or LightGBM
Accuracy on table dataLowest of the threeHigh with defaultsOften highest after tuning
Tuning neededLittleLittleA lot: learning rate, depth, rounds
Overfitting riskHighLowMedium if you skip early stopping
Can you explain it?Yes, you can draw itPartly, through importance scoresPartly, through importance scores
Training speedFastFast, runs trees in parallelSlower, builds trees one by one

So random forest wins when you need a good model today with little tuning. It is not for teams chasing the last half point of accuracy on a leaderboard, where XGBoost and LightGBM usually come out ahead. It is also not for cases where a regulator wants a short formula, where logistic regression or a single small tree is easier to defend.

XGBoost, in turn, is not for small data sets or rushed projects, because it overfits when tuned carelessly. A single decision tree is not for production scoring, since it is the least stable of the three.

Read also: Hindu Months Name & Meaning in Marathi

Where a Random Forest Falls Short

Every method has weak spots, and random forests have four that catch people out.

First, a regression forest cannot predict outside the range it saw in training. In a quick test, a forest learned targets from 0 to 90. It then predicted 85 for an input of 20 and also 85 for an input of 100. So do not use one to forecast prices that keep rising past anything in your history.

Second, the model can get large. Each full-depth tree keeps every split it made, so hundreds of trees on millions of rows eat a lot of memory. As a fix, cap max_depth or raise min_samples_leaf.

Third, predictions are slower than a linear model because every row passes through every tree. That matters for an app that must answer in a few milliseconds.

Finally, a forest is hard to explain one decision at a time. Tools such as SHAP values help, but they add work.

If you want to turn skills like these into a job, our guide to the highest-paying AI careers covers the roles that use them most. Teams that label their own training data can also see how AI data annotation businesses work.

Questions About Random Forest Models

Is random forest supervised or unsupervised?

It is supervised learning. Each training row needs a known answer, such as a class or a number.

Do I need to scale features for a random forest?

No. Trees split on thresholds, so changing the units of a column does not change the splits.

Can a random forest handle missing values?

Recent scikit-learn versions can. Version 1.9.1 trains and predicts on data with NaN values without an error. Older versions need you to fill gaps first.

Can a random forest still overfit?

Yes, mostly on small or noisy data. Raise min_samples_leaf or cap max_depth, then compare the OOB score with the training score.

Is random forest a type of deep learning?

No. It is a tree ensemble with no neural network layers, so it trains well on a laptop CPU without a GPU.

Which programming languages support random forests?

Python has scikit-learn, and R has the randomForest and ranger packages. Spark MLlib also offers a version for very large data.

Joydeep Bhattacharya Avatar

Written by

Founder, Editor and Business Reporter, Bizolaunch

Free Tools for Founders

Calculators and templates built by Bizolaunch. Run the numbers in minutes.

Keep Reading