创建自定义模型:“加N”模型
下载此Notebook 我们的第一个示例简单但具有启发性。我们将创建一个模型,该模型将指定的数值 n 加到 Pandas DataFrame 输入的所有列上。这将演示定义自定义模型、保存它、重新加载它以及进行预测的过程。
步骤 1:定义模型类
我们首先定义模型的 Python 类。此类应继承自 mlflow.pyfunc.PythonModel 并实现必要的方法。
import mlflow.pyfunc
class AddN(mlflow.pyfunc.PythonModel):
  """
  A custom model that adds a specified value `n` to all columns of the input DataFrame.
  Attributes:
  -----------
  n : int
      The value to add to input columns.
  """
  def __init__(self, n):
      """
      Constructor method. Initializes the model with the specified value `n`.
      Parameters:
      -----------
      n : int
          The value to add to input columns.
      """
      self.n = n
  def predict(self, context, model_input, params=None):
      """
      Prediction method for the custom model.
      Parameters:
      -----------
      context : Any
          Ignored in this example. It's a placeholder for additional data or utility methods.
      model_input : pd.DataFrame
          The input DataFrame to which `n` should be added.
      params : dict, optional
          Additional prediction parameters. Ignored in this example.
      Returns:
      --------
      pd.DataFrame
          The input DataFrame with `n` added to all columns.
      """
      return model_input.apply(lambda column: column + self.n)
步骤 2:保存模型
现在模型类已定义,我们可以使用 MLflow 实例化并保存它。
# Define the path to save the model
model_path = "/tmp/add_n_model"
# Create an instance of the model with `n=5`
add5_model = AddN(n=5)
# Save the model using MLflow
mlflow.pyfunc.save_model(path=model_path, python_model=add5_model)
/Users/benjamin.wilson/miniconda3/envs/mlflow-dev-env/lib/python3.8/site-packages/_distutils_hack/__init__.py:30: UserWarning: Setuptools is replacing distutils.
warnings.warn("Setuptools is replacing distutils.")
步骤 3:加载模型
保存模型后,我们可以使用 MLflow 将其重新加载,然后用于预测。
# Load the saved model
loaded_model = mlflow.pyfunc.load_model(model_path)
步骤 4:评估模型
现在,让我们使用加载的模型对样本输入进行预测,并验证其正确性。
import pandas as pd
# Define a sample input DataFrame
model_input = pd.DataFrame([range(10)])
# Use the loaded model to make predictions
model_output = loaded_model.predict(model_input)
model_output
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 
结论
这个简单的示例演示了 MLflow 自定义 pyfunc 的强大功能和灵活性。通过封装任意 Python 代码及其依赖项,自定义 pyfunc 模型可确保为各种用例提供一致且统一的接口。无论您是使用小众的机器学习框架、需要自定义预处理步骤,还是想集成独特的预测逻辑,pyfunc 都是完成这项工作的工具。