使用Python客户端

简介

我们要访问TensorFlow serving服务,Python应用也需要实现对应的gRPC客户端。

TensorFlow serving官方文档提供了生成mnist Python客户端的例子,但由于依赖bazel编译,编译出来的Python脚本不能直接运行。

完整例子

这里提供一个Python gRPC客户端例子,手动生成proto代码,没有任何依赖可以直接运行 https://github.com/tobegit3hub/deep_recommend_system/tree/master/python_predict_client

  1. ./predict_client.py --host 127.0.0.1 --port 9000 --model_name linear --model_version 1

不同模型的输入格式不同,我们只需要直接修改Python脚本中构建TensorProto的代码即可,建议使用该项目编译生成的文件和代码例子。

实现原理

实现Python gRPC客户端,我们需要编译TensorFlow serving和TensorFlow的proto文件,由于官方项目依赖bazel编译,我们需要修改proto文件中的依赖路径。

编译生成的Python文件可以直接import,然后参考TensorFlow的文档生成TensorProto对象,参考gRPC的文档调用gRPC服务端即可。

读取图片文件生成TesorProto

在图像分类等场景,我们需要将图片转成numpy或者TensorProto对象,才能通过gRPC请求TensorFlow serving服务,这里提供使用scipy ndimage的例子,测试已经支持jpg和png文件。

这里提供一个完整的使用CNN训练图像分类模型,然后使用Python客户端加载jpg或png文件进行预测的例子 https://github.com/tobegit3hub/deep_cnn/blob/master/python_predict_client/predict_client.py

  1. from scipy import ndimage
  2. # Create numpy ndarray for batch images
  3. features = np.ndarray(shape=(5, 32, 32, 3), dtype=np.float32)
  4. image_filepaths = ["../data/inference/Blastoise.png",
  5. "../data/inference/Charizard.png",
  6. "../data/inference/Mew.png",
  7. "../data/inference/Pikachu.png",
  8. "../data/inference/Venusaur.png"]
  9. for index, image_filepath in enumerate(image_filepaths):
  10. image_ndarray = ndimage.imread(image_filepaths[0], mode="RGB")
  11. features[index] = image_ndarray
  12. # Create TensorProto
  13. features_tensor_proto = tf.contrib.util.make_tensor_proto(features,
  14. dtype=tf.float32)

原文: http://docs.api.xiaomi.com/cloud-ml/modelservice/0902_use_python_client.html