RESTful API以标准的HTTP POST方法进行交互,请求和回复均为JSON对象。为了调用服务器端的模型,我们在客户端向服务器发送以下格式的请求:

    服务器URI:

    请求内容:

    回复为:

    1. {
    2. "predictions": 返回值
    3. }

    输出:

    1. [7 2 1 0 4 1 4 9 6 9]
    2. [7 2 1 0 4 1 4 9 5 9]

    可见预测结果与真实标签值非常接近。

    对于自定义的Keras模型,在发送的数据中加入 键值即可,即将上面代码的 data 建立过程改为

    Node.js客户端示例(Ziyang)

    以下示例使用 Node.js 将下图转换为28*28的灰度图,发送给本机的TensorFlow Serving服务器,并输出返回的预测值和概率。(其中使用了 和 HTTP库superagent ,可使用 和 npm install superagent 安装)

    1. const Jimp = require('jimp')
    2. const superagent = require('superagent')
    3.  
    4. const url = 'http://localhost:8501/v1/models/MLP:predict'
    5.  
    6. const getPixelGrey = (pic, x, y) => {
    7. const pointColor = pic.getPixelColor(x, y)
    8. const { r, g, b } = Jimp.intToRGBA(pointColor)
    9. return [ gray / 255 ]
    10. }
    11.  
    12. const getPicGreyArray = async (fileName) => {
    13. const pic = await Jimp.read(fileName)
    14. const resizedPic = pic.resize(28, 28)
    15. const greyArray = []
    16. for ( let i = 0; i< 28; i ++ ) {
    17. let line = []
    18. for (let j = 0; j < 28; j ++) {
    19. line.push(getPixelGrey(resizedPic, j, i))
    20. }
    21. console.log(line.map(_ => _ > 0.3 ? ' ' : '1').join(' '))
    22. greyArray.push(line)
    23. }
    24. }
    25.  
    26. const evaluatePic = async (fileName) => {
    27. const arr = await getPicGreyArray(fileName)
    28. const result = await superagent.post(url)
    29. .send({
    30. instances: [arr]
    31. })
    32. result.body.predictions.map(res => {
    33. const sortedRes = res.map((_, i) => [_, i])
    34. .sort((a, b) => b[0] - a[0])
    35. console.log(`我们猜这个数字是${sortedRes[0][1]},概率是${sortedRes[0][0]}`)
    36. })
    37. }
    38.  

    运行结果为:

    可见输出结果符合预期。

    注解

    如果你不熟悉HTTP POST,可以参考 。事实上,当你在用浏览器填写表单(比方说性格测试)并点击“提交”按钮,然后获得返回结果(比如说“你的性格是ISTJ”)时,就很有可能是在向服务器发送一个HTTP POST请求并获得了服务器的回复。

    关于TensorFlow Serving的RESTful API的完整使用方式可参考 文档