mlflow models predict 怎样做一批离线预测?
先说出你的答案
定义边界、关键机制、一个反例;P8题再补容量、失败与验证。
查看完整题解
参考回答
直接回答
用 mlflow models predict 指定模型、输入文件与类型,并可指定输出路径。它适合不启动长期 HTTP 服务,直接在当前或指定环境读一批数据并写出结果。
讲清原理
输入的列与类型仍要匹配模型签名。大任务可据内存和重跑成本拆批,并保留输入批号及模型版本。
例子与易错点
示例把两笔金额写到 JSON,以 CLI 运行预测,再读输出文件验证对应结果。
from pathlib import Path
from tempfile import TemporaryDirectory
import mlflow
import pandas as pd
fixture = TemporaryDirectory()
root = Path(fixture.name)
model_code = root / "order_model.py"
model_code.write_text(
"import mlflow\n"
"class OrderModel(mlflow.pyfunc.PythonModel):\n"
" def predict(self, context, model_input):\n"
" return model_input[['amount']].assign(total=model_input['amount'] * 2)[['total']]\n"
"mlflow.models.set_model(OrderModel())\n"
)
inputs = pd.DataFrame({"amount": [2.0, 5.0]})
directory = root / "order-model"
mlflow.pyfunc.save_model(
str(directory), python_model=str(model_code), input_example=inputs,
pip_requirements=["pandas"],
)
import json
import subprocess
source = root / "input.json"
output = root / "results.json"
source.write_text(json.dumps({"dataframe_split": {"columns": ["amount"], "data": [[3.0], [8.0]]}}))
subprocess.run(
["mlflow", "models", "predict", "-m", str(directory), "-i", str(source),
"-t", "json", "-o", str(output), "--env-manager", "local"],
check=True,
)
assert json.loads(output.read_text())["predictions"] == [{"total": 6.0}, {"total": 16.0}]
print("the output file contains both predictions")
和评分标准对照,你能独立回答到哪一步?
自评会安排下一次复习,不保存你的口述内容。
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。