如何使用 Python 進行整合學習?


整合學習是一種機器學習技術,它結合多個模型的預測結果來提高模型的整體效能。整合學習的思想是獨立地訓練多個模型,然後結合它們的預測結果來做出最終預測。這種方法可以比使用單個模型獲得更好的效能,因為它可以減少過擬合併提高模型的泛化能力。

整合學習廣泛應用於機器學習領域,並在許多應用中取得了成功,包括影像分類、語音識別和自然語言處理。它是一個強大的工具,可以提高機器學習模型的效能,在解決機器學習問題時值得考慮。

在本教程中,我們將討論四種整合學習方法,即**Bagging、Boosting、Stacking**和**Voting**,以及它們在 Python 程式語言中的實現。

Bagging

Bagging 是一種整合學習方法,其中多個模型在資料的不同子集上進行訓練,最終預測結果是透過對所有模型的預測結果進行平均獲得的。一種流行的 Bagging 演算法是**隨機森林**,它在資料的每個子集上訓練一棵決策樹。

在 Python 中,可以使用 `sklearn.ensemble` 模組中的 `RandomForestClassifier` 或 `RandomForestRegressor` 類來訓練隨機森林模型。

Python 實現

下面是一個使用 Bagging 整合方法和隨機森林演算法在 Iris 資料集上進行操作的示例,該資料集包含關於三種鳶尾花物種的資訊。

首先,讓我們載入必要的庫和資料集:

import pandas as pd
from sklearn.model_selection import train_test_split

# Load the dataset
df = pd.read_csv(r'C:\Users\Leekha\Desktop\ML Datasets\iris.csv')

# Split the data into features and target
X = df.drop('Species', axis=1)
y = df['Species']

# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

接下來,讓我們建立基礎模型。我們將使用 `sklearn.ensemble` 模組中的 `RandomForestClassifier` 類來建立基礎模型:

from sklearn.ensemble import RandomForestClassifier
# Create the base model
base_model = RandomForestClassifier(random_state=42)

現在,讓我們使用 `sklearn.ensemble` 模組中的 `BaggingClassifier` 類建立 Bagging 整合:

from sklearn.ensemble import BaggingClassifier

# Create the bagging ensemble
ensemble = BaggingClassifier(base_estimator=base_model, n_estimators=10)

最後,讓我們在訓練資料上訓練整合模型,並在測試資料上進行預測:

# Train the ensemble on the training data
ensemble.fit(X_train, y_train)

# Make predictions on the test data
y_pred = ensemble.predict(X_test)

為了評估整合的效能,我們可以使用 `sklearn.metrics` 模組中的 `classification_report` 函式,該函式將列印每個類別的精度、召回率和 F1 分數:

from sklearn.metrics import classification_report

# Print the classification report
print(classification_report(y_test, y_pred))

這將列印 Bagging 整合在測試資料上的以下評估指標。

              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        11
  versicolor       0.92      1.00      0.96        10
   virginica       1.00      0.91      0.95        11

    accuracy                           0.97        32
   macro avg       0.97      0.97      0.97        32
weighted avg       0.97      0.97      0.97        32

Boosting

Boosting 是一種整合學習方法,其中多個模型按順序進行訓練,每個模型都試圖糾正前一個模型的錯誤。一種流行的 Boosting 演算法是梯度提升,它在資料上訓練一系列決策樹。在 Python 中,可以使用 `sklearn.ensemble` 模組中的 `GradientBoostingClassifier` 或 `GradientBoostingRegressor` 類來訓練梯度提升模型。

Python 實現

下面是一個使用 Boosting 整合方法和 AdaBoost 演算法在 Iris 資料集上進行操作的示例:

首先,讓我們載入必要的庫和資料集:

import pandas as pd
from sklearn.model_selection import train_test_split

# Load the dataset
df = pd.read_csv(r'C:\Users\Leekha\Desktop\ML Datasets\iris.csv')

# Split the data into features and target
X = df.drop('species', axis=1)
y = df['species']

# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

接下來,讓我們建立基礎模型。我們將使用 `sklearn.tree` 模組中的 `DecisionTreeClassifier` 類來建立基礎模型:

from sklearn.tree import DecisionTreeClassifier

# Create the base model
base_model = DecisionTreeClassifier(random_state=42)

現在,讓我們使用 `sklearn.ensemble` 模組中的 `AdaBoostClassifier` 類建立 Boosting 整合:

from sklearn.ensemble import AdaBoostClassifier

# Create the boosting ensemble
ensemble = AdaBoostClassifier(base_estimator=base_model, n_estimators=10)

最後,讓我們在訓練資料上訓練整合模型,並在測試資料上進行預測:

# Train the ensemble on the training data
ensemble.fit(X_train, y_train)

# Make predictions on the test data
y_pred = ensemble.predict(X_test)

為了評估整合的效能,我們可以使用 `sklearn.metrics` 模組中的 `classification_report` 函式,該函式將列印每個類別的精度、召回率和 F1 分數:

from sklearn.metrics import classification_report

# Print the classification report
print(classification_report(y_test, y_pred))

這將列印 Boosting 整合在測試資料上的評估指標:

 precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        11
  versicolor       0.92      1.00      0.96        10
   virginica       1.00      0.91      0.95        11

    accuracy                           0.97        32
   macro avg       0.97      0.97      0.97        32
