機器學習 - 隨機森林



隨機森林是一種機器學習演算法,它使用決策樹的集合來進行預測。該演算法由 Leo Breiman 於 2001 年首次提出。該演算法背後的關鍵思想是建立大量的決策樹,每個決策樹都訓練於不同的資料子集。然後將這些單個樹的預測結果組合起來,以產生最終預測。

隨機森林演算法的工作原理

我們可以透過以下步驟來理解隨機森林演算法的工作原理:

  • 步驟 1 - 首先,從給定的資料集中選擇隨機樣本。

  • 步驟 2 - 接下來,該演算法將為每個樣本構建一棵決策樹。然後它將從每棵決策樹中獲取預測結果。

  • 步驟 3 - 在此步驟中,將對每個預測結果進行投票。

  • 步驟 4 - 最後,選擇得票最多的預測結果作為最終預測結果。

下圖說明了隨機森林演算法的工作原理:

Random Forest Algorithm

隨機森林是一種靈活的演算法,可用於分類和迴歸任務。在分類任務中,該演算法使用各個樹預測結果的眾數來進行最終預測。在迴歸任務中,該演算法使用各個樹預測結果的平均值。

隨機森林演算法的優點

隨機森林演算法比其他機器學習演算法具有幾個優點。一些關鍵優勢包括:

  • 對過擬合的魯棒性 - 隨機森林演算法以其對過擬合的魯棒性而聞名。這是因為該演算法使用決策樹的集合,這有助於減少資料中異常值和噪聲的影響。

  • 高精度 - 隨機森林演算法以其高精度而聞名。這是因為該演算法結合了多個決策樹的預測結果,這有助於減少可能存在偏差或不準確的單個決策樹的影響。

  • 處理缺失資料 - 隨機森林演算法可以處理缺失資料,無需進行插補。這是因為該演算法只考慮每個資料點可用的特徵,並且不需要所有資料點的所有特徵都存在。

  • 非線性關係 - 隨機森林演算法可以處理特徵和目標變數之間的非線性關係。這是因為該演算法使用決策樹,可以模擬非線性關係。

  • 特徵重要性 - 隨機森林演算法可以提供有關模型中每個特徵重要性的資訊。此資訊可用於識別資料中最重要的特徵,並可用於特徵選擇和特徵工程。

在 Python 中實現隨機森林演算法

讓我們來看一下在 Python 中實現隨機森林演算法的方法。我們將使用 scikit-learn 庫來實現該演算法。scikit-learn 庫是一個流行的機器學習庫,它提供了廣泛的機器學習演算法和工具。

步驟 1 - 匯入庫

我們將從匯入必要的庫開始。我們將使用 pandas 庫進行資料操作,並使用 scikit-learn 庫來實現隨機森林演算法。

import pandas as pd
from sklearn.ensemble import RandomForestClassifier

步驟 2 - 載入資料

接下來,我們將資料載入到 pandas 資料框中。在本教程中,我們將使用著名的 Iris 資料集,這是一個用於分類任務的經典資料集。

# Loading the iris dataset

iris = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learningdatabases/iris/iris.data', header=None)

iris.columns = ['sepal_length', 'sepal_width', 'petal_length','petal_width', 'species']

步驟 3 - 資料預處理

在我們使用資料訓練模型之前,我們需要對其進行預處理。這包括分離特徵和目標變數,並將資料分成訓練集和測試集。

# Separating the features and target variable
X = iris.iloc[:, :-1]
y = iris.iloc[:, -1]

# Splitting the data into training and testing sets
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.35, random_state=42)

步驟 4 - 訓練模型

接下來,我們將使用訓練資料訓練我們的隨機森林分類器。

# Creating the Random Forest classifier object
rfc = RandomForestClassifier(n_estimators=100)

# Training the model on the training data
rfc.fit(X_train, y_train)

步驟 5 - 進行預測

訓練完模型後,我們可以使用它對測試資料進行預測。

# Making predictions on the test data
y_pred = rfc.predict(X_test)

步驟 6 - 評估模型

最後,我們將使用各種指標(如準確率、精確率、召回率和 F1 分數)來評估模型的效能。

# Importing the metrics library
from sklearn.metrics import accuracy_score, precision_score,
recall_score, f1_score

# Calculating the accuracy, precision, recall, and F1-score
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average='weighted')
recall = recall_score(y_test, y_pred, average='weighted')
f1 = f1_score(y_test, y_pred, average='weighted')

print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1-score:", f1)

完整的實現示例

以下是使用 iris 資料集在 python 中實現隨機森林演算法的完整實現示例:

import pandas as pd
from sklearn.ensemble import RandomForestClassifier

# Loading the iris dataset
iris = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learningdatabases/iris/iris.data', header=None)

iris.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']

# Separating the features and target variable
X = iris.iloc[:, :-1]
y = iris.iloc[:, -1]

# Splitting the data into training and testing sets
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.35, random_state=42)

# Creating the Random Forest classifier object
rfc = RandomForestClassifier(n_estimators=100)

# Training the model on the training data
rfc.fit(X_train, y_train)
# Making predictions on the test data
y_pred = rfc.predict(X_test)
# Importing the metrics library
from sklearn.metrics import accuracy_score, precision_score,
recall_score, f1_score

# Calculating the accuracy, precision, recall, and F1-score
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average='weighted')
recall = recall_score(y_test, y_pred, average='weighted')
f1 = f1_score(y_test, y_pred, average='weighted')

print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1-score:", f1)

輸出

這將給出我們隨機森林分類器的效能指標,如下所示:

Accuracy: 0.9811320754716981
Precision: 0.9821802935010483
Recall: 0.9811320754716981
F1-score: 0.9811157396063056
廣告