怎样向一个已启动的 MLflow 模型服务请求预测?
查看完整题解
参考回答
直接回答
本地 MLflow 推理服务通常用 HTTP POST 调用 /invocations。请求内容要符合模型签名和所用服务支持的 JSON 格式,例如带列和值的 dataframe_split。
讲清原理
先检查 HTTP 状态,再解析预测结果。出错时核对列名、类型和载荷层级。写批量调用时也要确认输入行和输出的对应关系。
例子与易错点
示例向真实的本地模型端点发送两笔金额,检查返回的两条结果按输入顺序排列。
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"],
)
from contextlib import contextmanager
from urllib.request import urlopen
from urllib.error import URLError
import socket
import subprocess
import time
@contextmanager
def serve_on_loopback(directory):
with socket.socket() as locator:
locator.bind(("127.0.0.1", 0))
port = locator.getsockname()[1]
url = f"http://127.0.0.1:{port}"
log = root / "server.log"
with log.open("w") as output:
process = subprocess.Popen(
["mlflow", "models", "serve", "-m", str(directory), "--host", "127.0.0.1",
"--port", str(port), "--env-manager", "local", "--workers", "1"],
stdout=output, stderr=subprocess.STDOUT,
)
try:
for _ in range(100):
if process.poll() is not None:
raise RuntimeError(log.read_text())
try:
with urlopen(url + "/ping", timeout=1) as response:
if response.status == 200:
break
except (URLError, TimeoutError):
time.sleep(0.2)
else:
raise RuntimeError(log.read_text())
yield url
finally:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
from urllib.request import Request
import json
payload = {"dataframe_split": {"columns": ["amount"], "data": [[3.0], [8.0]]}}
with serve_on_loopback(directory) as url:
req = Request(url + "/invocations", data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"})
with urlopen(req, timeout=5) as response:
predictions = json.load(response)["predictions"]
assert predictions == [{"total": 6.0}, {"total": 16.0}]
print("endpoint returned totals 6.0 and 16.0")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。