最近一段時間研究了如何打通tensorflow線下使用python訓練深度學習模型,然后線上使用c++調用預先訓練好的模型完成預測的流程。畢竟深度學習模型上線是需要考慮效率的,目前來說c++的效率還是python所不能比的。
這篇文章基于tensorflow 1.2版本寫的,tensorflow 1.2版本及以上提供了一種更加方便的c++ API調用python API訓練好的模型。但這方面的資料比較少,自己也踩了不少坑,于是寫了一個簡單的使用tensorflow c++ API調用線下python API訓練好的模型的demo,以及如何配置環境和編譯。
大體的流程如下:
- 1.使用tensorflow python API編寫和訓練自己的模型,訓練完成后,使用tensorflow saver 將模型保存下來。
- 2.使用tensorflow c++ API 構建新的session,讀取python版本保存的模型,然后使用session->run()獲得模型的輸出。
- 3.編譯和運行基于tensorflow c++ API寫的代碼。
安裝Bazel
Bazel是一個類似于Make的工具,是Google為其內部軟件開發的特點量身定制的工具,如今Google使用它來構建內部大多數的軟件。
在編譯 tensorflow c++的時候,需要利用bazel來進行編譯的,理論上是可以使用Cmake等其工具來編譯的,但是我嘗試了好久沒有成功,所以最后還是使用了google的bazel進行編譯。希望有大神可以把編譯方法告訴我~
安裝方法按照官方教程走就行。我采用的是直接編譯二進制文件的方法,這個最簡單直接,首先下載對應版本的二進制文件,然后執行下面的命令即可:
$ chmod +x bazel-version-installer-os.sh
$ ./bazel-version-installer-os.sh --user
下載Tensorflow源碼
我們需要將Tensorflow源碼下載到本地,后續編譯tensorflow c++ 代碼需要在這個目錄下進行。在這里需要說明的一點是,本文采用的c++ API載入python 預訓練模型的方法,是基于tensorflow1.2版本。所以需要下載tensorflow 1.2版本及以上,直接從github上clone即可:
$ git clone -b r1.2 https://github.com/tensorflow/tensorflow.git
使用Tensorflow Python API線下定義模型和訓練
這里的話我寫了一個十分簡單的基于tensorflow的demo:res=a*b+y
,代碼如下:
# -*-coding:utf-8 -*-
import numpy as np
import tensorflow as tf
import sys, os
if __name__ == '__main__':
train_dir = os.path.join('demo_model/', "demo")
a = tf.placeholder(dtype=tf.int32, shape=None, name='a')
b = tf.placeholder(dtype=tf.int32, shape=None, name='b')
y = tf.Variable(tf.ones(shape=[1], dtype=tf.int32), dtype=tf.int32, name='y')
res = tf.add(tf.multiply(a, b), y, name='res')
with tf.Session() as sess:
feed_dict = dict()
feed_dict[a] = 2
feed_dict[b] = 3
fetch_list = [res]
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
# 訓練和保存模型
res = sess.run(feed_dict=feed_dict, fetches=fetch_list)
saver.save(sess, train_dir)
print("result: ", res[0])
運行結果如下:
result: [7]
模型保存在了demo_model/
下,里面的包含四個文件:
checkpoint #模型checkpoint中的一些文件名的信息
demo.data-00000-of-00001 #模型中保存的各個權重
demo.index #可能是保存的各個權重的索引
demo.meta #模型構造的圖的拓撲結構
使用python API 載入和運行模型的代碼如下:
# -*- coding:utf-8 -*-
import tensorflow as tf
import os
if __name__ == '__main__':
with tf.Session() as sess:
saver = tf.train.import_meta_graph('demo_model/demo.meta')
saver.restore(sess, tf.train.latest_checkpoint('demo_model/'))
# sess.run()
graph = tf.get_default_graph()
a = graph.get_tensor_by_name("a:0")
b = graph.get_tensor_by_name("b:0")
feed_dict = {a: 2, b: 3}
op_to_restore = graph.get_tensor_by_name("res:0")
print(sess.run(fetches=op_to_restore, feed_dict=feed_dict))
運行結果如下:
[7]
使用Tensorflow c++ API讀入預訓練模型
關于tensorflow c++ API的教程網上資料真的很少,我只能一邊看著官方文檔一邊查著Stack Overflow慢慢寫了,有些API我現在也不是很清楚怎么用,直接上代碼吧:
//
// Created by MoMo on 17-8-10.
//
#include <iostream>
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/protobuf/meta_graph.pb.h"
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/tensor.h"
using namespace std;
using namespace tensorflow;
int main()
{
const string pathToGraph = "demo_model/demo.meta";
const string checkpointPath = "demo_model/demo";
auto session = NewSession(SessionOptions());
if (session == nullptr)
{
throw runtime_error("Could not create Tensorflow session.");
}
Status status;
// 讀入我們預先定義好的模型的計算圖的拓撲結構
MetaGraphDef graph_def;
status = ReadBinaryProto(Env::Default(), pathToGraph, &graph_def);
if (!status.ok())
{
throw runtime_error("Error reading graph definition from " + pathToGraph + ": " + status.ToString());
}
// 利用讀入的模型的圖的拓撲結構構建一個session
status = session->Create(graph_def.graph_def());
if (!status.ok())
{
throw runtime_error("Error creating graph: " + status.ToString());
}
// 讀入預先訓練好的模型的權重
Tensor checkpointPathTensor(DT_STRING, TensorShape());
checkpointPathTensor.scalar<std::string>()() = checkpointPath;
status = session->Run(
{{ graph_def.saver_def().filename_tensor_name(), checkpointPathTensor },},
{},
{graph_def.saver_def().restore_op_name()},
nullptr);
if (!status.ok())
{
throw runtime_error("Error loading checkpoint from " + checkpointPath + ": " + status.ToString());
}
// 構造模型的輸入,相當與python版本中的feed
std::vector<std::pair<string, Tensor>> input;
tensorflow::TensorShape inputshape;
inputshape.InsertDim(0,1);
Tensor a(tensorflow::DT_INT32,inputshape);
Tensor b(tensorflow::DT_INT32,inputshape);
auto a_map = a.tensor<int,1>();
a_map(0) = 2;
auto b_map = b.tensor<int,1>();
b_map(0) = 3;
input.emplace_back(std::string("a"), a);
input.emplace_back(std::string("b"), b);
// 運行模型,并獲取輸出
std::vector<tensorflow::Tensor> answer;
status = session->Run(input, {"res"}, {}, &answer);
Tensor result = answer[0];
auto result_map = result.tensor<int,1>();
cout<<"result: "<<result_map(0)<<endl;
return 0;
}
使用tensorflow c++ API讀入預先訓練的模型的大體的流程就是這樣 ,復雜的模型,可能會需要構造更加復雜的輸入和輸出,讀入部分一樣。
編譯和運行
代碼寫了,最后一步就是編譯和運行了。在這里我采用的是bazel進行編譯運行,這里需要寫一個BUILD
文件,內容如下:
cc_binary(
name = "demo",#目標文件名
srcs = ["demo.cc"],#源代碼文件名
deps = [
"http://tensorflow/cc:cc_ops",
"http://tensorflow/cc:client_session",
"http://tensorflow/core:tensorflow"
],
)
然后將代碼,BUILD文件一起放在我們下載下來的tensorflow的源碼的tensorflow/tensorflow/demo
目錄下,demo目錄為自己新建的。執行如下命令進行編譯運行:
bazel build -c opt --copt=-mavx --copt="-ggdb" --copt="-g3" demo/...
經過漫長的編譯過程,大概30分鐘。會在tensorflow/bazel-bin/tensorflow/demo
生成可執行文件demo,之后將我們預先訓練好的模型放入相同的目錄,運行即可,下面是運行結果:
result: 7
總結
整個tensorflow線下使用python訓練深度學習模型,然后線上使用c++調用預先訓練好的模型完成預測的流程,基本介紹完了。從這個過程可以看出tensorflow的強大之處,開發者在開發之處考慮到了落地工業界,提供了這樣一套線上和線下打通的流程,十分方便。