自訂模型

MLflow 入門

Weston Bassler

Senior MLOps Engineer

範例情境

  • NLP-Tokenizer(分詞器)

  • 分類-標籤編碼器

  • 前處理/後處理

  • 非內建風味

不同

1 unsplash.com
MLflow 入門

自訂 Python 模型

  • 內建風味-python_function

  • mlflow.pyfunc

    • save_model()
    • log_model()
    • load_model()
MLflow 入門

自訂模型類別

  • 自訂模型類別

    • MyClass(mlflow.pyfunc.PythonModel)
  • PythonModel 類別

    • load_context()-在呼叫 mlflow.pyfunc.load_model() 時載入 artifacts
    • predict()-接收模型輸入並執行使用者自訂的推論
MLflow 入門

Python 類別

# 類別
class MyPythonClass:

# 會印出 Hello! 的函式 def my_func(): print("Hello!")
# 建立新物件
x = MyPythonClass()

# 執行 my_func 函式 x.my_func()
"Hello!"
MLflow 入門

自訂類別範例

import mlflow.pyfunc

# 定義模型類別
class CustomPredict(mlflow.pyfunc.PythonModel):

# 載入 artifacts def load_context(self, context): self.model = mlflow.sklearn.load_model(context.artifacts["custom_model"])
# 使用 custom_function() 評估輸入 def predict(self, context, model_input): prediction = self.model.predict(model_input) return custom_function(prediction)
MLflow 入門

儲存與記錄自訂模型

# 儲存模型到本機檔案系統
mlflow.pyfunc.save_model(path="custom_model", python_model=CustomPredict())
# 將模型記錄到 MLflow Tracking
mlflow.pyfunc.log_model(artifact_path="custom_model", python_model=CustomPredict())
MLflow 入門

載入自訂模型

# 從本機檔案系統載入模型
mlflow.pyfunc.load_model("local")
# 從 MLflow Tracking 載入模型
mlflow.pyfunc.load_model("runs:/run_id/tracking_path")
MLflow 入門

模型評估

  • mlflow.evaluate()-以資料集衡量效能

  • 支援回歸與分類模型

MLflow 入門

評估範例

# 訓練資料
X_train, X_test, y_train, y_test = \
    train_test_split(X, y,
    train_size=0.7,random_state=0)

# 線性回歸模型 lr = LinearRegression() lr.fit(X_train, y_train)
# 資料集
eval_data = X_test
eval_data["test_label"] = y_test

# 以資料集評估模型 mlflow.evaluate( "runs:/run_id/model", eval_data, targets="test_label", model_type="regressor" )
MLflow 入門

Tracking 介面

eval

shap

1 shap.readthedocs.io
MLflow 入門

一起來練習吧!

MLflow 入門

Preparing Video For Download...