如何使用 Python 進行網格搜尋?
最佳化機器學習模型中的超引數需要使用網格搜尋。超引數(如正則化強度或學習率)會極大地影響模型的效能。透過網格搜尋,可以系統地探索預設的一組超引數,以找到產生最佳結果的配置。網格搜尋提供了一個易於使用的介面來構建超引數網格並透過交叉驗證評估模型效能,這兩者都可以使用 Python 的 Scikit-learn 模組來完成。網格搜尋自動化了尋找理想超引數的過程,使機器學習從業者能夠專注於特徵工程和模型選擇等關鍵任務。在本文中,我們將詳細介紹如何使用 Python 執行網格搜尋。
使用 Python 執行網格搜尋 CV
在這個專案中,我們打算使用網格搜尋來展示 Python 的 Scikit-learn 包的潛力。首先,我們使用 Scikit-learn 建立了一個用於分類的示例資料集。在將資料集劃分為訓練集和測試集之後,我們再次使用 Scikit-learn 建立了一個 SVM 模型。
然後,對 SVM 模型進行網格搜尋測試,這相當於嘗試各種超引數組合以找到效能最佳的組合。Scikit-learn 在這方面表現出色,因為它使該過程變得非常簡單。最後,我們使用 Scikit-learn 的分類報告評估了模型的效能,該報告為我們提供了各種重要指標,包括資料集每個類別的準確率、召回率和 F1 分數。
匯入庫和建立資料集
我們將使用 Scikit-learn(一個包含大量有用機器學習功能的出色庫)來構建我們自己的資料集。資料集是使用以下程式碼建立的:
from sklearn.datasets import make_classification X, y = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1, random_state=42)
資料集的建立使用了相當簡單的程式設計。只需要指定幾個引數,包括樣本大小(在本例中為 1000)、相關特徵的數量(我們將設定為 2)以及每個類別的叢集數量(我們將設定為 1 以避免叢集重疊)。
分割資料集
資料集準備就緒後,我們需要將其分成訓練集和測試集。80% 的資料將用於訓練我們的模型,其餘 20% 將用於測試。
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
建立模型
接下來,我們將使用支援向量機 (SVM) 方法構建我們的模型。SVM 是一個廣受歡迎的分類任務選擇,因為它可以有效地處理線性資料和非線性資料。
from sklearn.svm import SVC model = SVC()
執行網格搜尋
在這種情況下,是時候開始網格搜尋了。我們將使用 Scikit-learn 的 Grid Search CV 函式測試各種超引數組合,以找到效能最佳的組合。
from sklearn.model_selection import GridSearchCV
param_grid = {'C': [0.1, 1, 10, 100],
'gamma': [0.1, 1, 10, 100],
'kernel': ['linear', 'rbf']}
grid = GridSearchCV(model, param_grid, refit=True, verbose=3)
grid.fit(X_train, y_train)
在程式碼中,我們使用字典建立了一個超引數網格,然後將其與模型、設定為 True 的 refit 引數和設定為 3 的 verbose 引數一起提供給 GridSearchCV 函式。
評估模型
網格搜尋完成後,是時候評估我們的模型工作效果了。我們將為此使用 Scikit-learn 的 classification_report 函式。此函式使用網格搜尋找到的最佳超引數,生成模型在測試集上的效能報告。
from sklearn.metrics import classification_report
y_pred = grid.predict(X_test)
print("Best Hyperparameters:", grid.best_params_)
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
輸出
Best Hyperparameters: {'C': 10, 'gamma': 1, 'kernel': 'rbf'}
Classification Report:
precision recall f1-score support
0 0.92 0.97 0.94 104
1 0.97 0.91 0.94 96
accuracy 0.94 200
macro avg 0.94 0.94 0.94 200
weighted avg 0.94 0.94 0.94 200
在程式碼中,我們基於最佳超引數使用 Grid Search CV 物件的預測方法為測試集建立預測。然後列印分類報告和最重要的超引數。
隨機搜尋 CV 方法
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
param_dist = {'C': randint(1, 100),
'gamma': randint(1, 100),
'kernel': ['linear', 'rbf']}
random_search = RandomizedSearchCV(model, param_distributions=param_dist, n_iter=10, random_state=42)
random_search.fit(X_train, y_train)
y_pred_random = random_search.predict(X_test)
print("Best Hyperparameters (Grid Search):", grid.best_params_)
print("\nClassification Report (Grid Search):")
print(classification_report(y_test, y_pred))
print("\nBest Hyperparameters (Randomized Search):", random_search.best_params_)
print("\nClassification Report (Randomized Search):")
print(classification_report(y_test, y_pred_random))
輸出
Best Hyper parameters (Grid Search): {'C': 10, 'gamma': 1, 'kernel': 'rbf'}
Classification Report (Grid Search):
precision recall f1-score support
0 0.92 0.97 0.94 104
1 0.97 0.91 0.94 96
accuracy 0.94 200
macro avg 0.94 0.94 0.94 200
weighted avg 0.94 0.94 0.94 200
Best Hyperparameters (Randomized Search): {'C': 24, 'gamma': 3, 'kernel': 'rbf'}
Classification Report (Randomized Search):
precision recall f1-score support
0 0.93 0.96 0.94 104
1 0.96 0.92 0.94 96
accuracy 0.94 200
macro avg 0.94 0.94 0.94 200
weighted avg 0.94 0.94 0.94 200
結論
網格搜尋是最佳化機器學習模型超引數的終極方法。在本博文中,我們使用 Scikit-learn 和 Python 演示瞭如何執行網格搜尋。除此之外,我們還處理了一個真實的專案,其中我們建立了自己的資料集,對資料進行了廣泛分析,並展示了我們的結論。
由於 Python 的 Scikit-learn 模組的網格搜尋功能,資料科學家和機器學習愛好者可以輕鬆地提高其模型的效能。結合本文的建議,在您自己的資料集上進行網格搜尋可以幫助您的模型獲得更好的效能。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP