Random Forest
Imagine you are taking part in an important knowledge contest. Faced with a difficult question, do you trust the judgment of a top expert more, or the result voted on by 100 fairly capable contestants? In most cases, collective wisdom tends to compensate for individual bias and limitations, leading to more stable and more accurate decisions.
In the world of machine learning,Random Forest is precisely an outstanding representative of thiscollective wisdomidea. By building a large number of decision trees and letting them vote together to make predictions, it has become one of the most powerful and most popular machine learning algorithms.
What is a random forest?
Random Forest is a machine learning algorithm based on ensemble learning. Its core idea is very simple:Two heads are better than one.。
- Forest: refers to a collection formed by many Decision Tree (Decision Tree) decision trees.
- random: refers to the fact that, when building each decision tree, the algorithm introduces two types of randomness, ensuring each tree is unique.
Finally, for classification tasks, the forest gives its result by voting (majority rule) ; for regression tasks, it gives its result by taking the average to give the result.
Core idea: Bagging and randomness
The success of random forests rests on two cornerstones:
Bagging(Bootstrap Aggregating):
- Bootstrap (bootstrap sampling): from the original training dataset,with replacementrandomly draw samples to generate multiple different sub-training sets. This means the same sample may appear multiple times in one subset, while another sample may not appear at all.
- Aggregating (aggregation): train a decision tree independently with each sub-training set, and finally aggregate the results of all trees (by voting or averaging).

Feature randomness:
- When splitting at each node of each tree, the algorithm does not consider all features; instead, itrandomly selects a subset from all the features, and then chooses the best splitting feature from that subset.
- This further increases the diversity among trees, allowing the forest to see different aspects of the problem.
In short, random forests create a diversecommittee of experts**. **Even if some of the trees make mistakes, the other correct trees can correct them through voting, resulting in more stable and more powerful performance than a single decision tree.
Algorithm flow and key parameters
The working steps of a random forest
Let us use a flowchart to clearly see how it works:

