自訂 scikit-learn 模型
在這個練習中,你將使用 MLflow 的 pyfunc 風味來建立自訂模型。使用 insurance_charges 資料集時,為了在訓練期間進行分類,標籤需要把 female 改為 0、male 改為 1。在使用模型做預測時,必須回傳字串 female 或 male,而不是 0 或 1。
這個自訂模型是基於 LogisticRegression 的分類模型,並會使用名為 CustomPredict 的類別。CustomPredict 在 predict 方法中加入額外步驟,當模型接收輸入時,會把標籤 0 與 1 轉回 female 與 male。你將使用 pyfunc 風味來記錄並載入你的模型。
我們的 insurance_charges 資料集會先行完成前處理,並使用以下程式碼進行訓練:
lr_model = LogisticRegression().fit(X_train, y_train)
已經匯入 MLflow 模組。
本練習屬於課程
MLflow 入門
練習說明
- 使用 MLflow 的
pyfunc風味來記錄自訂模型。 - 將
pyfunc的python_model參數設定為使用自訂類別CustomPredict()。 - 使用
pyfunc載入這個自訂模型。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Log the pyfunc model
____.____.____(
artifact_path="lr_pyfunc",
# Set model to use CustomPredict Class
python_model=____,
artifacts={"lr_model": "lr_model"}
)
run = mlflow.last_active_run()
run_id = run.info.run_id
# Load the model in python_function format
loaded_model = ____.____.____(f"runs:/{run_id}/lr_pyfunc")