weighted avg       0.97      0.97      0.97        32

Stacking

Stacking 是一種整合學習方法,其中多個模型在相同的資料上進行訓練,這些模型的預測結果被用作輸入來訓練一個更高層次的模型。在 Python 中,可以使用 `mlxtend.classifier` 模組中的 `StackingClassifier` 或 `StackingRegressor` 類來訓練 Stacking 模型。

Python 實現

下面是一個使用 Stacking 整合方法和決策樹作為更高層次的模型在 Iris 資料集上進行操作的示例,其中包含輸出結果。我們將使用邏輯迴歸和支援向量機作為基礎模型。

首先,讓我們載入必要的庫和資料集:

import pandas as pd
from sklearn.model_selection import train_test_split

# Load the dataset
df = pd.read_csv('iris.csv')

# Split the data into features and target
X = df.drop('species', axis=1)
y = df['species']

# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

接下來,讓我們建立基礎模型和更高層次的模型。我們將分別使用 `sklearn.linear_model` 和 `sklearn.svm` 模組中的 `LogisticRegression` 和 `SVC` 類來建立基礎模型,並使用 `sklearn.ensemble` 模組中的 `RandomForestClassifier` 類來建立更高層次的模型:

from mlxtend.classifier import StackingClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC

# Create the base models
logistic_regression = LogisticRegression(random_state=42)
svm = SVC(random_state=42)

# Create the higher-level model
dt = RandomForestClassifier(random_state=42)

現在,讓我們使用 `mlxtend.classifier` 模組中的 `StackingClassifier` 類建立 Stacking 整合:

# Create the stacking ensemble
ensemble = StackingClassifier(
   classifiers=[logistic_regression, svm], 
   meta_classifier=dt, use_probas=True, average_probas=False
)

最後,讓我們在訓練資料上訓練整合模型,並在測試資料上進行預測:

# Train the ensemble on the training data
ensemble.fit(X_train, y_train)

# Make predictions on the test data
y_pred = ensemble.predict(X_test)

為了評估整合的效能,我們可以使用 `sklearn.metrics` 模組中的 `classification_report` 函式,該函式將列印每個類別的精度、召回率和 F1 分數:

from sklearn.metrics import classification_report

# Print the classification report
print(classification_report(y_test, y_pred))

這將列印 Stacking 整合在測試資料上的評估指標:

precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        11
  versicolor       0.90      0.90      0.90        10
   virginica       0.91      0.91      0.91        11

    accuracy                           0.93        32
   macro avg       0.93      0.93

Voting

Voting 是一種整合學習方法,其中多個模型在相同的資料上進行訓練,最終預測結果是透過多數投票獲得的。在 Python 中,可以使用 `sklearn.ensemble` 模組中的 `VotingClassifier` 類來訓練 Voting 整合模型。

Python 實現

下面是一個使用 Voting 整合方法和邏輯迴歸、支援向量機和決策樹作為基礎模型在 Iris 資料集上進行操作的示例。

首先,讓我們載入必要的庫和資料集:

import pandas as pd
from sklearn.model_selection import train_test_split

# Load the dataset
df = pd.read_csv('iris.csv')

# Split the data into features and target
X = df.drop('species', axis=1)
y = df['species']

# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

接下來,讓我們建立基礎模型。我們將分別使用 `sklearn.linear_model`、`sklearn.svm` 和 `sklearn.tree` 模組中的 `LogisticRegression`、`SVC` 和 `DecisionTreeClassifier` 類來建立基礎模型:

from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier

# Create the base models
logistic_regression = LogisticRegression(random_state=42)
svm = SVC(random_state=42)
dt = DecisionTreeClassifier(random_state=42)

現在,讓我們使用 `sklearn.ensemble` 模組中的 `VotingClassifier` 類建立 Voting 整合:

from sklearn.ensemble import VotingClassifier

# Create the voting ensemble
ensemble = VotingClassifier(estimators=[('lr', logistic_regression), 
   ('svm', svm), 
   ('dt', dt)], voting='hard')

最後,讓我們在訓練資料上訓練整合模型,並在測試資料上進行預測:

# Train the ensemble on the training data
ensemble.fit(X_train, y_train)

# Make predictions on the test data
y_pred = ensemble.predict(X_test)

為了評估整合的效能,我們可以使用 `sklearn.metrics` 模組中的 `classification_report` 函式,該函式將列印每個類別的精度、召回率和 F1 分數:

from sklearn.metrics import classification_report

# Print the classification report
print(classification_report(y_test, y_pred))

這將列印 Voting 整合在測試資料上的評估指標:

precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        11
  versicolor       0.92      1.00      0.96        10
   virginica       1.00      0.91      0.95        11

    accuracy                           0.97        32
   macro avg       0.97      0.97      0.97        32
weighted avg       0.97      0.97      0.97        32

結論

在本教程中,我們解釋瞭如何使用 Python 進行整合學習,並提供了在 Iris 資料集上使用 Bagging、Boosting 和 Stacking 等各種方法的示例。

我們演示了整合學習如何比使用單個模型獲得更好的效能,並且可以作為提高機器學習模型效能的有用技術。

更新於:2024年2月20日

144 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告