我已经导出了一个SavedModel
,现在我将其加载并进行预测。它经过培训,具有以下功能和标签:
F1 : FLOAT32
F2 : FLOAT32
F3 : FLOAT32
L1 : FLOAT32
所以说我想在20.9, 1.8, 0.9
值中输入单个FLOAT32
预测。我该如何做到这一点?我已成功加载模型,但我不知道如何访问它来进行预测调用。
with tf.Session(graph=tf.Graph()) as sess:
tf.saved_model.loader.load(
sess,
[tf.saved_model.tag_constants.SERVING],
"/job/export/Servo/1503723455"
)
# How can I predict from here?
# I want to do something like prediction = model.predict([20.9, 1.8, 0.9])
这个问题与here发布的问题不重复。这个问题集中在对任何模型类(不仅限于SavedModel
)的tf.estimator
和指定输入和输出节点名称的语法进行推理的最小示例。
假设您想要在Python中进行预测,SavedModelPredictor可能是加载SavedModel并获得预测的最简单方法。假设您保存模型,如下所示:
# Build the graph
f1 = tf.placeholder(shape=[], dtype=tf.float32)
f2 = tf.placeholder(shape=[], dtype=tf.float32)
f3 = tf.placeholder(shape=[], dtype=tf.float32)
l1 = tf.placeholder(shape=[], dtype=tf.float32)
output = build_graph(f1, f2, f3, l1)
# Save the model
inputs = {'F1': f1, 'F2': f2, 'F3': f3, 'L1': l1}
outputs = {'output': output_tensor}
tf.contrib.simple_save(sess, export_dir, inputs, outputs)
(输入可以是任何形状,甚至不必是图中的占位符或根节点)。
然后,在将使用SavedModel
的Python程序中,我们可以得到如下预测:
from tensorflow.contrib import predictor
predict_fn = predictor.from_saved_model(export_dir)
predictions = predict_fn(
{"F1": 1.0, "F2": 2.0, "F3": 3.0, "L1": 4.0})
print(predictions)
This answer展示了如何在Java,C ++和Python中进行预测(尽管问题集中在Estimators上,但答案实际上与SavedModel
的创建无关)。
对于任何需要保存训练有素的罐装模型并在没有张量流服务的情况下提供服务的工作示例的人,我在此处记录了https://github.com/tettusud/tensorflow-examples/tree/master/estimators
tf.tensorflow.contrib.predictor.from_saved_model( exported_model_path)
创建预测器tf.train.Example(
features= tf.train.Features(
feature={
'x': tf.train.Feature(
float_list=tf.train.FloatList(value=[6.4, 3.2, 4.5, 1.5])
)
}
)
)
这里x
是导出时input_receiver_function中给出的输入的名称。例如:
feature_spec = {'x': tf.FixedLenFeature([4],tf.float32)}
def serving_input_receiver_fn():
serialized_tf_example = tf.placeholder(dtype=tf.string,
shape=[None],
name='input_tensors')
receiver_tensors = {'inputs': serialized_tf_example}
features = tf.parse_example(serialized_tf_example, feature_spec)
return tf.estimator.export.ServingInputReceiver(features, receiver_tensors)
加载图形后,它在当前上下文中可用,您可以通过它提供输入数据以获得预测。每个用例都有很大不同,但是对代码的添加看起来像这样:
with tf.Session(graph=tf.Graph()) as sess:
tf.saved_model.loader.load(
sess,
[tf.saved_model.tag_constants.SERVING],
"/job/export/Servo/1503723455"
)
prediction = sess.run(
'prefix/predictions/Identity:0',
feed_dict={
'Placeholder:0': [20.9],
'Placeholder_1:0': [1.8],
'Placeholder_2:0': [0.9]
}
)
print(prediction)
在这里,您需要知道预测输入的名称。如果你没有在你的serving_fn
给他们一个中殿,那么他们默认为Placeholder_n
,其中n
是第n个特征。
sess.run
的第一个字符串参数是预测目标的名称。这将根据您的使用情况而有所不同。
tf.estimator.DNNClassifier
的构造函数有一个名为warm_start_from
的参数。你可以给它SavedModel
文件夹名称,它将恢复你的会话。