我使用tf.estimator .method export_savedmodel保存模型,如下所示:
export_dir="exportModel/"
feature_spec = tf.feature_column.make_parse_example_spec(feature_columns)
input_receiver_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)
classifier.export_savedmodel(export_dir, input_receiver_fn, as_text=False, checkpoint_path="Model/model.ckpt-400")
如何导入此保存的模型并用于预测?
答案 0 :(得分:40)
我试图搜索一个很好的基础示例,但看起来文档和示例对于此主题来说有点分散。因此,让我们从一个基本示例开始:tf.estimator quickstart。
该特定示例实际上并未导出模型,因此我们这样做(不需要用例1):
def serving_input_receiver_fn():
"""Build the serving inputs."""
# The outer dimension (None) allows us to batch up inputs for
# efficiency. However, it also means that if we want a prediction
# for a single instance, we'll need to wrap it in an outer list.
inputs = {"x": tf.placeholder(shape=[None, 4], dtype=tf.float32)}
return tf.estimator.export.ServingInputReceiver(inputs, inputs)
export_dir = classifier.export_savedmodel(
export_dir_base="/path/to/model",
serving_input_receiver_fn=serving_input_receiver_fn)
此代码上的巨大星号:TensorFlow 1.3中似乎存在一个错误,它不允许您在" canned"上进行上述导出。估计器(例如DNNClassifier)。有关解决方法,请参阅"附录:解决方法"部分。
下面的代码引用export_dir
(导出步骤的返回值)以强调它是不" / path / to / model",而是,该目录的子目录,其名称为时间戳。
用例1:在与培训相同的过程中执行预测
这是一种sci-kit学习类型的经验,并已通过示例进行了示例。为了完整性'为此,你只需在训练有素的模型上调用predict
:
classifier.train(input_fn=train_input_fn, steps=2000)
# [...snip...]
predictions = list(classifier.predict(input_fn=predict_input_fn))
predicted_classes = [p["classes"] for p in predictions]
用例2:将SavedModel加载到Python / Java / C ++中并执行预测
Python客户端
如果你想在Python中进行预测,也许最容易使用的是SavedModelPredictor。在将使用SavedModel
的Python程序中,我们需要这样的代码:
from tensorflow.contrib import predictor
predict_fn = predictor.from_saved_model(export_dir)
predictions = predict_fn(
{"x": [[6.4, 3.2, 4.5, 1.5],
[5.8, 3.1, 5.0, 1.7]]})
print(predictions['scores'])
Java客户端
package dummy;
import java.nio.FloatBuffer;
import java.util.Arrays;
import java.util.List;
import org.tensorflow.SavedModelBundle;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
public class Client {
public static void main(String[] args) {
Session session = SavedModelBundle.load(args[0], "serve").session();
Tensor x =
Tensor.create(
new long[] {2, 4},
FloatBuffer.wrap(
new float[] {
6.4f, 3.2f, 4.5f, 1.5f,
5.8f, 3.1f, 5.0f, 1.7f
}));
// Doesn't look like Java has a good way to convert the
// input/output name ("x", "scores") to their underlying tensor,
// so we hard code them ("Placeholder:0", ...).
// You can inspect them on the command-line with saved_model_cli:
//
// $ saved_model_cli show --dir $EXPORT_DIR --tag_set serve --signature_def serving_default
final String xName = "Placeholder:0";
final String scoresName = "dnn/head/predictions/probabilities:0";
List<Tensor> outputs = session.runner()
.feed(xName, x)
.fetch(scoresName)
.run();
// Outer dimension is batch size; inner dimension is number of classes
float[][] scores = new float[2][3];
outputs.get(0).copyTo(scores);
System.out.println(Arrays.deepToString(scores));
}
}
C ++客户端
您可能希望将tensorflow::LoadSavedModel
与Session
一起使用。
#include <unordered_set>
#include <utility>
#include <vector>
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/public/session.h"
namespace tf = tensorflow;
int main(int argc, char** argv) {
const string export_dir = argv[1];
tf::SavedModelBundle bundle;
tf::Status load_status = tf::LoadSavedModel(
tf::SessionOptions(), tf::RunOptions(), export_dir, {"serve"}, &bundle);
if (!load_status.ok()) {
std::cout << "Error loading model: " << load_status << std::endl;
return -1;
}
// We should get the signature out of MetaGraphDef, but that's a bit
// involved. We'll take a shortcut like we did in the Java example.
const string x_name = "Placeholder:0";
const string scores_name = "dnn/head/predictions/probabilities:0";
auto x = tf::Tensor(tf::DT_FLOAT, tf::TensorShape({2, 4}));
auto matrix = x.matrix<float>();
matrix(0, 0) = 6.4;
matrix(0, 1) = 3.2;
matrix(0, 2) = 4.5;
matrix(0, 3) = 1.5;
matrix(0, 1) = 5.8;
matrix(0, 2) = 3.1;
matrix(0, 3) = 5.0;
matrix(0, 4) = 1.7;
std::vector<std::pair<string, tf::Tensor>> inputs = {{x_name, x}};
std::vector<tf::Tensor> outputs;
tf::Status run_status =
bundle.session->Run(inputs, {scores_name}, {}, &outputs);
if (!run_status.ok()) {
cout << "Error running session: " << run_status << std::endl;
return -1;
}
for (const auto& tensor : outputs) {
std::cout << tensor.matrix<float>() << std::endl;
}
}
使用案例3:使用TensorFlow服务模拟服务
以适合Classification model的方式导出模型要求输入为tf.Example
个对象。以下是我们如何为TensorFlow服务导出模型:
def serving_input_receiver_fn():
"""Build the serving inputs."""
# The outer dimension (None) allows us to batch up inputs for
# efficiency. However, it also means that if we want a prediction
# for a single instance, we'll need to wrap it in an outer list.
example_bytestring = tf.placeholder(
shape=[None],
dtype=tf.string,
)
features = tf.parse_example(
example_bytestring,
tf.feature_column.make_parse_example_spec(feature_columns)
)
return tf.estimator.export.ServingInputReceiver(
features, {'examples': example_bytestring})
export_dir = classifier.export_savedmodel(
export_dir_base="/path/to/model",
serving_input_receiver_fn=serving_input_receiver_fn)
有关如何设置TensorFlow服务的更多说明,请参阅TensorFlow服务文档,因此我只在此处提供客户端代码:
# Omitting a bunch of connection/initialization code...
# But at some point we end up with a stub whose lifecycle
# is generally longer than that of a single request.
stub = create_stub(...)
# The actual values for prediction. We have two examples in this
# case, each consisting of a single, multi-dimensional feature `x`.
# This data here is the equivalent of the map passed to the
# `predict_fn` in use case #2.
examples = [
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]))})),
tf.train.Example(
features=tf.train.Features(
feature={"x": tf.train.Feature(
float_list=tf.train.FloatList(value=[5.8, 3.1, 5.0, 1.7]))})),
]
# Build the RPC request.
predict_request = predict_pb2.PredictRequest()
predict_request.model_spec.name = "default"
predict_request.inputs["examples"].CopyFrom(
tensor_util.make_tensor_proto(examples, tf.float32))
# Perform the actual prediction.
stub.Predict(request, PREDICT_DEADLINE_SECS)
请注意,examples
中引用的密钥predict_request.inputs
需要与导出时serving_input_receiver_fn
中使用的密钥匹配(参见构造函数ServingInputReceiver
在那段代码中。)
附录:解决TF 1.3中的预制模型的出口
TensorFlow 1.3中似乎存在一个错误,其中固定模型无法正确导出用例2(&#34;自定义&#34;估算器不存在该问题)。这是一个解决方法,它包装了一个DNNClassifier以使工作正常,特别是对于Iris示例:
# Build 3 layer DNN with 10, 20, 10 units respectively.
class Wrapper(tf.estimator.Estimator):
def __init__(self, **kwargs):
dnn = tf.estimator.DNNClassifier(**kwargs)
def model_fn(mode, features, labels):
spec = dnn._call_model_fn(features, labels, mode)
export_outputs = None
if spec.export_outputs:
export_outputs = {
"serving_default": tf.estimator.export.PredictOutput(
{"scores": spec.export_outputs["serving_default"].scores,
"classes": spec.export_outputs["serving_default"].classes})}
# Replace the 3rd argument (export_outputs)
copy = list(spec)
copy[4] = export_outputs
return tf.estimator.EstimatorSpec(mode, *copy)
super(Wrapper, self).__init__(model_fn, kwargs["model_dir"], dnn.config)
classifier = Wrapper(feature_columns=feature_columns,
hidden_units=[10, 20, 10],
n_classes=3,
model_dir="/tmp/iris_model")
答案 1 :(得分:3)
我不认为罐装Estimators存在错误(或者更确切地说,如果有的话,它已被修复)。我能够使用Python成功导出罐装估算器模型并将其导入Java。
以下是导出模型的代码:
QProcess *maxwell_process = new QProcess;
maxwell_process->start(maxwellExePath, args);
connect(maxwell_process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
[&](int exitCode, QProcess::ExitStatus exitStatus){
printf("process stopped");
this->stopped = true;
});
t_ini = clock();
while (1) {
Sleep(100);
t_fin = clock();
secs = (double)(t_fin - t_ini);
secs = secs / CLOCKS_PER_SEC;
if (solution->getTimeOutValue() == -1) {
std::cout<<"init population time"<<std::endl;
if (this->stopped) {
disconnect(maxwell_process);
std::cout<<"init population time "<<secs<<std::endl;
solution->setTime(secs);
break;
}
} else {
if (secs > solution->getTimeOutValue()) {
disconnect(maxwell_process);
printf("timeout");
maxwell_process->kill();
solution->setTime(secs);
break;
}
}
QCoreApplication::processEvents();
}
要在Java中导入模型,我使用上面的rhaertel80提供的Java客户端代码,它可以工作。希望这也能回答Ben Fowler的上述问题。
答案 2 :(得分:0)
TensorFlow团队似乎不同意版本1.3中存在使用预设估算器导出模型的错误#2。我在这里提交了一个错误报告: https://github.com/tensorflow/tensorflow/issues/13477
我从TensorFlow收到的响应是输入必须只是单个字符串张量。似乎可能有一种方法可以使用序列化的TF.examples将多个功能合并到单个字符串张量中,但我还没有找到一个明确的方法来执行此操作。如果有人有代码显示如何做到这一点,我会很感激。
答案 3 :(得分:0)
您需要使用tf.contrib.export_savedmodel导出已保存的模型,并且需要定义输入接收器函数以将输入传递给。 稍后您可以从磁盘加载已保存的模型(通常为saved.model.pb)并提供服务。