绝对支持定义您自己的输出。典型的 TensorFlow 训练程序将:
- 构建训练图
- 使用该图训练模型
- 构建预测图
- 导出 SavedModel
这就是例证,例如,在这个sample code中。
当您构建预测图时,您将为输入创建占位符,例如:
with tf.Graph() as prediction_graph:
# dtypes can be anything
# First dimension of shape is "batch size" which must be None
# so the system can send variable-length batches. Beyond that,
# there are no other restrictions on shape.
x = tf.placeholder(dtype=tf.int32, shape=(None,))
y = tf.placeholder(dtype=tf.float32, shape=(None,))
z = build_prediction_graph(x, y)
saver = tf.train.Saver()
当您导出 SavedModel 时,您在所谓的“签名”中声明您的输入和输出;在这个过程中,你给他们起友好的名字(字典中的键),因为 TensorFlow 确实名字修饰。这些键是您在发送数据时在 JSON 中使用的键,它们是您在预测中返回的 JSON 中的键。
例如:
# Define the inputs and the outputs.
inputs = {"x": tf.saved_model.utils.build_tensor_info(x),
"y": tf.saved_model.utils.build_tensor_info(y)}
outputs = {"z": tf.saved_model.utils.build_tensor_info(z)}
signature = tf.saved_model.signature_def_utils.build_signature_def(
inputs=inputs,
outputs=outputs,
method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME
)
使用该签名对服务的假设请求可能如下所示:
{"instances": [{"x": 6, "y": 3.14}, {"x": 3, "y": 1.0}]}
假设响应如下:
{"predictions": [{"z": [1, 2, 3]}, {"z": [4, 5, 6]}]}
最后,您需要实际保存SavedModel:
with tf.Session(graph=prediction_graph) as session:
# Restore the most recently checkpointed variables from training
saver.restore(session, tf.train.latest_checkpoint(job_dir))
# Save the SavedModel
b = builder.SavedModelBuilder('/path/to/export')
b.add_meta_graph_and_variables(session, ['serving_default'], signature)
b.save()