整合所有重點
你在心律不整偵測新創的 pipeline 有兩個顧慮:
- 這個 App 的模型是用各年齡層的病患資料訓練的,但實際上主要由偏年輕的健身族群使用。你懷疑這可能是領域偏移(domain shift),因此想忽略所有年齡在 50 歲以上的樣本。
- 你仍擔心過度擬合,所以想看看把隨機森林分類器的複雜度降低,並且選取部分特徵,是否能有所幫助。
你將建立一個包含特徵選擇步驟 SelectKBest() 以及 RandomForestClassifier 的 pipeline,兩者都已經匯入。你也可以使用 GridSearchCV()、Pipeline、numpy(別名為 np)以及 pickle。資料存於 arrh。
本練習屬於課程
在 Python 設計機器學習工作流程
練習說明
- 建立一個 pipeline,將
SelectKBest()命名為步驟ft,RandomForestClassifier()命名為步驟clf。 - 建立參數網格,調整
SelectKBest()的k與RandomForestClassifier()的max_depth。 - 使用
GridSearchCV(),只用年齡小於 50 的資料,對該參數網格進行最佳化。 - 將最佳化後的 pipeline 存成 pickle,以供上線使用。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a pipeline
pipe = Pipeline([
('ft', ____), ('clf', ____(random_state=2))])
# Create a parameter grid
grid = {'ft__k':[5, 10], '____':[10, 20]}
# Execute grid search CV on a dataset containing under 50s
grid_search = ____(pipe, param_grid=grid)
arrh = arrh.____[____(arrh['age'] < 50)]
____.____(arrh.drop('class', 1), arrh['class'])
# Push the fitted pipeline to production
with ____('pipe.pkl', ____) as file:
pickle.dump(____, file)