使用TensorFlow C++ API构建线上预测服务

使用TensorFlow C++ API构建线上预测服务

运行环境:CentOS,TF-1.10

除了本机的tensorflow之外,仍需要安装下面的tf。

源码安装后,看到tensorflow/contrib/makefile/gen/lib/libtensorflow-core.a静态库和 tensorflow/contrib/makefile/gen/bin/benchmark可执行文件

运行示例:

1.mkdir -p ~/graphs
2.curl -o ~/graphs/inception.zip
https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
&& unzip ~/graphs/inception.zip -d ~/graphs/inception

3.tensorflow/contrib/makefile/gen/bin/benchmark
–graph=$HOME/graphs/inception/tensorflow_inception_graph.pb
能执行,不报错,即安装成功。

接下来,github上有两个示例可以试着运行下
参考https://github.com/formath/tensorflow-predictor-cpp.git的2)模块,可将其中Simple Model使用C++ AIP进行预测服务,Deep CTR Model报错如下:
Not found: Op type not registered ‘HashTableV2’ in binary running on gpu47. Make sure the Op and Kernel are registered in the binary running in this process. Note that if you are loading a saved graph which used ops from tf.contrib, accessing (e.g.) tf.contrib.resampler should be done before importing the graph, as contrib ops are lazily registered when the module is first accessed.
未解决。网上查资料,可能是tf版本的缘故。不过对我们的模型没什么影响。按照以下步骤即可:

步骤:
1.Freeze Graph。拿到tf保存的4个模型文件:checkpoint、ckpt(meta、data、index),利用freeze_graph.py ,构建pb文件。具体如下:

python …/…/python/freeze_graph.py
–checkpoint_dir=’./checkpoint’
–output_node_names=‘predict/add’
–output_dir=’./model’
参数说明:checkpoint_dir为checkpoint文件的路径名称,而非文件,output_node_names为op节点名称(一般取前向的最后一步操作,视情况而定),output_dir为pb文件的保存路径。

2.编写CPP文件,读取pb图,构建输入和输出的结构,并进行编译。

具体示例:
因为github上的示例错误不能解决,我自己编写了一个示例,用来帮助理解。
使用mnist手写数字的数据集,编写了一个数字识别的例子。

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import sys

mnist = input_data.read_data_sets(‘MNIST_data/’,one_hot=True)
print(mnist.train.images.shape,mnist.train.labels.shape)
print(mnist.test.images.shape,mnist.test.labels.shape)
print(mnist.validation.images.shape,mnist.validation.labels.shape)

sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32,[None,784])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x,W)+b)
y_ = tf.placeholder(tf.float32,[None,10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))
saver = tf.train.Saver()
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
with tf.Session() as session:
tf.global_variables_initializer().run()
for i in range(1000):
batch_xs,batch_ys = mnist.train.next_batch(100)
train_step.run({x:batch_xs,y_:batch_ys})
if i%100 == 0:
saver.save(session,’./model.ckpt’)
print(‘model saved’)

上面是手写数字识别的TF代码。训练后可得到model.ckpt.data-00000-of-00001、model.ckpt.index、model.ckpt.meta、checkpoint四个文件。

freeze_graph过程:

python freeze_graph.py
–checkpoint_dir=’./’
–output_node_names=‘Softmax’
–output_dir=’./’
得到freeze_graph.pb文件。
此处若出现:init_all_tables节点没有的情况,只需修改freeze_graph.py,找到第63行 output_node_names = ‘init_all_tables,’ + output_node_names,删除即可。

编写CPP代码:

#include
#include
#include
#include
#include
#include
#include <unordered_map>
#include “util.h”
#include “tensorflow/core/public/session.h”
#include “tensorflow/core/platform/env.h”
#include “tensorflow/core/framework/tensor.h”
#include “tensorflow/core/util/sparse/sparse_tensor.h”
#include “tensorflow/core/framework/tensor_testutil.h”
#include “tensorflow/core/framework/types.h”
#include “tensorflow/core/framework/tensor.pb.h”
#include “tensorflow/core/framework/variant_encode_decode.h”
#include “tensorflow/core/framework/variant_tensor_data.h”
#include “tensorflow/core/lib/strings/strcat.h”
#include “tensorflow/core/platform/logging.h”
#include “tensorflow/core/platform/test.h”
#include “tensorflow/core/platform/test_benchmark.h”

using namespace tensorflow;
//using namespace std;

int main(int argc, char* argv[]) {
// Initialize a tensorflow session
Session* session;
Status status = NewSession(SessionOptions(), &session);
if (!status.ok()) {
std::cerr << status.ToString() << “\n”;
return 1;
} else {
std::cout << “Session created successfully” << std::endl;
}

// Load graph protobuf
GraphDef graph_def;
std::string graph_path = argv[1];
status = ReadBinaryProto(Env::Default(), graph_path, &graph_def);
if (!status.ok()) {
std::cerr << status.ToString() << std::endl;
return 1;
} else {
std::cout << “Load graph protobuf successfully” << std::endl;
}

// Add the graph to the session
status = session->Create(graph_def);
if (!status.ok()) {
std::cerr << status.ToString() << std::endl;
return 1;
} else {
std::cout << “Add graph to session successfully” << std::endl;
}
// Setup inputs and outputs
//std::vector<std::pair<std::string, Tensor> > inputs;
std::vector kkk;
//std::cout<<‘1’<<std::endl;
std::ifstream myfile("/data/liusijia/tensorflow-predictor-cpp/src/xiangsu_1.txt");
//std::cout<<myfile<<std::endl;
std::string temp;
//std::cout<<‘2’<<std::endl;
float num;
for (int i = 0; i < 784; i++)
{
getline(myfile,temp);
num = atof(temp.c_str());
kkk.push_back(num);
}
myfile.close();
auto kkk_tensor = test::AsTensor(kkk,{1,784}); //容器转换为Tensor的操作,{}中数字代表维度
//构建输入,输入的名称要与图的op相对应
std::vector<std::pair<std::string, Tensor> > inputs = {
{“Placeholder”,kkk_tensor},
};

std::vectortensorflow::Tensor outputs; //构建输出

status = session->Run(inputs,{“Softmax”},{},&outputs);
if (!status.ok()) {
std::cerr << status.ToString() << std::endl;
return 1;
}
else{
std::cout << “Run session successfully” << std::endl;
}

auto softmax = outputs[0].tensor<float,2>();

std::cout << outputs[0].DebugString() << std::endl;
std::cout << "output value: " << softmax << std::endl;
session->Close();

return 0;

}
压缩包中提供了xiangsu_1.txt,文件中存储了数字0的图像784个像素点。
注意:inputs中的“Placehoder”是本图中输入数据的op。实际使用时,要根据自己图的op名称进行修改。session—>Run中的Softmax同理。
编译cc文件:我是仿照上面提到的github项目,在src文件夹中CMakelist里加入了自己模型的路径。我的cc文件名字为rhn.cc

cd到build文件夹里,make。可得到自己cc文件的编译后的bin。
输入下面命令或者写成脚本:

运行,可得到以下输出:

output value为输出的softmax结果,对应着session->Run中的“Softmax”。可看到识别结果为数字0,与真实结果一致。

猜你喜欢

转载自blog.csdn.net/lsj1342/article/details/82752951