カスタムモデル

MLflow 入門

Weston Bassler

Senior MLOps Engineer

ユースケース例

  • NLP - トークナイザー

  • 分類 - ラベルエンコーダー

  • 前処理/後処理

  • ビルトインフレーバーではない

異なる

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() 呼び出し時にアーティファクトを読み込む
    • 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):

# アーティファクトを読み込む 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 入門

トラッキング UI

eval

shap

1 shap.readthedocs.io
MLflow 入門

Ayo berlatih!

MLflow 入門

Preparing Video For Download...