我最近经历了this tutorial。我有来自教程的经过训练的模型,我想用docker服务它,所以我可以向它发送一个任意字符串,并从模型中获取预测。
我还通过this tutorial了解如何使用docker服务。但我不理解模型是如何保存的,具有接受输入参数的能力。例如:
curl -d '{"instances": [1.0, 2.0, 5.0]}' \
-X POST http://localhost:8501/v1/models/half_plus_two:predict
half_plus_two
模型如何知道如何处理instances
param?
在文本生成教程中,有一个名为generate_text
的方法可以处理生成预测。
def generate_text(model, start_string):
# Evaluation step (generating text using the learned model)
# Number of characters to generate
num_generate = 1000
# Converting our start string to numbers (vectorizing)
input_eval = [char2idx[s] for s in start_string]
input_eval = tf.expand_dims(input_eval, 0)
# Empty string to store our results
text_generated = []
# Low temperatures results in more predictable text.
# Higher temperatures results in more surprising text.
# Experiment to find the best setting.
temperature = 1.0
# Here batch size == 1
model.reset_states()
for i in range(num_generate):
predictions = model(input_eval)
# remove the batch dimension
predictions = tf.squeeze(predictions, 0)
# using a multinomial distribution to predict the word returned by the model
predictions = predictions / temperature
predicted_id = tf.multinomial(predictions, num_samples=1)[-1,0].numpy()
# We pass the predicted word as the next input to the model
# along with the previous hidden state
input_eval = tf.expand_dims([predicted_id], 0)
text_generated.append(idx2char[predicted_id])
return (start_string + ''.join(text_generated))
如何从文本生成教程中提供训练模型,并将模型api的输入参数映射到generate_text
等独特方法?例如:
curl -d '{"start_string": "ROMEO: "}' \
-X POST http://localhost:8501/v1/models/text_generation:predict
注意:完全和广泛地回答这个问题需要深入研究Serving架构,它的API以及它们如何与模型的签名交互。我将跳过所有这些以使答案保持可接受的长度,但如果有必要,我可以随时扩展过于模糊的部分(如果是这样的话,请留下评论)。
half_plus_two模型如何知道如何处理实例参数?
由于几个未提及的原因堆积起来,使这个方便简短的例子,如果只有IMO有点误导。
1)instances
参数来自哪里? RESTful API的Predict API定义具有预定义的请求格式,在其两种可能的形式之一中,采用一个instances
参数。
2)instances
参数映射到什么?我们不知道。对于只有一个输入的SignatureDefs,非常特定的调用格式的instances
直接映射到输入,而不需要指定输入的键(see section "Specifying input tensors in row format" in the API specs)。
因此,会发生的情况是:只对一个输入定义的模型发出POST请求。 TF服务获取该输入并将其提供给模型,运行它直到它具有模型签名的“输出”部分中定义的张量的所有值,并为“输出”中的每个键返回一个带有key:result
项的JSON对象“清单。
如何从文本生成教程中提供训练模型,并将模型api的输入参数映射到独特的方法,如generate_text?
你不能(至少不直接将函数映射到Serving方法)。服务基础结构公开了一些预定义的方法(regress
,predict
,classify
),这些方法知道如何解释签名以生成通过运行模型的特定子图所请求的输出。这些子图必须包含在SavedModel中,因此例如使用tf.py_func
将不起作用。
你最好的机会是尝试将文本生成描述为TF子图(即仅使用TF操作)并编写一个单独的SignatureDef,它将起始字符串和num_generate
作为输入。