Key hyperparameters explained in detail
When using scikit-learn when using the library, it is crucial to understand the following core parameters:
| Parameter name | Meaning | Typical value / impact | Plain explanation |
|---|---|---|---|
n_estimators |
The number of decision trees in the forest. | Defaults to 100. The larger the value, the more stable the model and the better its performance, but the higher the computational cost. | "the number of people on the committee". The more people, the more reliable the decision usually is, but the longer the meeting takes. |
max_depth |
The maximum depth of a single decision tree. | Default None(unlimited). Limiting the depth prevents overfitting and makes the model simpler. |
"limit each person's speaking time". This prevents a particular expert (tree) from getting stuck in a rut and paying too much attention to the details of the training data. |
max_features |
The number of features considered when searching for the best split. | Can be an integer, a float, or 'auto'/'sqrt'None. This is the key parameter for introducing "feature randomness". |
"randomly look at only a few aspects in each discussion". This ensures each tree analyzes the problem from a different angle, increasing diversity. |
min_samples_split |
The minimum number of samples required to split a node. | Defaults to 2. The larger the value, the more conservative the tree growth and the less likely it is to overfit. | "how many people a group must have at least to continue the discussion". This avoids creating a new rule based on just one or two samples. |
min_samples_leaf |
The minimum number of samples required at a leaf node. | Defaults to 1. The larger the value, the smoother the model. | "at least how many cases the final conclusion must be based on". This ensures every conclusion is backed by a certain amount of data. |
bootstrap |
Whether to use bootstrap sampling. | Default True. If set to FalseFalse, each tree will be trained using the entire dataset, but some of the randomness will be lost. |
"whether a person is allowed to speak more than once". Turning it on is the essence of Bagging. |
Hands-on practice - code examples
Let us practice with a classic iris (Iris) classification dataset.
Example 1: Basic classification task
Example
Import the necessary libraries
from
sklearn.
datasets
import
load_iris
from
sklearn.
model_selection
import
train_test_split
from
sklearn.
ensemble
import
RandomForestClassifier
from
sklearn.
metrics
import
accuracy_score
,
classification_report
1. Load the data
iris
=
load_iris
(
)
X
=
iris.
data
Features: sepal length, sepal width, petal length, petal width
y
=
iris.
target
Labels: three species of iris
2. Split into training and test sets
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.3
,
random_state
=
42
)
3. Create a random forest classifier
Here we set 100 trees and limit the maximum depth to 5
rf_clf
=
RandomForestClassifier
(
n_estimators
=
100
,
max_depth
=
5
,
random_state
=
42
)
4. Train the model
rf_clf.
fit
(
X_train
,
y_train
)
5. Make predictions on the test set
y_pred
=
rf_clf.
predict
(
X_test
)
6. Evaluate model performance
(
"Test set accuracy:"
,
accuracy_score
(
y_test
,
y_pred
)
)
(
"\nClassification report:"
)
(
classification_report
(
y_test
,
y_pred
,
target_names
=
iris.
target_names
)
)
Code analysis:
- Import libraries:
RandomForestClassifieris the random forest classifier. - Load data: the iris dataset has 150 samples, 4 features, and 3 classes.
- Data Splitting: use 70% of the data for training and 30% for testing, to verify the model's ability to generalize to new data.
- Instantiate the model:
random_state=42Ensure the results are reproducible across runs. - Train the model:
fitmethod will build 100 decision trees. - Prediction and evaluation: use the trained forest to predict on the test set and compute metrics such as accuracy.
Output:
setosa 1.00 1.00 1.00 19
versicolor 1.00 1.00 1.00 13
virginica 1.00 1.00 1.00 13
accuracy 1.00 45
macro avg 1.00 1.00 1.00 45
weighted avg 1.00 1.00 1.00 45
Example 2: View feature importance
Random forests also have a powerful feature: evaluating how much each feature contributes to the prediction.
Example
Import the necessary libraries
from
sklearn.
datasets
import
load_iris
from
sklearn.
model_selection
import
train_test_split
from
sklearn.
ensemble
import
RandomForestClassifier
from
sklearn.
metrics
import
accuracy_score
,
classification_report
import
pandas
as
pd
import
matplotlib.
pyplot
as
plt
-------------------------- Set Chinese font start --------------------------
plt.
rcParams
[
'font.sans-serif'
]
=
[
Windows first
'SimHei'
,
'Microsoft YaHei'
,
macOS first
'PingFang SC'
,
'Heiti TC'
,
Linux first
'WenQuanYi Micro Hei'
,
'DejaVu Sans'
]
Fix the issue of minus signs displaying as squares
plt.
rcParams
[
'axes.unicode_minus'
]
=
False
-------------------------- Set Chinese font end --------------------------
1. Load the data
iris
=
load_iris
(
)
X
=
iris.
data
Features: sepal length, sepal width, petal length, petal width
y
=
iris.
target
Labels: three species of iris
2. Split into training and test sets
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.3
,
random_state
=
42
)
3. Create a random forest classifier
Here we set 100 trees and limit the maximum depth to 5
rf_clf
=
RandomForestClassifier
(
n_estimators
=
100
,
max_depth
=
5
,
random_state
=
42
)
4. Train the model
rf_clf.
fit
(
X_train
,
y_train
)
5. Make predictions on the test set
y_pred
=
rf_clf.
predict
(
X_test
)
6. Evaluate model performance
(
"Test set accuracy:"
,
accuracy_score
(
y_test
,
y_pred
)
)
(
"\nClassification report:"
)
Get feature importance
feature_importances
=
rf_clf.
feature_importances_
features
=
iris.
feature_names
Create a DataFrame for easy viewing
importance_df
=
pd.
DataFrame
(
{
'feature'
: features
,
'importance'
: feature_importances
}
)
.
sort_values
(
'importance'
,
ascending
=
False
)
(
"Feature importance ranking:"
)
(
importance_df
)
Visualization
plt.
figure
(
figsize
=
(
8
,
5
)
)
plt.
barh
(
importance_df
[
'feature'
]
,
importance_df
[
'importance'
]
)
plt.
xlabel
(
'feature_importance'
)
plt.
title
(
'Random Forest - Feature Importance'
)
plt.
gca
(
)
.
invert_yaxis
(
)
Show the most important features at the top
plt.
show
(
)

Output analysis: you may find that petal length and petal width are far more important than sepal dimensions. This is consistent with botanical common sense, as petal features are indeed the key to distinguishing different iris species.This feature is extremely valuable for feature selection and data understanding.
Part Four: Advantages, disadvantages, and application scenarios
Advantages
- High accuracy: ensemble learning usually achieves top-level performance on the given data.
- Strong resistance to overfitting: thanks to Bagging and random feature selection, it is not prone to overfitting even without pruning.
- Friendly to data requirements: it can handle both numerical and categorical features and does not require feature scaling (such as normalization).
- Provides feature importance: the built-in feature evaluation is a valuable by-product.
- Easy to parallelize: each tree is trained independently, so it can be easily accelerated through parallelism.
Disadvantages
- Poor model interpretability: a "black box" made up of hundreds or thousands of trees is much harder to interpret than a single decision tree.
- Slower training and prediction: with a large number of trees, more computational resources and time are required.
- Large memory footprint: all tree structures of the entire forest need to be stored.
Typical use cases
- Classification problems: such as spam detection, disease diagnosis, and image classification.
- Regression problems: such as house price prediction and sales forecasting.
- Feature selection: use the feature importance it outputs for feature selection.
- Handling Missing Values: random forests have a natural ability to handle missing values reasonably well.