Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Random Forest

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.。

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):

Feature randomness:

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

print

(

"Test set accuracy:"

,

accuracy_score

(

y_test

,

y_pred

)

)

print

(

"\nClassification report:"

)

print

(

classification_report

(

y_test

,

y_pred

,

target_names

=

iris.

target_names

)

)

Code analysis:

  1. Import libraries: RandomForestClassifier is the random forest classifier.
  2. Load data: the iris dataset has 150 samples, 4 features, and 3 classes.
  3. Data Splitting: use 70% of the data for training and 30% for testing, to verify the model's ability to generalize to new data.
  4. Instantiate the model: random_state=42 Ensure the results are reproducible across runs.
  5. Train the model: fit method will build 100 decision trees.
  6. 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

print

(

"Test set accuracy:"

,

accuracy_score

(

y_test

,

y_pred

)

)

print

(

"\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

)

print

(

"Feature importance ranking:"

)

print

(

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

  1. High accuracy: ensemble learning usually achieves top-level performance on the given data.
  2. Strong resistance to overfitting: thanks to Bagging and random feature selection, it is not prone to overfitting even without pruning.
  3. Friendly to data requirements: it can handle both numerical and categorical features and does not require feature scaling (such as normalization).
  4. Provides feature importance: the built-in feature evaluation is a valuable by-product.
  5. Easy to parallelize: each tree is trained independently, so it can be easily accelerated through parallelism.

Disadvantages

  1. Poor model interpretability: a "black box" made up of hundreds or thousands of trees is much harder to interpret than a single decision tree.
  2. Slower training and prediction: with a large number of trees, more computational resources and time are required.
  3. Large memory footprint: all tree structures of the entire forest need to be stored.

Typical use cases