你的第一個 pipeline——再來一次!
回到心律不整的新創公司,你的月度檢視即將到來,其中一項是由資深的 Python 程式設計師審查你的程式碼。你決定依照最佳實務來整理:把原本做特徵選擇與隨機森林分類的腳本,改寫成一個 pipeline。你使用的訓練資料集為 X_train 與 y_train,以及多個模組:用於特徵選擇的 RandomForestClassifier、SelectKBest() 與 f_classif(),還有 GridSearchCV 與 Pipeline。
本練習屬於課程
在 Python 設計機器學習工作流程
練習說明
- 使用範例程式碼提供的特徵選擇器,搭配隨機森林分類器,建立一個 pipeline。將第一個步驟命名為
feature_selection。 - 在
params中加入 2 組鍵值:選擇器中的特徵數k(取值 10 與 20),以及森林中的n_estimators(可能值 2 與 5)。 - 以給定的 pipeline 與參數網格初始化一個
GridSearchCV物件。 - 將物件擬合到資料並列印表現最佳的參數組合。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create pipeline with feature selector and classifier
pipe = ___([
(___, SelectKBest(f_classif)),
('clf', ___(random_state=2))])
# Create a parameter grid
params = {
'feature_selection__k':___,
___:[2, 5]}
# Initialize the grid search object
grid_search = ___(___, ___=params)
# Fit it to the data and print the best value combination
print(grid_search.fit(___, ___).___)