開始使用免費開始

Pickle 檔

現在是把你的第一個模型推上正式環境的時候了。你將使用一個隨機森林分類器作為基準模型,同時你還在開發更好的替代方案。你已經有資料分割成訓練與測試,變數名稱分別為 X_trainX_testy_trainy_test。此外你也可以使用模組 RandomForestClassifier()pickle,本練習會用到它們的 .load().dump() 方法。

本練習屬於課程

在 Python 設計機器學習工作流程

檢視課程

練習說明

  • 將隨機森林分類器擬合到資料上。把隨機種子固定為 42,確保結果可重現。
  • 使用 pickle 將模型寫入檔案。請用 with open(____) as ____ 語法開啟目的檔案。
  • 接著把檔案中的模型載入到另一個變數名稱 clf_from_file
  • 將你載入的模型所做的預測存入變數 preds

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Fit a random forest to the training set
clf = ____(____=42).____(
  X_train, y_train)

# Save it to a file, to be pushed to production
with ____('model.pkl', ____) as ____:
    pickle.____(clf, file=file)

# Now load the model from file in the production environment
with ____ as file:
    clf_from_file = pickle.____(file)

# Predict the labels of the test dataset
preds = clf_from_file.____
編輯並執行程式碼