首页 > 解决方案 > 使用 Tensorflow Serving 为 Keras 模型提供服务

问题描述

Tensorflow 1.12 发行说明指出:“Keras 模型现在可以直接导出为 SavedModel 格式(tf.contrib.saved_model.save_keras_model())并与 Tensorflow Serving 一起使用”。所以我试了一下——

我使用单行导出了一个带有此操作的简单模型。但是,Tensorflow 服务无法识别该模型。我想问题出在 docker 调用上,并且模型定义中可能缺少“signature_defs”。我将感谢有关缺少步骤的信息。

1. 训练模型并将模型导出到 TF serving

这是基于 Jason Brownlee 的第一个 NN的代码(由于其简单性而选择)

(训练数据,作为一个简短的 CSV 文件,在这里):

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.contrib.saved_model import save_keras_model
import numpy

# fix random seed for reproducibility
numpy.random.seed(7)

# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]

# create model
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Fit the model
model.fit(X, Y, epochs=150, batch_size=10)

# evaluate the model
scores = model.evaluate(X, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

# calculate predictions
predictions = model.predict(X)
# round predictions
rounded = [round(x[0]) for x in predictions]
print(rounded)

# Save the model for serving
path = '/TensorFlow_Models/Keras_serving/saved_model' # full path of where to save the model
save_keras_model(model, path)

2.设置TensorFlow服务器

服务器可以通过 docker 或它自己的构建来设置。TF 推荐使用 docker ( TF ref )。在此之后,基于TF 博客TF Serving Tutorial

  1. 安装 Docker(从这里
  2. 获取最新的 TF 服务版本:

码头工人拉张量流/服务

  1. 使用此模型激活 TF 服务(TF ref):

docker run -p 8501:8501 --name NNN --mount type=bind,source=SSS,target=TTT -e MODEL_NAME=MMM -t tensorflow/serving &

如果有人可以确认,我会很高兴:

3. 客户

服务器可以通过 gRPC 或 RESTful API 获取请求。假设我们使用 RESTful API,可以使用 curl 访问模型(这里是一个 TF 示例)。但是我们如何设置模型的输入/输出呢?需要 SignatureDefs ( ref ) 吗?

总而言之,虽然“Keras 模型现在可以直接导出为 SavedModel 格式(tf.contrib.saved_model.save_keras_model())并与 Tensorflow Serving 一起使用”,如 TF1.12 发行说明中所述,但还有一条路要走为了真正为模型服务。我会很高兴有关于完成这个的想法。

标签: pythontensorflowkerastensorflow-serving

解决方案


You are all correct about NNN and SSS. NNN can be arbitrary, if not specified, docker will give it a random name.

For MMM, better give it a meaningful name.

For TTT this is general about docker run command, and you can refer docker doc. This is where you map(bind) SSS inside the container, usually set to /models/$MODEL_NAME. If you get into this container and open /models/$MODEL_NAME, you will see the version folder(s) just as in SSS.

The input of RESTful API is the same as the input to the model in TensorFlow code, in your example is X = dataset[:,0:8].

If you didn't define signature when saving the model like the example in doc, then it's not necessary in serving.


推荐阅读