通过REST API查询

Note

REST API非常好用和简单,当输入和输出不太大时,它可以很好的工作。
这里我们使用python的requests模块发送请求。

准备好数据

import utils

(X_train, y_train), (X_val, y_val), (X_test, y_test) = utils.load_fashion_mnist()
# 假设X_new是要预测的数据
X_new = X_test[:3]
import json

# REST API是基于JSON的
input_data_json = json.dumps({
    # 函数签名为模型的默认服务函数,可以用来做预测
    "signature_name": "serving_default",
    # 必须把numpy数组转化为python列表
    "instances": X_new.tolist(),
})

请求

import requests

# TF Serving使用8501端口为REST API服务
SERVER_URL = 'http://localhost:8501/v1/models/serve_mnist:predict'
# 发送POST请求,获取请求结果
response = requests.post(SERVER_URL, data=input_data_json)
# raise an exception in case of error
response.raise_for_status()
response = response.json()
import numpy as np

# response是一个包含`predictions`键的字典
y_proba = np.array(response["predictions"])
# as expected
y_proba.round(2)
array([[0.  , 0.  , 0.  , 0.  , 0.  , 0.  , 0.  , 0.03, 0.  , 0.97],
       [0.  , 0.  , 0.99, 0.  , 0.  , 0.  , 0.01, 0.  , 0.  , 0.  ],
       [0.  , 1.  , 0.  , 0.  , 0.  , 0.  , 0.  , 0.  , 0.  , 0.  ]])